context-mode 1.0.134 → 1.0.136

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.codex-plugin/hooks.json +65 -0
  4. package/.codex-plugin/mcp.json +9 -0
  5. package/.codex-plugin/plugin.json +31 -0
  6. package/.openclaw-plugin/openclaw.plugin.json +1 -1
  7. package/.openclaw-plugin/package.json +1 -1
  8. package/README.md +60 -12
  9. package/build/adapters/detect.d.ts +3 -1
  10. package/build/adapters/detect.js +7 -2
  11. package/build/adapters/pi/mcp-bridge.d.ts +44 -0
  12. package/build/adapters/pi/mcp-bridge.js +149 -3
  13. package/build/cli.js +17 -0
  14. package/build/lifecycle.d.ts +13 -13
  15. package/build/lifecycle.js +14 -14
  16. package/build/runtime.js +8 -5
  17. package/build/session/analytics.d.ts +0 -13
  18. package/build/session/analytics.js +50 -1
  19. package/build/session/extract.js +39 -1
  20. package/build/util/claude-config.d.ts +12 -6
  21. package/build/util/claude-config.js +16 -23
  22. package/cli.bundle.mjs +135 -133
  23. package/configs/kilo/kilo.json +9 -2
  24. package/configs/opencode/opencode.json +9 -2
  25. package/hooks/codex/platform.mjs +1 -0
  26. package/hooks/codex/posttooluse.mjs +1 -0
  27. package/hooks/codex/precompact.mjs +1 -0
  28. package/hooks/codex/pretooluse.mjs +1 -0
  29. package/hooks/codex/sessionstart.mjs +24 -1
  30. package/hooks/codex/stop.mjs +1 -0
  31. package/hooks/codex/userpromptsubmit.mjs +1 -0
  32. package/hooks/core/platform-detect.mjs +1 -1
  33. package/hooks/core/routing.mjs +112 -10
  34. package/hooks/ensure-deps.mjs +14 -3
  35. package/hooks/normalize-hooks.mjs +5 -2
  36. package/hooks/security.bundle.mjs +1 -1
  37. package/hooks/session-extract.bundle.mjs +2 -2
  38. package/openclaw.plugin.json +1 -1
  39. package/package.json +2 -1
  40. package/scripts/heal-installed-plugins.mjs +67 -0
  41. package/server.bundle.mjs +99 -99
  42. package/start.mjs +73 -11
  43. package/build/openclaw-plugin.d.ts +0 -130
  44. package/build/openclaw-plugin.js +0 -626
  45. package/build/opencode-plugin.d.ts +0 -122
  46. package/build/opencode-plugin.js +0 -372
  47. package/build/pi-extension.d.ts +0 -14
  48. package/build/pi-extension.js +0 -451
  49. package/build/util/db-lock.d.ts +0 -65
  50. package/build/util/db-lock.js +0 -166
package/cli.bundle.mjs CHANGED
@@ -1,38 +1,42 @@
1
1
  #!/usr/bin/env node
2
- var IT=Object.create;var Tl=Object.defineProperty;var AT=Object.getOwnPropertyDescriptor;var NT=Object.getOwnPropertyNames;var DT=Object.getPrototypeOf,MT=Object.prototype.hasOwnProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),ze=(t,e)=>{for(var r in e)Tl(t,r,{get:e[r],enumerable:!0})},jT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of NT(e))!MT.call(t,s)&&s!==r&&Tl(t,s,{get:()=>e[s],enumerable:!(n=AT(e,s))||n.enumerable});return t};var No=(t,e,r)=>(r=t!=null?IT(DT(t)):{},jT(e||!t||!t.__esModule?Tl(r,"default",{value:t,enumerable:!0}):r,t));var Nl=M((BU,h_)=>{"use strict";var Al={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)},GT={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?Al.up():"");return t&&(e+=Al.left),e}};h_.exports={cursor:Al,scroll:WT,erase:GT,beep:"\x07"}});var S_=M(($H,Ul)=>{var Ea=process||{},v_=Ea.argv||[],wa=Ea.env||{},bP=!(wa.NO_COLOR||v_.includes("--no-color"))&&(!!wa.FORCE_COLOR||v_.includes("--color")||Ea.platform==="win32"||(Ea.stdout||{}).isTTY&&wa.TERM!=="dumb"||!!wa.CI),vP=(t,e,r=t)=>n=>{let s=""+n,o=s.indexOf(e,t.length);return~o?t+xP(s,e,r,o)+e:t+s+e},xP=(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)},x_=(t=bP)=>{let e=t?vP:()=>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")}};Ul.exports=x_();Ul.exports.createColors=x_});import{execFileSync as k_,execSync as jo}from"node:child_process";import{existsSync as $a}from"node:fs";function kP(t){let e=t.split(/[\\/]/),r=e[e.length-1];return SP.test(r)}function Je(t){try{let e=zo?`where ${t}`:`command -v ${t}`;return jo(e,{stdio:"pipe"}),!0}catch{return!1}}function Hl(t){if(zo)try{let r=jo(`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(!Je(t))return!1;try{return zo?jo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):k_(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function w_(){if(Je("bun"))return!0;for(let t of E_())if($a(t))return!0;return!1}function wP(){for(let e of E_())if($a(e))return e;if(Je("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return zo?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function E_(){let t=process.env.HOME??process.env.USERPROFILE??"";if(zo){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 EP(){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=jo("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 zt(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return jo(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return k_(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function Ts(){let e=w_()?wP():null,r=process.env.SHELL,n=r&&$a(r)&&kP(r)?r:null,s=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(Je("tsx")?"tsx":Je("ts-node")?"ts-node":null),python:Hl("python3")?"python3":Hl("python")?"python":Hl("py")?"py":null,shell:n??(s?EP()??(Je("sh")?"sh":Je("powershell")?"powershell":"cmd.exe"):Je("bash")?"bash":"sh"),ruby:Je("ruby")?"ruby":null,go:Je("go")?"go":null,rust:Je("rustc")?"rustc":null,php:Je("php")?"php":null,perl:Je("perl")?"perl":null,r:Je("Rscript")?"Rscript":Je("r")?"r":null,elixir:Je("elixir")?"elixir":null,csharp:Je("dotnet-script")?"dotnet-script":null}}function Cn(){return w_()}function Ta(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${zt(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${zt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${zt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${zt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${zt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${zt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${zt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${zt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${zt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${zt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${zt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${zt(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
3
- `)}function Pa(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function $_(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];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var SP,zo,Ra=x(()=>{"use strict";SP=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i;zo=process.platform==="win32"});function xe(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}function Ca(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}var Sr=x(()=>{"use strict"});function $P(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 TP(t){let e=Ca(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function Oa(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 $P(o)){let a=TP(i);a&&r.add(a)}return[...r]}var Zl=x(()=>{"use strict";Sr()});import{resolve as Lo}from"node:path";import{homedir as Bl}from"node:os";import{createRequire as PP}from"node:module";function Be(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Lo(Bl(),e.replace(/^~[/\\]?/,"")):Lo(e):Lo(Bl(),".claude")}function RP(t=process.env){return Lo(Be(t),"settings.json")}function ql(t=process.env){let e=[],r=null,n=null;try{let i=PP(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(Lo(Bl(),...o,"settings.json"))}let s=RP(t);return e.includes(s)||e.push(s),e}var tn=x(()=>{"use strict"});var T_={};ze(T_,{discoverSiblingMcpPids:()=>Ia,killSiblingMcpServers:()=>Aa,startupSiblingSweep:()=>FP});import{execFileSync as Vl}from"node:child_process";function IP(t){try{let e=Vl("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=Number.parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function AP(t){try{let e=Vl("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").ParentProcessId`],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=Number.parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function NP(t){return process.platform==="win32"?AP(t):IP(t)}function zP(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=r.trim();if(!n||!/^\d+$/.test(n))continue;let s=Number.parseInt(n,10);Number.isFinite(s)&&s>0&&e.add(s)}return[...e]}function Ia(t){let e=t.platform??process.platform,r=t.runCommand??DP,n="";try{e==="win32"?n=r("powershell",["-NoProfile","-Command",OP]):n=r("pgrep",["-f",CP])}catch{return[]}let s=zP(n).filter(i=>i!==t.ownPid&&i!==t.ownPpid);if(!t.sameParentOnly)return s;let o=t.readPpid??NP;return s.filter(i=>{let a=o(i);return Number.isFinite(a)&&a===t.ownPpid})}function LP(t){return new Promise(e=>{setTimeout(e,t)})}async function Aa(t){let e=t.timeoutMs??1500,r=t.pollIntervalMs??100,n=t.isAlive??MP,s=t.sendSignal??jP,o={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0};if(t.pids.length===0)return o;let i=new Set,a=new Set;for(let l of t.pids){n(l)&&(i.add(l),a.add(l));try{s(l,"SIGTERM")}catch(m){m?.code!=="ESRCH"&&a.delete(l)}}let c=Date.now()+e,u=0;for(;a.size>0&&Date.now()<c;){await LP(r);for(let l of[...a])n(l)||(a.delete(l),u++)}let d=0;for(let l of a){try{s(l,"SIGKILL")}catch(m){if(m?.code==="ESRCH"){u++;continue}continue}i.has(l)&&d++}return{terminatedBySigterm:u,terminatedBySigkill:d,totalKilled:u+d}}async function FP(t=process.env){let e={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0},r=t.CONTEXT_MODE_STARTUP_SWEEP;if(r==="0"||r==="false")return e;try{let n=Ia({ownPid:process.pid,ownPpid:process.ppid,sameParentOnly:!0});return n.length===0?e:await Aa({pids:n})}catch{return e}}var CP,OP,DP,MP,jP,Wl=x(()=>{"use strict";CP="(node|bun).*(plugins/(cache|marketplaces)/.*context-mode.*start\\.mjs|context-mode/start\\.mjs|context-mode/server\\.bundle\\.mjs|bin/context-mode($|[^a-zA-Z0-9_-]))",OP=`Get-CimInstance Win32_Process -Filter "Name='node.exe' OR Name='bun.exe'" | Where-Object { $_.CommandLine -match 'plugins[\\\\/](cache|marketplaces)[\\\\/].*context-mode.*start\\.mjs|context-mode[\\\\/]start\\.mjs|context-mode[\\\\/]server\\.bundle\\.mjs|bin[\\\\/]context-mode($|[^a-zA-Z0-9_-])' } | Select-Object -ExpandProperty ProcessId`;DP=(t,e)=>Vl(t,[...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),MP=t=>{try{return process.kill(t,0),!0}catch{return!1}},jP=(t,e)=>{process.kill(t,e)}});var N_,D_=x(()=>{"use strict";N_={"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 Yl}from"node:path";import{accessSync as ZP,copyFileSync as BP,constants as qP,mkdirSync as VP}from"node:fs";import{homedir as M_}from"node:os";var ke,Ct=x(()=>{"use strict";ke=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=Yl(M_(),...this.sessionDirSegments,"context-mode","sessions");return VP(e,{recursive:!0}),e}getConfigDir(e){return Yl(M_(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(){return Yl(this.getConfigDir(),"memory")}backupSettings(){let e=this.getSettingsPath();try{ZP(e,qP.R_OK);let r=e+".bak";return BP(e,r),r}catch{return null}}}});var Rs,Xl=x(()=>{"use strict";Ct();Rs=class extends ke{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??""}}});async function WP(){if(Cs)return Cs;if(Fo)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let r of t)try{let n=await import(r.href);if(typeof n?.assertPluginCacheIntegrity=="function")return Cs=n,Cs}catch(n){e=n}return Fo=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return Fo=t instanceof Error?t.message:String(t),null}}function j_(t){if(Cs){let e=Cs.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}return Fo?{status:"FAIL",detail:`integrity helper unavailable: ${Fo}`}:{status:"FAIL",detail:"integrity helper not yet loaded"}}var Cs,Fo,z_=x(()=>{"use strict";Cs=null,Fo=null;WP()});function Uo(t,e){let r=On[e],n=ed(e);return t.hooks?.some(s=>s.command?.includes(r)||s.command?.includes(n))??!1}function ed(t,e){if(e){let r=On[t];return xe(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function td(t){let e=Ca(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function U_(t){let e=Object.values(On);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var or,GP,Ql,L_,KP,tZ,On,F_,rZ,H_=x(()=>{"use strict";Sr();or={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},GP="mcp__",Ql=["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",GP],L_=Ql.join("|"),KP=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],tZ=KP.join("|"),On={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},F_=[or.PRE_TOOL_USE,or.SESSION_START],rZ=[or.POST_TOOL_USE,or.PRE_COMPACT,or.USER_PROMPT_SUBMIT]});var nd={};ze(nd,{ClaudeCodeAdapter:()=>rd});import{readFileSync as Na,writeFileSync as Z_,existsSync as B_,readdirSync as JP,chmodSync as YP,accessSync as XP,mkdirSync as QP,constants as eR}from"node:fs";import{resolve as Da,join as In}from"node:path";import{homedir as q_}from"node:os";var rd,sd=x(()=>{"use strict";Xl();tn();z_();Sr();H_();rd=class extends Rs{constructor(){super([".claude"])}name="Claude Code";paradigm="json-stdio";projectDirEnvVar="CLAUDE_PROJECT_DIR";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};getConfigDir(e){return Be()}getSessionDir(){let e=In(this.getConfigDir(),"context-mode","sessions");return QP(e,{recursive:!0}),e}getSettingsPath(){return In(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=xe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...Ql].map(s=>({matcher:s,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/sessionstart.mjs`)}]}]}}readSettings(){try{let e=Na(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){Z_(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,or.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,or.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}getHealthChecks(e){let r=Object.entries(On).map(([s,o])=>{let i=In(e,"hooks",o);return{name:`Hook script: ${s} (${o})`,check:()=>B_(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),n={name:"Plugin cache integrity",check:()=>j_(e)};return[...r,n]}readPluginHooks(e){let r=[In(e,"hooks","hooks.json"),In(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let s=Na(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=>Uo(i,n)))return!0;let o=r?.[n];return!!(o&&o.length>0&&o.some(i=>Uo(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=In(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(Na(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(),Be(),Da(q_(),".claude"),Da(q_(),".config","claude")]));for(let r of e){let n=Da(r,"plugins","cache","context-mode","context-mode");try{let o=JP(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 m=l;if(!U_(m))return!0;let h=m.hooks??[];return h.every(f=>!f.command||!td(f.command))?!0:h.every(f=>{let g=f.command?td(f.command):null;return g?B_(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&&F_.every(c=>this.checkHookType(void 0,o,c))){let c=Object.values(On),u=d=>d!=null&&(c.some(l=>d.includes(l))||d.includes("context-mode hook"));for(let d of Object.keys(n)){let l=n[d];if(!Array.isArray(l))continue;let m=0;for(let p of l){let f=p,g=f.hooks??[],y=g.length;f.hooks=g.filter(b=>!u(b.command)),m+=y-f.hooks.length}let h=l.filter(p=>{let f=p.hooks;return Array.isArray(f)&&f.length>0});(m>0||h.length!==l.length)&&(n[d]=h,m>0&&s.push(`Removed ${m} 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=[or.PRE_TOOL_USE,or.SESSION_START];for(let a of i){let c=ed(a,e);if(a===or.PRE_TOOL_USE){let u={matcher:L_,hooks:[{type:"command",command:c}]},d=n.PreToolUse;if(d&&Array.isArray(d)){let l=d.findIndex(m=>Uo(m,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(m=>Uo(m,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(On)){let s=Da(e,"hooks",n);try{XP(s,eR.R_OK),YP(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=In(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(Na(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();Z_(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 An(t,e){let r=od[t];return e&&r?xe(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var Te,V_,od,mZ,fZ,W_=x(()=>{"use strict";Sr();Te={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},V_="mcp__(?!.*context-mode)",od={[Te.BEFORE_AGENT]:"beforeagent.mjs",[Te.BEFORE_TOOL]:"beforetool.mjs",[Te.AFTER_TOOL]:"aftertool.mjs",[Te.PRE_COMPRESS]:"precompress.mjs",[Te.SESSION_START]:"sessionstart.mjs"},mZ=[Te.BEFORE_TOOL,Te.SESSION_START],fZ=[Te.AFTER_TOOL,Te.PRE_COMPRESS]});var K_={};ze(K_,{GeminiCLIAdapter:()=>ad});import{readFileSync as id,writeFileSync as G_,mkdirSync as tR,accessSync as rR,chmodSync as nR,constants as sR}from"node:fs";import{resolve as Ho,join as oR}from"node:path";import{homedir as Ma}from"node:os";var ad,J_=x(()=>{"use strict";Ct();W_();ad=class extends ke{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 Ho(Ma(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[Te.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:An(Te.BEFORE_AGENT,e)}]}],[Te.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${V_}`,hooks:[{type:"command",command:An(Te.BEFORE_TOOL,e)}]}],[Te.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:An(Te.AFTER_TOOL,e)}]}],[Te.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:An(Te.PRE_COMPRESS,e)}]}],[Te.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:An(Te.SESSION_START,e)}]}]}}readSettings(){try{let e=id(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=Ho(Ma(),".gemini");tR(r,{recursive:!0}),G_(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?.[Te.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?.[Te.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(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=Ho(Ma(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(id(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:Te.BEFORE_AGENT},{name:Te.BEFORE_TOOL},{name:Te.SESSION_START}];for(let i of o){let c={matcher:"",hooks:[{type:"command",command:An(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let d=u.findIndex(l=>l.hooks?.some(h=>h.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=oR(e,"hooks","gemini-cli");for(let s of Object.values(od)){let o=Ho(n,s);try{rR(o,sR.R_OK),nR(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Ho(Ma(),".gemini","extensions","context-mode","package.json"),s=JSON.parse(id(n,"utf-8"));s.version=r,s.installPath=e,s.lastUpdated=new Date().toISOString(),G_(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 Nn,xZ,SZ,Y_=x(()=>{"use strict";Nn={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},xZ=[Nn.BEFORE,Nn.AFTER],SZ=[Nn.COMPACTING]});var Q_={};ze(Q_,{OpenCodeAdapter:()=>cd});import{readFileSync as X_,writeFileSync as aR,mkdirSync as cR,copyFileSync as uR,accessSync as lR,constants as dR}from"node:fs";import{resolve as Lt,join as rn}from"node:path";import{homedir as nn}from"node:os";function iR(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var cd,eb=x(()=>{"use strict";Ct();Y_();cd=class extends ke{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"),rn(nn(),".config","kilo","kilo.json"),rn(nn(),".config","kilo","kilo.jsonc")]:[Lt("opencode.json"),Lt("opencode.jsonc"),Lt(".opencode","opencode.json"),Lt(".opencode","opencode.jsonc"),rn(nn(),".config","opencode","opencode.json"),rn(nn(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=rn(this.getConfigDir(),"context-mode","sessions");return cR(e,{recursive:!0}),e}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||rn(nn(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||rn(nn(),".config"),rn(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[Nn.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Nn.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Nn.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(nn()))),n=null,s;for(let o of e)try{let i=X_(o,"utf-8"),a=o.endsWith(".jsonc")?iR(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){aR(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(nn(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(X_(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{lR(this.settingsPath,dR.R_OK);let r=this.settingsPath+".bak";return uR(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 Dn,RZ,CZ,tb=x(()=>{"use strict";Dn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},RZ=[Dn.TOOL_CALL_BEFORE,Dn.TOOL_CALL_AFTER],CZ=[Dn.COMMAND_NEW]});var rb={};ze(rb,{OpenClawAdapter:()=>pd});import{readFileSync as ud,writeFileSync as pR,copyFileSync as mR,accessSync as fR,constants as hR}from"node:fs";import{resolve as Dr,join as ld}from"node:path";import{homedir as dd}from"node:os";var pd,nb=x(()=>{"use strict";Ct();tb();pd=class extends ke{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 Dr("openclaw.json")}getConfigDir(e){return Dr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(){return ld(this.getConfigDir(),"memory")}generateHookConfig(e){return{[Dn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Dn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Dn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Dr("openclaw.json"),Dr(".openclaw","openclaw.json"),ld(dd(),".openclaw","openclaw.json")];for(let r of e)try{let n=ud(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Dr("openclaw.json");pR(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=Dr(dd(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(ud(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Dr("node_modules","context-mode","package.json"),r=JSON.parse(ud(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=[Dr("openclaw.json"),Dr(".openclaw","openclaw.json"),ld(dd(),".openclaw","openclaw.json")];for(let r of e)try{fR(r,hR.R_OK);let n=r+".bak";return mR(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 sb}from"node:os";import{resolve as md}from"node:path";function ja(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?md(sb(),t.replace(/^~[/\\]?/,"")):md(t):md(sb(),".codex")}var fd=x(()=>{"use strict"});var cb={};ze(cb,{CodexAdapter:()=>yd});import{readFileSync as Os,writeFileSync as ob,accessSync as gR,copyFileSync as yR,constants as _R,mkdirSync as hd}from"node:fs";import{resolve as bR,dirname as gd,join as za}from"node:path";import{fileURLToPath as vR}from"node:url";function ib(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 ab(t){let e=ib(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function kR(t){let e=ib(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function wR(t){if(ab(t))return{text:t,changed:!1};let e=t.includes(`\r
2
+ var jT=Object.create;var Nl=Object.defineProperty;var zT=Object.getOwnPropertyDescriptor;var LT=Object.getOwnPropertyNames;var FT=Object.getPrototypeOf,UT=Object.prototype.hasOwnProperty;var x=(t,e)=>()=>(t&&(e=t(t=0)),e);var M=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ie=(t,e)=>{for(var r in e)Nl(t,r,{get:e[r],enumerable:!0})},HT=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of LT(e))!UT.call(t,s)&&s!==r&&Nl(t,s,{get:()=>e[s],enumerable:!(n=zT(e,s))||n.enumerable});return t};var Mo=(t,e,r)=>(r=t!=null?jT(FT(t)):{},HT(e||!t||!t.__esModule?Nl(r,"default",{value:t,enumerable:!0}):r,t));var Ul=M((YU,k_)=>{"use strict";var Fl={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"},XT={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},QT={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?Fl.up():"");return t&&(e+=Fl.left),e}};k_.exports={cursor:Fl,scroll:XT,erase:QT,beep:"\x07"}});var C_=M((AH,Gl)=>{var Ra=process||{},P_=Ra.argv||[],Pa=Ra.env||{},wP=!(Pa.NO_COLOR||P_.includes("--no-color"))&&(!!Pa.FORCE_COLOR||P_.includes("--color")||Ra.platform==="win32"||(Ra.stdout||{}).isTTY&&Pa.TERM!=="dumb"||!!Pa.CI),EP=(t,e,r=t)=>n=>{let s=""+n,o=s.indexOf(e,t.length);return~o?t+$P(s,e,r,o)+e:t+s+e},$P=(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)},R_=(t=wP)=>{let e=t?EP:()=>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")}};Gl.exports=R_();Gl.exports.createColors=R_});import{execFileSync as I_,execSync as Lo}from"node:child_process";import{existsSync as Ca}from"node:fs";function Jl(t){let e=t.split(/[\\/]/);return e[e.length-1]??t}function PP(t){return TP.test(Jl(t))}function Je(t){try{let e=Fo?`where ${t}`:`command -v ${t}`;return Lo(e,{stdio:"pipe"}),!0}catch{return!1}}function Kl(t){if(Fo)try{let r=Lo(`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(!Je(t))return!1;try{return Fo?Lo(`"${t}" --version`,{stdio:"pipe",timeout:5e3}):I_(t,["--version"],{stdio:"pipe",timeout:1500}),!0}catch{return!1}}function A_(){if(Je("bun"))return!0;for(let t of N_())if(Ca(t))return!0;return!1}function RP(){for(let e of N_())if(Ca(e))return e;if(Je("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return Fo?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function N_(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Fo){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 CP(){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(Ca(e))return e;try{let r=Lo("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 Lt(t,e=["--version"]){try{if(process.platform==="win32"){let r=[t,...e].map(n=>/[\s"&|<>^()%!]/.test(n)?JSON.stringify(n):n).join(" ");return Lo(r,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}else return I_(t,e,{encoding:"utf-8",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function Ps(){let e=A_()?RP():null,r=process.env.SHELL,n=r&&Ca(r)&&PP(r)?r:null,s=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(Je("tsx")?"tsx":Je("ts-node")?"ts-node":null),python:Kl("python3")?"python3":Kl("python")?"python":Kl("py")?"py":null,shell:n??(s?CP()??(Je("sh")?"sh":Je("powershell")?"powershell":"cmd.exe"):Je("bash")?"bash":"sh"),ruby:Je("ruby")?"ruby":null,go:Je("go")?"go":null,rust:Je("rustc")?"rustc":null,php:Je("php")?"php":null,perl:Je("perl")?"perl":null,r:Je("Rscript")?"Rscript":Je("r")?"r":null,elixir:Je("elixir")?"elixir":null,csharp:Je("dotnet-script")?"dotnet-script":null}}function In(){return A_()}function Oa(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${Lt(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${Lt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Lt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Lt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Lt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Lt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Lt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Lt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Lt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Lt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Lt(t.elixir)})`),t.csharp&&e.push(` C#: ${t.csharp} (${Lt(t.csharp)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
3
+ `)}function Ia(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),t.csharp&&e.push("csharp"),e}function D_(t,e,r){switch(e){case"javascript":return O_.test(Jl(t.javascript))?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return O_.test(Jl(t.typescript))?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let 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];case"csharp":if(!t.csharp)throw new Error("C# not available. Install dotnet-script via `dotnet tool install -g dotnet-script`.");return[t.csharp,r]}}var TP,O_,Fo,Aa=x(()=>{"use strict";TP=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i,O_=/^bun(\.exe)?$/i;Fo=process.platform==="win32"});function xe(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}function Na(t){if(typeof t!="string"||t.length===0)return null;let e=t.match(/^"([^"]+)"\s+"([^"]+)"\s*$/);return e?{nodePath:e[1],scriptPath:e[2]}:null}var Sr=x(()=>{"use strict"});function OP(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 IP(t){let e=Na(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function Da(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 OP(o)){let a=IP(i);a&&r.add(a)}return[...r]}var Yl=x(()=>{"use strict";Sr()});var M_,j_=x(()=>{"use strict";M_={"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 Xl}from"node:path";import{accessSync as AP,copyFileSync as NP,constants as DP,mkdirSync as MP}from"node:fs";import{homedir as z_}from"node:os";var ke,Ct=x(()=>{"use strict";ke=class{constructor(e){this.sessionDirSegments=e}sessionDirSegments;getSessionDir(){let e=Xl(z_(),...this.sessionDirSegments,"context-mode","sessions");return MP(e,{recursive:!0}),e}getConfigDir(e){return Xl(z_(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(){return Xl(this.getConfigDir(),"memory")}backupSettings(){let e=this.getSettingsPath();try{AP(e,DP.R_OK);let r=e+".bak";return NP(e,r),r}catch{return null}}}});var Rs,Ql=x(()=>{"use strict";Ct();Rs=class extends ke{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??""}}});async function jP(){if(Cs)return Cs;if(Uo)return null;try{let t=[new URL("../../scripts/plugin-cache-integrity.mjs",import.meta.url),new URL("./scripts/plugin-cache-integrity.mjs",import.meta.url)],e=null;for(let r of t)try{let n=await import(r.href);if(typeof n?.assertPluginCacheIntegrity=="function")return Cs=n,Cs}catch(n){e=n}return Uo=e instanceof Error?e.message:String(e??"not found"),null}catch(t){return Uo=t instanceof Error?t.message:String(t),null}}function L_(t){if(Cs){let e=Cs.assertPluginCacheIntegrity({pluginRoot:t});return e.ok?{status:"OK",detail:`${t} (all required runtime siblings present)`}:{status:"FAIL",detail:`missing: ${e.missing.join(", ")}`}}return Uo?{status:"FAIL",detail:`integrity helper unavailable: ${Uo}`}:{status:"FAIL",detail:"integrity helper not yet loaded"}}var Cs,Uo,F_=x(()=>{"use strict";Cs=null,Uo=null;jP()});function Ho(t,e){let r=An[e],n=td(e);return t.hooks?.some(s=>s.command?.includes(r)||s.command?.includes(n))??!1}function td(t,e){if(e){let r=An[t];return xe(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function rd(t){let e=Na(t);if(e)return e.scriptPath.endsWith(".mjs")?e.scriptPath:null;let r=t.match(/^\s*node\s+"([^"]+\.mjs)"\s*$/);if(r)return r[1];let n=t.match(/^\s*node\s+(\S+\.mjs)\s*$/);return n?n[1]:null}function Z_(t){let e=Object.values(An);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var ir,zP,ed,U_,LP,KH,An,H_,JH,B_=x(()=>{"use strict";Sr();ir={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},zP="mcp__",ed=["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",zP],U_=ed.join("|"),LP=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],KH=LP.join("|"),An={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},H_=[ir.PRE_TOOL_USE,ir.SESSION_START],JH=[ir.POST_TOOL_USE,ir.PRE_COMPACT,ir.USER_PROMPT_SUBMIT]});var sd={};Ie(sd,{ClaudeCodeAdapter:()=>nd});import{readFileSync as Ma,writeFileSync as q_,existsSync as V_,readdirSync as FP,chmodSync as UP,accessSync as HP,mkdirSync as ZP,constants as BP}from"node:fs";import{resolve as ja,join as Nn}from"node:path";import{homedir as W_}from"node:os";var nd,od=x(()=>{"use strict";Ql();rn();F_();Sr();B_();nd=class extends Rs{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=Nn(this.getConfigDir(),"context-mode","sessions");return ZP(e,{recursive:!0}),e}getSettingsPath(){return Nn(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=xe(`${e}/hooks/pretooluse.mjs`);return{PreToolUse:[...ed].map(s=>({matcher:s,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/posttooluse.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/userpromptsubmit.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/sessionstart.mjs`)}]}]}}readSettings(){try{let e=Ma(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){q_(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,ir.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,ir.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}getHealthChecks(e){let r=Object.entries(An).map(([s,o])=>{let i=Nn(e,"hooks",o);return{name:`Hook script: ${s} (${o})`,check:()=>V_(i)?{status:"OK",detail:i}:{status:"FAIL",detail:`not found at ${i}`}}}),n={name:"Plugin cache integrity",check:()=>L_(e)};return[...r,n]}readPluginHooks(e){let r=[Nn(e,"hooks","hooks.json"),Nn(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let s=Ma(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=>Ho(i,n)))return!0;let o=r?.[n];return!!(o&&o.length>0&&o.some(i=>Ho(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=Nn(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(Ma(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(),ja(W_(),".claude"),ja(W_(),".config","claude")]));for(let r of e){let n=ja(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 m=l;if(!Z_(m))return!0;let h=m.hooks??[];return h.every(f=>!f.command||!rd(f.command))?!0:h.every(f=>{let g=f.command?rd(f.command):null;return g?V_(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&&H_.every(c=>this.checkHookType(void 0,o,c))){let c=Object.values(An),u=d=>d!=null&&(c.some(l=>d.includes(l))||d.includes("context-mode hook"));for(let d of Object.keys(n)){let l=n[d];if(!Array.isArray(l))continue;let m=0;for(let p of l){let f=p,g=f.hooks??[],y=g.length;f.hooks=g.filter(b=>!u(b.command)),m+=y-f.hooks.length}let h=l.filter(p=>{let f=p.hooks;return Array.isArray(f)&&f.length>0});(m>0||h.length!==l.length)&&(n[d]=h,m>0&&s.push(`Removed ${m} 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=[ir.PRE_TOOL_USE,ir.SESSION_START];for(let a of i){let c=td(a,e);if(a===ir.PRE_TOOL_USE){let u={matcher:U_,hooks:[{type:"command",command:c}]},d=n.PreToolUse;if(d&&Array.isArray(d)){let l=d.findIndex(m=>Ho(m,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(m=>Ho(m,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(An)){let s=ja(e,"hooks",n);try{HP(s,BP.R_OK),UP(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Nn(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(Ma(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();q_(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 Dn(t,e){let r=id[t];return e&&r?xe(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var Te,G_,id,aZ,cZ,K_=x(()=>{"use strict";Sr();Te={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},G_="mcp__(?!.*context-mode)",id={[Te.BEFORE_AGENT]:"beforeagent.mjs",[Te.BEFORE_TOOL]:"beforetool.mjs",[Te.AFTER_TOOL]:"aftertool.mjs",[Te.PRE_COMPRESS]:"precompress.mjs",[Te.SESSION_START]:"sessionstart.mjs"},aZ=[Te.BEFORE_TOOL,Te.SESSION_START],cZ=[Te.AFTER_TOOL,Te.PRE_COMPRESS]});var Y_={};Ie(Y_,{GeminiCLIAdapter:()=>cd});import{readFileSync as ad,writeFileSync as J_,mkdirSync as qP,accessSync as VP,chmodSync as WP,constants as GP}from"node:fs";import{resolve as Zo,join as KP}from"node:path";import{homedir as za}from"node:os";var cd,X_=x(()=>{"use strict";Ct();K_();cd=class extends ke{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 Zo(za(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[Te.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:Dn(Te.BEFORE_AGENT,e)}]}],[Te.BEFORE_TOOL]:[{matcher:`run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode|mcp__context-mode|${G_}`,hooks:[{type:"command",command:Dn(Te.BEFORE_TOOL,e)}]}],[Te.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:Dn(Te.AFTER_TOOL,e)}]}],[Te.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:Dn(Te.PRE_COMPRESS,e)}]}],[Te.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:Dn(Te.SESSION_START,e)}]}]}}readSettings(){try{let e=ad(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=Zo(za(),".gemini");qP(r,{recursive:!0}),J_(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?.[Te.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?.[Te.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(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=Zo(za(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(ad(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:Te.BEFORE_AGENT},{name:Te.BEFORE_TOOL},{name:Te.SESSION_START}];for(let i of o){let c={matcher:"",hooks:[{type:"command",command:Dn(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let d=u.findIndex(l=>l.hooks?.some(h=>h.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(id)){let o=Zo(n,s);try{VP(o,GP.R_OK),WP(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Zo(za(),".gemini","extensions","context-mode","package.json"),s=JSON.parse(ad(n,"utf-8"));s.version=r,s.installPath=e,s.lastUpdated=new Date().toISOString(),J_(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 Mn,hZ,gZ,Q_=x(()=>{"use strict";Mn={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},hZ=[Mn.BEFORE,Mn.AFTER],gZ=[Mn.COMPACTING]});var tb={};Ie(tb,{OpenCodeAdapter:()=>ud});import{readFileSync as eb,writeFileSync as YP,mkdirSync as XP,copyFileSync as QP,accessSync as eR,constants as tR}from"node:fs";import{resolve as Ft,join as nn}from"node:path";import{homedir as sn}from"node:os";function JP(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var ud,rb=x(()=>{"use strict";Ct();Q_();ud=class extends ke{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??Ft(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Ft("kilo.json"),Ft("kilo.jsonc"),Ft(".kilo","kilo.json"),Ft(".kilo","kilo.jsonc"),Ft(".kilocode","kilo.json"),Ft(".kilocode","kilo.jsonc"),nn(sn(),".config","kilo","kilo.json"),nn(sn(),".config","kilo","kilo.jsonc")]:[Ft("opencode.json"),Ft("opencode.jsonc"),Ft(".opencode","opencode.json"),Ft(".opencode","opencode.jsonc"),nn(sn(),".config","opencode","opencode.json"),nn(sn(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=nn(this.getConfigDir(),"context-mode","sessions");return XP(e,{recursive:!0}),e}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||nn(sn(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||nn(sn(),".config"),nn(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[Mn.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Mn.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Mn.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(sn()))),n=null,s;for(let o of e)try{let i=eb(o,"utf-8"),a=o.endsWith(".jsonc")?JP(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){YP(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=Ft(sn(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(eb(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{eR(this.settingsPath,tR.R_OK);let r=this.settingsPath+".bak";return QP(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 jn,kZ,wZ,nb=x(()=>{"use strict";jn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},kZ=[jn.TOOL_CALL_BEFORE,jn.TOOL_CALL_AFTER],wZ=[jn.COMMAND_NEW]});var sb={};Ie(sb,{OpenClawAdapter:()=>md});import{readFileSync as ld,writeFileSync as rR,copyFileSync as nR,accessSync as sR,constants as oR}from"node:fs";import{resolve as Mr,join as dd}from"node:path";import{homedir as pd}from"node:os";var md,ob=x(()=>{"use strict";Ct();nb();md=class extends ke{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 Mr("openclaw.json")}getConfigDir(e){return Mr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(){return dd(this.getConfigDir(),"memory")}generateHookConfig(e){return{[jn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[jn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[jn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Mr("openclaw.json"),Mr(".openclaw","openclaw.json"),dd(pd(),".openclaw","openclaw.json")];for(let r of e)try{let n=ld(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Mr("openclaw.json");rR(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=Mr(pd(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(ld(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Mr("node_modules","context-mode","package.json"),r=JSON.parse(ld(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=[Mr("openclaw.json"),Mr(".openclaw","openclaw.json"),dd(pd(),".openclaw","openclaw.json")];for(let r of e)try{sR(r,oR.R_OK);let n=r+".bak";return nR(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 ib}from"node:os";import{resolve as fd}from"node:path";function La(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?fd(ib(),t.replace(/^~[/\\]?/,"")):fd(t):fd(ib(),".codex")}var hd=x(()=>{"use strict"});var lb={};Ie(lb,{CodexAdapter:()=>_d});import{readFileSync as Os,writeFileSync as ab,accessSync as iR,copyFileSync as aR,constants as cR,mkdirSync as gd}from"node:fs";import{resolve as uR,dirname as yd,join as Fa}from"node:path";import{fileURLToPath as lR}from"node:url";function cb(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 ub(t){let e=cb(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function mR(t){let e=cb(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function fR(t){if(ub(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 xR,Mn,SR,yd,ub=x(()=>{"use strict";Ct();fd();xR="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",Mn={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"},SR={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"]};yd=class extends ke{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 ja()}getSettingsPath(){return za(this.getConfigDir(),"config.toml")}getSessionDir(){let e=za(this.getConfigDir(),"context-mode","sessions");return hd(e,{recursive:!0}),e}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(){return za(this.getConfigDir(),"memories")}generateHookConfig(e){return{PreToolUse:[{matcher:xR,hooks:[{type:"command",command:Mn.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:Mn.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Mn.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Mn.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Mn.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:Mn.Stop}]}]}}readSettings(){try{return{_raw_toml:Os(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[];try{let o=Os(this.getSettingsPath(),"utf-8"),i=ab(o),a=!i&&kR(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=Os(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=Os(a,"utf-8")}catch{c=""}let u=wR(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 dR,zn,pR,_d,db=x(()=>{"use strict";Ct();hd();dR="local_shell|shell|shell_command|exec_command|Bash|Shell|apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__",zn={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"},pR={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"]};_d=class extends ke{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 La()}getSettingsPath(){return Fa(this.getConfigDir(),"config.toml")}getSessionDir(){let e=Fa(this.getConfigDir(),"context-mode","sessions");return gd(e,{recursive:!0}),e}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(){return Fa(this.getConfigDir(),"memories")}generateHookConfig(e){return{PreToolUse:[{matcher:dR,hooks:[{type:"command",command:zn.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:zn.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:zn.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:zn.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:zn.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:zn.Stop}]}]}}readSettings(){try{return{_raw_toml:Os(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[];try{let o=Os(this.getSettingsPath(),"utf-8"),i=ub(o),a=!i&&mR(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=Os(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=Os(a,"utf-8")}catch{c=""}let u=fR(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}`;hd(gd(a),{recursive:!0}),ob(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{gR(r,_R.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=bR(gd(vR(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return Os(e,"utf-8")}catch{return`# context-mode
18
+ `)?u.text:`${u.text}${d}`;gd(yd(a),{recursive:!0}),ab(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{iR(r,cR.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=uR(yd(lR(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return Os(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 za(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return yR(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(Os(e,"utf-8"))}}catch(r){let n=r instanceof Error?r.message:String(r);return(typeof r=="object"&&r!==null&&"code"in r?String(r.code??""):"")==="ENOENT"?{ok:!1,reason:"missing"}:r instanceof SyntaxError?{ok:!1,reason:"invalid_json",error:n}:{ok:!1,reason:"read_error",error:n}}}writeHooksConfig(e){let r=this.getHooksPath();hd(gd(r),{recursive:!0}),ob(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(Mn[e]??""),o=SR[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 lb,writeFileSync as ER,mkdirSync as $R,accessSync as TR,chmodSync as PR,constants as RR}from"node:fs";import{resolve as La,join as CR}from"node:path";var Is,_d=x(()=>{"use strict";Ct();Is=class extends ke{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 La(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=lb(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=lb(La(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();$R(La(".github","hooks"),{recursive:!0}),ER(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=CR(e,"hooks",this.hookSubdir);for(let s of Object.values(this.hookModule.HOOK_SCRIPTS)){let o=La(n,s);try{TR(o,RR.R_OK),PR(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}}});function db(t,e){let r=bd[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?xe(`${e}/hooks/vscode-copilot/${r}`):`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Ft,bd,JZ,YZ,pb=x(()=>{"use strict";Sr();Ft={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},bd={[Ft.PRE_TOOL_USE]:"pretooluse.mjs",[Ft.POST_TOOL_USE]:"posttooluse.mjs",[Ft.PRE_COMPACT]:"precompact.mjs",[Ft.SESSION_START]:"sessionstart.mjs"},JZ=[Ft.PRE_TOOL_USE,Ft.SESSION_START],YZ=[Ft.POST_TOOL_USE,Ft.PRE_COMPACT]});var mb={};ze(mb,{VSCodeCopilotAdapter:()=>Sd});import{readFileSync as vd,mkdirSync as OR,accessSync as IR,existsSync as AR,constants as NR}from"node:fs";import{resolve as As,join as Fa}from"node:path";import{homedir as xd}from"node:os";var Sd,fb=x(()=>{"use strict";_d();pb();Sd=class extends Is{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Ft,HOOK_SCRIPTS:bd,buildHookCommand:db};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=As(".github","context-mode","sessions"),r=Fa(xd(),".vscode","context-mode","sessions"),n=AR(As(".github"))?e:r;return OR(n,{recursive:!0}),n}getConfigDir(e){return As(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=As(".github","hooks");try{IR(n,NR.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let s=As(n,"context-mode.json");try{let o=vd(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=As(".vscode","mcp.json"),r=vd(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=[Fa(xd(),".vscode","extensions"),Fa(xd(),".vscode-insiders","extensions")];for(let r of e)try{let n=vd(Fa(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 hb(t,e){let r=kd[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?xe(`${e}/hooks/jetbrains-copilot/${r}`):`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Ut,kd,oB,iB,gb=x(()=>{"use strict";Sr();Ut={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},kd={[Ut.PRE_TOOL_USE]:"pretooluse.mjs",[Ut.POST_TOOL_USE]:"posttooluse.mjs",[Ut.PRE_COMPACT]:"precompact.mjs",[Ut.SESSION_START]:"sessionstart.mjs"},oB=[Ut.PRE_TOOL_USE,Ut.SESSION_START],iB=[Ut.POST_TOOL_USE,Ut.PRE_COMPACT]});var yb={};ze(yb,{JetBrainsCopilotAdapter:()=>wd});import{readFileSync as DR}from"node:fs";import{resolve as MR}from"node:path";var wd,_b=x(()=>{"use strict";_d();gb();wd=class extends Is{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Ut,HOOK_SCRIPTS:kd,buildHookCommand:hb};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 MR(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=DR(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 Zo(t,e){let r=Ed[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,Ed,jR,zR,$d,bb,vb,xb=x(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Ed={[_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"},jR="MCP:(?!ctx_)",zR=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",jR],$d=zR.join("|"),bb=[_e.PRE_TOOL_USE],vb=[_e.POST_TOOL_USE]});var $b={};ze($b,{CursorAdapter:()=>Td});import{readFileSync as Ua,writeFileSync as LR,mkdirSync as FR,accessSync as Sb,chmodSync as UR,constants as kb,existsSync as wb,readdirSync as HR}from"node:fs";import{execSync as ZR}from"node:child_process";import{resolve as jn,join as zn}from"node:path";import{homedir as Ha}from"node:os";var Eb,Td,Tb=x(()=>{"use strict";Ct();tn();xb();Eb="/Library/Application Support/Cursor/hooks.json",Td=class extends ke{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 jn(".cursor","hooks.json")}getConfigDir(e){return jn(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:$d,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=Ua(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();FR(jn(".cursor"),{recursive:!0}),LR(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 bb){let a=o[i],c=Array.isArray(a)&&a.some(u=>Zo(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 vb){let a=o[i],c=Array.isArray(a)&&a.some(u=>Zo(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`})}}wb(Eb)&&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=>Zo(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=[zn(Ha(),".cursor","plugins","local"),zn(Ha(),".cursor","plugins","cache")],r=[];for(let n of e){try{Sb(n,kb.F_OK)}catch{continue}let s=[];try{s=HR(n)}catch{continue}for(let o of s){let i=zn(n,o,".cursor-plugin","plugin.json");try{let a=Ua(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[jn(".cursor","mcp.json"),zn(Ha(),".cursor","mcp.json")];for(let n of e)try{let s=Ua(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 ZR("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:$d,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=zn(e,"hooks","cursor");for(let s of Object.values(Ed)){let o=jn(n,s);try{Sb(o,kb.R_OK),UR(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),zn(Ha(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(Eb),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=Ua(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[jn(".claude","settings.json"),jn(".claude","settings.local.json"),zn(Be(),"settings.json")].some(r=>wb(r))}upsertHookEntry(e,r,n,s){let o=e[r],i=Array.isArray(o)?[...o]:[],a=i.findIndex(c=>Zo(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 Rb={};ze(Rb,{AntigravityAdapter:()=>Rd});import{readFileSync as Za,writeFileSync as BR,mkdirSync as qR}from"node:fs";import{resolve as Ba,dirname as Pb}from"node:path";import{fileURLToPath as VR}from"node:url";import{homedir as Pd}from"node:os";var Rd,Cb=x(()=>{"use strict";Ct();Rd=class extends ke{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 Ba(Pd(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Ba(Pd(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Za(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();qR(Pb(r),{recursive:!0}),BR(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=Za(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=Ba(Pd(),".gemini","extensions","context-mode","package.json");return JSON.parse(Za(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Ba(Pb(VR(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Za(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 Fa(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return aR(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(Os(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();gd(yd(r),{recursive:!0}),ab(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(zn[e]??""),o=pR[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 pb,writeFileSync as hR,mkdirSync as gR,accessSync as yR,chmodSync as _R,constants as bR}from"node:fs";import{resolve as Ua,join as vR}from"node:path";var Is,bd=x(()=>{"use strict";Ct();Is=class extends ke{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 Ua(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=pb(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=pb(Ua(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();gR(Ua(".github","hooks"),{recursive:!0}),hR(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=vR(e,"hooks",this.hookSubdir);for(let s of Object.values(this.hookModule.HOOK_SCRIPTS)){let o=Ua(n,s);try{yR(o,bR.R_OK),_R(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}}});function mb(t,e){let r=vd[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?xe(`${e}/hooks/vscode-copilot/${r}`):`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Ut,vd,BZ,qZ,fb=x(()=>{"use strict";Sr();Ut={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},vd={[Ut.PRE_TOOL_USE]:"pretooluse.mjs",[Ut.POST_TOOL_USE]:"posttooluse.mjs",[Ut.PRE_COMPACT]:"precompact.mjs",[Ut.SESSION_START]:"sessionstart.mjs"},BZ=[Ut.PRE_TOOL_USE,Ut.SESSION_START],qZ=[Ut.POST_TOOL_USE,Ut.PRE_COMPACT]});var hb={};Ie(hb,{VSCodeCopilotAdapter:()=>kd});import{readFileSync as xd,mkdirSync as xR,accessSync as SR,existsSync as kR,constants as wR}from"node:fs";import{resolve as As,join as Ha}from"node:path";import{homedir as Sd}from"node:os";var kd,gb=x(()=>{"use strict";bd();fb();kd=class extends Is{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Ut,HOOK_SCRIPTS:vd,buildHookCommand:mb};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=As(".github","context-mode","sessions"),r=Ha(Sd(),".vscode","context-mode","sessions"),n=kR(As(".github"))?e:r;return xR(n,{recursive:!0}),n}getConfigDir(e){return As(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=As(".github","hooks");try{SR(n,wR.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let s=As(n,"context-mode.json");try{let o=xd(s,"utf-8"),a=JSON.parse(o).hooks;a?.[Ut.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?.[Ut.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=As(".vscode","mcp.json"),r=xd(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=[Ha(Sd(),".vscode","extensions"),Ha(Sd(),".vscode-insiders","extensions")];for(let r of e)try{let n=xd(Ha(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 yb(t,e){let r=wd[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?xe(`${e}/hooks/jetbrains-copilot/${r}`):`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Ht,wd,QZ,eB,_b=x(()=>{"use strict";Sr();Ht={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},wd={[Ht.PRE_TOOL_USE]:"pretooluse.mjs",[Ht.POST_TOOL_USE]:"posttooluse.mjs",[Ht.PRE_COMPACT]:"precompact.mjs",[Ht.SESSION_START]:"sessionstart.mjs"},QZ=[Ht.PRE_TOOL_USE,Ht.SESSION_START],eB=[Ht.POST_TOOL_USE,Ht.PRE_COMPACT]});var bb={};Ie(bb,{JetBrainsCopilotAdapter:()=>Ed});import{readFileSync as ER}from"node:fs";import{resolve as $R}from"node:path";var Ed,vb=x(()=>{"use strict";bd();_b();Ed=class extends Is{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Ht,HOOK_SCRIPTS:wd,buildHookCommand:yb};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 $R(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?.[Ht.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?.[Ht.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 Bo(t,e){let r=$d[e],n=Zt(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 Zt(t){return`context-mode hook cursor ${t.toLowerCase()}`}var _e,$d,TR,PR,Td,xb,Sb,kb=x(()=>{"use strict";_e={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},$d={[_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_)",PR=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute",TR],Td=PR.join("|"),xb=[_e.PRE_TOOL_USE],Sb=[_e.POST_TOOL_USE]});var Pb={};Ie(Pb,{CursorAdapter:()=>Pd});import{readFileSync as Za,writeFileSync as RR,mkdirSync as CR,accessSync as wb,chmodSync as OR,constants as Eb,existsSync as $b,readdirSync as IR}from"node:fs";import{execSync as AR}from"node:child_process";import{resolve as Ln,join as Fn}from"node:path";import{homedir as Ba}from"node:os";var Tb,Pd,Rb=x(()=>{"use strict";Ct();rn();kb();Tb="/Library/Application Support/Cursor/hooks.json",Pd=class extends ke{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 Ln(".cursor","hooks.json")}getConfigDir(e){return Ln(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[_e.PRE_TOOL_USE]:[{type:"command",command:Zt(_e.PRE_TOOL_USE),matcher:Td,loop_limit:null,failClosed:!1}],[_e.POST_TOOL_USE]:[{type:"command",command:Zt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[_e.SESSION_START]:[{type:"command",command:Zt(_e.SESSION_START),loop_limit:null,failClosed:!1}],[_e.STOP]:[{type:"command",command:Zt(_e.STOP),loop_limit:null,failClosed:!1}],[_e.AFTER_AGENT_RESPONSE]:[{type:"command",command:Zt(_e.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=Za(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();CR(Ln(".cursor"),{recursive:!0}),RR(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 xb){let a=o[i],c=Array.isArray(a)&&a.some(u=>Bo(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 Sb){let a=o[i],c=Array.isArray(a)&&a.some(u=>Bo(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`})}}$b(Tb)&&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=>Bo(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=[Fn(Ba(),".cursor","plugins","local"),Fn(Ba(),".cursor","plugins","cache")],r=[];for(let n of e){try{wb(n,Eb.F_OK)}catch{continue}let s=[];try{s=IR(n)}catch{continue}for(let o of s){let i=Fn(n,o,".cursor-plugin","plugin.json");try{let a=Za(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[Ln(".cursor","mcp.json"),Fn(Ba(),".cursor","mcp.json")];for(let n of e)try{let s=Za(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:Zt(_e.PRE_TOOL_USE),matcher:Td,loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.POST_TOOL_USE,{type:"command",command:Zt(_e.POST_TOOL_USE),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.SESSION_START,{type:"command",command:Zt(_e.SESSION_START),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.STOP,{type:"command",command:Zt(_e.STOP),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,_e.AFTER_AGENT_RESPONSE,{type:"command",command:Zt(_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=Fn(e,"hooks","cursor");for(let s of Object.values($d)){let o=Ln(n,s);try{wb(o,Eb.R_OK),OR(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),Fn(Ba(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(Tb),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=Za(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[Ln(".claude","settings.json"),Ln(".claude","settings.local.json"),Fn(Ze(),"settings.json")].some(r=>$b(r))}upsertHookEntry(e,r,n,s){let o=e[r],i=Array.isArray(o)?[...o]:[],a=i.findIndex(c=>Bo(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 Ob={};Ie(Ob,{AntigravityAdapter:()=>Cd});import{readFileSync as qa,writeFileSync as NR,mkdirSync as DR}from"node:fs";import{resolve as Va,dirname as Cb}from"node:path";import{fileURLToPath as MR}from"node:url";import{homedir as Rd}from"node:os";var Cd,Ib=x(()=>{"use strict";Ct();Cd=class extends ke{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 Va(Rd(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return Va(Rd(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=qa(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();DR(Cb(r),{recursive:!0}),NR(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=qa(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=Va(Rd(),".gemini","extensions","context-mode","package.json");return JSON.parse(qa(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Va(Cb(MR(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return qa(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 qa(t,e){let r=Ob[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function Ns(t,e){let r=Ob[t];return e&&r?xe(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Le,Ob,WR,GR,Cd,TB,PB,Ib=x(()=>{"use strict";Sr();Le={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},Ob={[Le.PRE_TOOL_USE]:"pretooluse.mjs",[Le.POST_TOOL_USE]:"posttooluse.mjs",[Le.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Le.AGENT_SPAWN]:"agentspawn.mjs"},WR="@(?!context-mode/)",GR=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",WR],Cd=GR.join("|"),TB=[Le.PRE_TOOL_USE,Le.AGENT_SPAWN],PB=[Le.POST_TOOL_USE,Le.USER_PROMPT_SUBMIT]});var Mb={};ze(Mb,{KiroAdapter:()=>Od});import{readFileSync as Ds,writeFileSync as Ab,mkdirSync as Nb}from"node:fs";import{resolve as Ln,dirname as Db}from"node:path";import{fileURLToPath as KR}from"node:url";import{homedir as Va}from"node:os";var Od,jb=x(()=>{"use strict";Ct();Ib();Od=class extends ke{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 Ln(Va(),".kiro","settings","mcp.json")}getConfigDir(e){return Ln(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Le.PRE_TOOL_USE]:[{matcher:Cd,hooks:[{type:"command",command:Ns(Le.PRE_TOOL_USE,e)}]}],[Le.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:Ns(Le.POST_TOOL_USE,e)}]}],[Le.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:Ns(Le.AGENT_SPAWN,e)}]}],[Le.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:Ns(Le.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=Ds(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();Nb(Db(r),{recursive:!0}),Ab(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=Ln(Va(),".kiro","agents","default.json");try{let o=JSON.parse(Ds(n,"utf-8")).hooks??{};for(let i of[Le.PRE_TOOL_USE]){let c=(o[i]??[]).some(u=>qa(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[Le.POST_TOOL_USE]){let c=(o[i]??[]).some(u=>qa(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=Ds(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=Ln(Va(),".kiro","extensions","context-mode","package.json");return JSON.parse(Ds(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=Ln(Va(),".kiro","agents"),s=Ln(n,"default.json");try{Nb(n,{recursive:!0});let o={};try{o=JSON.parse(Ds(s,"utf-8"))}catch{}let i=o.hooks??{},a=[[Le.PRE_TOOL_USE,Cd],[Le.POST_TOOL_USE,"*"],[Le.AGENT_SPAWN,"*"],[Le.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let d=i[c]??[];d.some(l=>qa(l,c))||(d.push({matcher:u,command:Ns(c,e)}),i[c]=d,r.push(`Added ${c} hook to ${s}`))}o.hooks=i,Ab(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=Ln(Db(KR(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return Ds(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 Wa(t,e){let r=Ab[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function Ns(t,e){let r=Ab[t];return e&&r?xe(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Le,Ab,jR,zR,Od,xB,SB,Nb=x(()=>{"use strict";Sr();Le={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},Ab={[Le.PRE_TOOL_USE]:"pretooluse.mjs",[Le.POST_TOOL_USE]:"posttooluse.mjs",[Le.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Le.AGENT_SPAWN]:"agentspawn.mjs"},jR="@(?!context-mode/)",zR=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute",jR],Od=zR.join("|"),xB=[Le.PRE_TOOL_USE,Le.AGENT_SPAWN],SB=[Le.POST_TOOL_USE,Le.USER_PROMPT_SUBMIT]});var zb={};Ie(zb,{KiroAdapter:()=>Id});import{readFileSync as Ds,writeFileSync as Db,mkdirSync as Mb}from"node:fs";import{resolve as Un,dirname as jb}from"node:path";import{fileURLToPath as LR}from"node:url";import{homedir as Ga}from"node:os";var Id,Lb=x(()=>{"use strict";Ct();Nb();Id=class extends ke{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 Un(Ga(),".kiro","settings","mcp.json")}getConfigDir(e){return Un(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Le.PRE_TOOL_USE]:[{matcher:Od,hooks:[{type:"command",command:Ns(Le.PRE_TOOL_USE,e)}]}],[Le.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:Ns(Le.POST_TOOL_USE,e)}]}],[Le.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:Ns(Le.AGENT_SPAWN,e)}]}],[Le.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:Ns(Le.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=Ds(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();Mb(jb(r),{recursive:!0}),Db(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=Un(Ga(),".kiro","agents","default.json");try{let o=JSON.parse(Ds(n,"utf-8")).hooks??{};for(let i of[Le.PRE_TOOL_USE]){let c=(o[i]??[]).some(u=>Wa(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[Le.POST_TOOL_USE]){let c=(o[i]??[]).some(u=>Wa(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=Ds(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=Un(Ga(),".kiro","extensions","context-mode","package.json");return JSON.parse(Ds(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=Un(Ga(),".kiro","agents"),s=Un(n,"default.json");try{Mb(n,{recursive:!0});let o={};try{o=JSON.parse(Ds(s,"utf-8"))}catch{}let i=o.hooks??{},a=[[Le.PRE_TOOL_USE,Od],[Le.POST_TOOL_USE,"*"],[Le.AGENT_SPAWN,"*"],[Le.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let d=i[c]??[];d.some(l=>Wa(l,c))||(d.push({matcher:u,command:Ns(c,e)}),i[c]=d,r.push(`Added ${c} hook to ${s}`))}o.hooks=i,Db(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=Un(jb(LR(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return Ds(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 Fb={};ze(Fb,{ZedAdapter:()=>Ad});import{readFileSync as Id,writeFileSync as JR,mkdirSync as YR}from"node:fs";import{resolve as zb,dirname as Lb}from"node:path";import{fileURLToPath as XR}from"node:url";import{homedir as QR}from"node:os";var Ad,Ub=x(()=>{"use strict";Ct();Ad=class extends ke{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 zb(QR(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Id(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();YR(Lb(r),{recursive:!0}),JR(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=Id(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=zb(Lb(XR(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Id(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 Hb={};Ie(Hb,{ZedAdapter:()=>Nd});import{readFileSync as Ad,writeFileSync as FR,mkdirSync as UR}from"node:fs";import{resolve as Fb,dirname as Ub}from"node:path";import{fileURLToPath as HR}from"node:url";import{homedir as ZR}from"node:os";var Nd,Zb=x(()=>{"use strict";Ct();Nd=class extends ke{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 Fb(ZR(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Ad(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();UR(Ub(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=Ad(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=Fb(Ub(HR(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return Ad(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 Nd,Hb=x(()=>{"use strict";Nd="mcp__(?!.*context-mode)"});var qb={};ze(qb,{QwenCodeAdapter:()=>Dd});import{readFileSync as eC,writeFileSync as tC,existsSync as rC}from"node:fs";import{resolve as Zb,join as nC}from"node:path";import{homedir as Bb}from"node:os";var Dd,Vb=x(()=>{"use strict";Xl();Hb();Sr();Dd=class extends Rs{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 Zb(Bb(),".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",Nd].join("|"),hooks:[{type:"command",command:xe(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:xe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=eC(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){tC(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 m=d.hooks??[];return m.some(p=>p.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(p.command))?m.every(p=>{if(!p.command)return!0;let f=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),y=f||g;return y?rC(y[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",Nd].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:xe(`${e}/hooks/${a}`)}]},d=n[i];if(d&&Array.isArray(d)){let l=d.findIndex(m=>m.hooks?.some(p=>p.command?.includes(a))??!1);l>=0?(d[l]=u,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:Zb(nC(Bb(),".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 Wb={};ze(Wb,{OMPAdapter:()=>zd});import{readFileSync as Md,writeFileSync as sC,mkdirSync as oC}from"node:fs";import{resolve as jd,dirname as iC}from"node:path";import{homedir as aC}from"node:os";var zd,Gb=x(()=>{"use strict";Ct();zd=class extends ke{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??jd(aC(),".omp","agent")}getSettingsPath(){return jd(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Md(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();oC(iC(r),{recursive:!0}),sC(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=Md(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=jd(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(Md(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 Dd,Bb=x(()=>{"use strict";Dd="mcp__(?!.*context-mode)"});var Wb={};Ie(Wb,{QwenCodeAdapter:()=>Md});import{readFileSync as BR,writeFileSync as qR,existsSync as VR}from"node:fs";import{resolve as qb,join as WR}from"node:path";import{homedir as Vb}from"node:os";var Md,Gb=x(()=>{"use strict";Ql();Bb();Sr();Md=class extends Rs{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 qb(Vb(),".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",Dd].join("|"),hooks:[{type:"command",command:xe(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:xe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:xe(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=BR(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){qR(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 m=d.hooks??[];return m.some(p=>p.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(p.command))?m.every(p=>{if(!p.command)return!0;let f=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),y=f||g;return y?VR(y[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",Dd].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:xe(`${e}/hooks/${a}`)}]},d=n[i];if(d&&Array.isArray(d)){let l=d.findIndex(m=>m.hooks?.some(p=>p.command?.includes(a))??!1);l>=0?(d[l]=u,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:qb(WR(Vb(),".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 Kb={};Ie(Kb,{OMPAdapter:()=>Ld});import{readFileSync as jd,writeFileSync as GR,mkdirSync as KR}from"node:fs";import{resolve as zd,dirname as JR}from"node:path";import{homedir as YR}from"node:os";var Ld,Jb=x(()=>{"use strict";Ct();Ld=class extends ke{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??zd(YR(),".omp","agent")}getSettingsPath(){return zd(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=jd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();KR(JR(r),{recursive:!0}),GR(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=jd(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=zd(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(jd(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 Kb={};ze(Kb,{PiAdapter:()=>Hd});import{readFileSync as Ld,writeFileSync as cC,mkdirSync as uC}from"node:fs";import{resolve as Fd,dirname as lC}from"node:path";import{homedir as Ud}from"node:os";var Hd,Jb=x(()=>{"use strict";Ct();Hd=class extends ke{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 Fd(Ud(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Ld(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();uC(lC(r),{recursive:!0}),cC(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=Fd(Ud(),".pi","extensions","context-mode","package.json");try{return JSON.parse(Ld(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=Fd(Ud(),".pi","extensions","context-mode","package.json");return JSON.parse(Ld(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 Yb={};Ie(Yb,{PiAdapter:()=>Zd});import{readFileSync as Fd,writeFileSync as XR,mkdirSync as QR}from"node:fs";import{resolve as Ud,dirname as eC}from"node:path";import{homedir as Hd}from"node:os";var Zd,Xb=x(()=>{"use strict";Ct();Zd=class extends ke{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 Ud(Hd(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Fd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();QR(eC(r),{recursive:!0}),XR(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=Ud(Hd(),".pi","extensions","context-mode","package.json");try{return JSON.parse(Fd(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=Ud(Hd(),".pi","extensions","context-mode","package.json");return JSON.parse(Fd(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 Wa={};ze(Wa,{PLATFORM_ENV_VARS:()=>Ms,__resetClaudeCodePluginCacheForTests:()=>mC,__seedClaudeCodePluginCacheMissForTests:()=>fC,detectPlatform:()=>ir,foreignIdentificationEnv:()=>_C,foreignWorkspaceEnv:()=>yC,getAdapter:()=>Bo,getEnvVarNames:()=>gC,getSessionDirSegments:()=>Bd,workspaceEnvVarsFor:()=>Zd});import{existsSync as Ot,readFileSync as dC}from"node:fs";import{resolve as vt}from"node:path";import{homedir as Yb}from"node:os";function pC(){if(Fn!==null)return Fn!=="miss"&&Fn.hasCM;try{let t=vt(Yb(),".claude","plugins","installed_plugins.json"),e=dC(t,"utf-8"),r=JSON.parse(e),s=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(o=>o.includes("context-mode"));return Fn={hasCM:s},s}catch{return Fn="miss",!1}}function mC(){Fn=null}function fC(){Fn="miss"}function gC(t){return(Ms.get(t)??[]).map(e=>e.name)}function Zd(t){return(Ms.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function yC(t){let e=new Set;for(let[r,n]of Ms)if(r!==t)for(let s of n)s.role==="workspace"&&e.add(s.name);return e}function _C(t){let e=new Set;for(let[r,n]of Ms)if(r!==t)for(let s of n)s.role==="identification"&&e.add(s.name);return e}function Bd(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 ir(t){if(t?.name){let n=N_[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 Ms)if(s.some(o=>o.detect!==!1&&process.env[o.name]))return n==="vscode-copilot"&&pC()?{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=Yb();return Ot(vt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ot(vt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ot(vt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ot(vt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ot(vt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Ot(vt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ot(vt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ot(vt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ot(vt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ot(vt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ot(vt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ot(vt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ot(vt(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 Bo(t){let e=t??ir().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(sd(),nd));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(J_(),K_));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(eb(),Q_));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(nb(),rb));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(ub(),cb));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(fb(),mb));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(_b(),yb));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(Tb(),$b));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(Cb(),Rb));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(jb(),Mb));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(Ub(),Fb));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(Vb(),qb));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(Gb(),Wb));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(Jb(),Kb));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(sd(),nd));return new r}}}var Fn,hC,Ms,Un=x(()=>{"use strict";D_();Fn=null;hC=[["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"}]]],Ms=new Map(hC)});var ie,qd,j,kr,qo=x(()=>{(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})})(qd||(qd={}));j=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kr=t=>{switch(typeof t){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(t)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(t)?j.array:t===null?j.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?j.promise:typeof Map<"u"&&t instanceof Map?j.map:typeof Set<"u"&&t instanceof Set?j.set:typeof Date<"u"&&t instanceof Date?j.date:j.object;default:return j.unknown}}});var O,bC,xt,Ga=x(()=>{qo();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"]),bC=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),xt=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()}};xt.create=t=>new xt(t)});var vC,Mr,Vd=x(()=>{Ga();qo();vC=(t,e)=>{let r;switch(t.code){case O.invalid_type:t.received===j.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,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}},Mr=vC});function xC(t){Xb=t}function js(){return Xb}var Xb,Ka=x(()=>{Vd();Xb=Mr});function N(t,e){let r=js(),n=Vo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Mr?void 0:Mr].filter(s=>!!s)});t.common.issues.push(n)}var Vo,SC,Ye,G,Hn,at,Ja,Ya,sn,zs,Wd=x(()=>{Ka();Vd();Vo=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}},SC=[];Ye=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 G;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 G;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}}},G=Object.freeze({status:"aborted"}),Hn=t=>({status:"dirty",value:t}),at=t=>({status:"valid",value:t}),Ja=t=>t.status==="aborted",Ya=t=>t.status==="dirty",sn=t=>t.status==="valid",zs=t=>typeof Promise<"u"&&t instanceof Promise});var Qb=x(()=>{});var F,ev=x(()=>{(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 sv(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 LC(t){return new RegExp(`^${sv(t)}$`)}function ov(t){let e=`${nv}T${sv(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 FC(t,e){return!!((e==="v4"||!e)&&IC.test(t)||(e==="v6"||!e)&&NC.test(t))}function UC(t,e){if(!PC.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 HC(t,e){return!!((e==="v4"||!e)&&AC.test(t)||(e==="v6"||!e)&&DC.test(t))}function ZC(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 Ls(t){if(t instanceof kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=St.create(Ls(n))}return new kt({...t._def,shape:()=>e})}else return t instanceof Lr?new Lr({...t._def,type:Ls(t.element)}):t instanceof St?St.create(Ls(t.unwrap())):t instanceof Er?Er.create(Ls(t.unwrap())):t instanceof wr?wr.create(t.items.map(e=>Ls(e))):t}function Kd(t,e){let r=kr(t),n=kr(e);if(t===e)return{valid:!0,data:t};if(r===j.object&&n===j.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=Kd(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===j.array&&n===j.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=Kd(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===j.date&&n===j.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function iv(t,e){return new Qn({values:t,typeName:I.ZodEnum,...Q(e)})}function rv(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function av(t,e={},r){return t?an.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=rv(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=rv(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):an.create()}var Zt,tv,te,kC,wC,EC,$C,TC,PC,RC,CC,OC,Gd,IC,AC,NC,DC,MC,jC,nv,zC,on,Zn,Bn,qn,Vn,Fs,Wn,Gn,an,zr,ar,Us,Lr,kt,Kn,jr,Xa,Jn,wr,Qa,Hs,Zs,ec,Yn,Xn,Qn,es,cn,Bt,St,Er,ts,rs,Bs,BC,Wo,Go,ns,qC,I,VC,cv,uv,WC,GC,lv,KC,JC,YC,XC,QC,eO,tO,rO,nO,Jd,sO,oO,iO,aO,cO,uO,lO,dO,pO,mO,fO,hO,gO,yO,_O,bO,vO,xO,SO,kO,wO,EO,$O,TO,dv=x(()=>{Ga();Ka();ev();Wd();qo();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}},tv=(t,e)=>{if(sn(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 xt(t.common.issues);return this._error=r,this._error}}};te=class{get description(){return this._def.description}_getType(e){return kr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:kr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ye,ctx:{common:e.parent.common,data:e.data,parsedType:kr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(zs(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:kr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return tv(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:kr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return sn(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=>sn(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:kr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(zs(s)?s:Promise.resolve(s));return tv(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 St.create(this,this._def)}nullable(){return Er.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Lr.create(this)}promise(){return cn.create(this,this._def)}or(e){return Kn.create([this,e],this._def)}and(e){return Jn.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 ts({...Q(this._def),innerType:this,defaultValue:r,typeName:I.ZodDefault})}brand(){return new Wo({typeName:I.ZodBranded,type:this,...Q(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new rs({...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 Go.create(this,e)}readonly(){return ns.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},kC=/^c[^\s-]{8,}$/i,wC=/^[0-9a-z]+$/,EC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,$C=/^[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,TC=/^[a-z0-9_-]{21}$/i,PC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,RC=/^[-+]?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)?)??$/,CC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,OC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",IC=/^(?:(?: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])$/,AC=/^(?:(?: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])$/,NC=/^(([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]))$/,DC=/^(([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])$/,MC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,jC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nv="((\\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])))",zC=new RegExp(`^${nv}$`);on=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:j.string,received:o.parsedType}),G}let n=new Ye,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")CC.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")Gd||(Gd=new RegExp(OC,"u")),Gd.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")$C.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")TC.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")kC.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")wC.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")EC.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"?ov(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"?zC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?LC(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"?RC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"duration",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?FC(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"?UC(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"?HC(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"?MC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?jC.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}};on.create=t=>new on({checks:[],typeName:I.ZodString,coerce:t?.coerce??!1,...Q(t)});Zn=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)!==j.number){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:j.number,received:o.parsedType}),G}let n,s=new Ye;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"?ZC(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)}};Zn.create=t=>new Zn({checks:[],typeName:I.ZodNumber,coerce:t?.coerce||!1,...Q(t)});Bn=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)!==j.bigint)return this._getInvalidInput(e);let n,s=new Ye;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:j.bigint,received:r.parsedType}),G}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}};Bn.create=t=>new Bn({checks:[],typeName:I.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});qn=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.boolean,received:n.parsedType}),G}return at(e.data)}};qn.create=t=>new qn({typeName:I.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});Vn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:j.date,received:o.parsedType}),G}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_date}),G}let n=new Ye,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}};Vn.create=t=>new Vn({checks:[],coerce:t?.coerce||!1,typeName:I.ZodDate,...Q(t)});Fs=class extends te{_parse(e){if(this._getType(e)!==j.symbol){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.symbol,received:n.parsedType}),G}return at(e.data)}};Fs.create=t=>new Fs({typeName:I.ZodSymbol,...Q(t)});Wn=class extends te{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.undefined,received:n.parsedType}),G}return at(e.data)}};Wn.create=t=>new Wn({typeName:I.ZodUndefined,...Q(t)});Gn=class extends te{_parse(e){if(this._getType(e)!==j.null){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.null,received:n.parsedType}),G}return at(e.data)}};Gn.create=t=>new Gn({typeName:I.ZodNull,...Q(t)});an=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return at(e.data)}};an.create=t=>new an({typeName:I.ZodAny,...Q(t)});zr=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return at(e.data)}};zr.create=t=>new zr({typeName:I.ZodUnknown,...Q(t)});ar=class extends te{_parse(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:j.never,received:r.parsedType}),G}};ar.create=t=>new ar({typeName:I.ZodNever,...Q(t)});Us=class extends te{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.void,received:n.parsedType}),G}return at(e.data)}};Us.create=t=>new Us({typeName:I.ZodVoid,...Q(t)});Lr=class t extends te{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==j.array)return N(r,{code:O.invalid_type,expected:j.array,received:r.parsedType}),G;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=>Ye.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Zt(r,i,r.path,a)));return Ye.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)}};Lr.create=(t,e)=>new Lr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...Q(e)});kt=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)!==j.object){let u=this._getOrReturnCtx(e);return N(u,{code:O.invalid_type,expected:j.object,received:u.parsedType}),G}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ar&&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 ar){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,m=await d.value;u.push({key:l,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>Ye.mergeObjectSync(n,u)):Ye.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 Ls(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 St;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return iv(ie.objectKeys(this.shape))}};kt.create=(t,e)=>new kt({shape:()=>t,unknownKeys:"strip",catchall:ar.create(),typeName:I.ZodObject,...Q(e)});kt.strictCreate=(t,e)=>new kt({shape:()=>t,unknownKeys:"strict",catchall:ar.create(),typeName:I.ZodObject,...Q(e)});kt.lazycreate=(t,e)=>new kt({shape:t,unknownKeys:"strip",catchall:ar.create(),typeName:I.ZodObject,...Q(e)});Kn=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 xt(a.ctx.common.issues));return N(r,{code:O.invalid_union,unionErrors:i}),G}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 xt(c));return N(r,{code:O.invalid_union,unionErrors:a}),G}}get options(){return this._def.options}};Kn.create=(t,e)=>new Kn({options:t,typeName:I.ZodUnion,...Q(e)});jr=t=>t instanceof Yn?jr(t.schema):t instanceof Bt?jr(t.innerType()):t instanceof Xn?[t.value]:t instanceof Qn?t.options:t instanceof es?ie.objectValues(t.enum):t instanceof ts?jr(t._def.innerType):t instanceof Wn?[void 0]:t instanceof Gn?[null]:t instanceof St?[void 0,...jr(t.unwrap())]:t instanceof Er?[null,...jr(t.unwrap())]:t instanceof Wo||t instanceof ns?jr(t.unwrap()):t instanceof rs?jr(t._def.innerType):[],Xa=class t extends te{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.object)return N(r,{code:O.invalid_type,expected:j.object,received:r.parsedType}),G;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]}),G)}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=jr(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)})}};Jn=class extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(Ja(o)||Ja(i))return G;let a=Kd(o.value,i.value);return a.valid?((Ya(o)||Ya(i))&&r.dirty(),{status:r.value,value:a.data}):(N(n,{code:O.invalid_intersection_types}),G)};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}))}};Jn.create=(t,e,r)=>new Jn({left:t,right:e,typeName:I.ZodIntersection,...Q(r)});wr=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.array)return N(n,{code:O.invalid_type,expected:j.array,received:n.parsedType}),G;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"}),G;!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=>Ye.mergeArray(r,i)):Ye.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};wr.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wr({items:t,typeName:I.ZodTuple,rest:null,...Q(e)})};Qa=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!==j.object)return N(n,{code:O.invalid_type,expected:j.object,received:n.parsedType}),G;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?Ye.mergeObjectAsync(r,s):Ye.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:on.create(),valueType:e,typeName:I.ZodRecord,...Q(r)})}},Hs=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!==j.map)return N(n,{code:O.invalid_type,expected:j.map,received:n.parsedType}),G;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 G;(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 G;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Hs.create=(t,e,r)=>new Hs({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!==j.set)return N(n,{code:O.invalid_type,expected:j.set,received:n.parsedType}),G;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 G;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)});ec=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.function)return N(r,{code:O.invalid_type,expected:j.function,received:r.parsedType}),G;function n(a,c){return Vo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,js(),Mr].filter(u=>!!u),issueData:{code:O.invalid_arguments,argumentsError:c}})}function s(a,c){return Vo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,js(),Mr].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 cn){let a=this;return at(async function(...c){let u=new xt([]),d=await a._def.args.parseAsync(c,o).catch(h=>{throw u.addIssue(n(c,h)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(h=>{throw u.addIssue(s(l,h)),u})})}else{let a=this;return at(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new xt([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new xt([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:wr.create(e).rest(zr.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||wr.create([]).rest(zr.create()),returns:r||zr.create(),typeName:I.ZodFunction,...Q(n)})}},Yn=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})}};Yn.create=(t,e)=>new Yn({getter:t,typeName:I.ZodLazy,...Q(e)});Xn=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}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};Xn.create=(t,e)=>new Xn({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}),G}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}),G}return at(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=iv;es=class extends te{_parse(e){let r=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==j.string&&n.parsedType!==j.number){let s=ie.objectValues(r);return N(n,{expected:ie.joinValues(s),received:n.parsedType,code:O.invalid_type}),G}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}),G}return at(e.data)}get enum(){return this._def.values}};es.create=(t,e)=>new es({values:t,typeName:I.ZodNativeEnum,...Q(e)});cn=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.promise&&r.common.async===!1)return N(r,{code:O.invalid_type,expected:j.promise,received:r.parsedType}),G;let n=r.parsedType===j.promise?r.data:Promise.resolve(r.data);return at(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};cn.create=(t,e)=>new cn({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 G;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?G:c.status==="dirty"?Hn(c.value):r.value==="dirty"?Hn(c.value):c});{if(r.value==="aborted")return G;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?G:a.status==="dirty"?Hn(a.value):r.value==="dirty"?Hn(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"?G:(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"?G:(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(!sn(i))return G;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=>sn(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):G);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)});St=class extends te{_parse(e){return this._getType(e)===j.undefined?at(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};St.create=(t,e)=>new St({innerType:t,typeName:I.ZodOptional,...Q(e)});Er=class extends te{_parse(e){return this._getType(e)===j.null?at(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Er.create=(t,e)=>new Er({innerType:t,typeName:I.ZodNullable,...Q(e)});ts=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===j.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ts.create=(t,e)=>new ts({innerType:t,typeName:I.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});rs=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 zs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};rs.create=(t,e)=>new rs({innerType:t,typeName:I.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});Bs=class extends te{_parse(e){if(this._getType(e)!==j.nan){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.nan,received:n.parsedType}),G}return{status:"valid",value:e.data}}};Bs.create=t=>new Bs({typeName:I.ZodNaN,...Q(t)});BC=Symbol("zod_brand"),Wo=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}},Go=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"?G:o.status==="dirty"?(r.dirty(),Hn(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"?G: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})}},ns=class extends te{_parse(e){let r=this._def.innerType._parse(e),n=s=>(sn(s)&&(s.value=Object.freeze(s.value)),s);return zs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};ns.create=(t,e)=>new ns({innerType:t,typeName:I.ZodReadonly,...Q(e)});qC={object:kt.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={}));VC=(t,e={message:`Input not instance of ${t.name}`})=>av(r=>r instanceof t,e),cv=on.create,uv=Zn.create,WC=Bs.create,GC=Bn.create,lv=qn.create,KC=Vn.create,JC=Fs.create,YC=Wn.create,XC=Gn.create,QC=an.create,eO=zr.create,tO=ar.create,rO=Us.create,nO=Lr.create,Jd=kt.create,sO=kt.strictCreate,oO=Kn.create,iO=Xa.create,aO=Jn.create,cO=wr.create,uO=Qa.create,lO=Hs.create,dO=Zs.create,pO=ec.create,mO=Yn.create,fO=Xn.create,hO=Qn.create,gO=es.create,yO=cn.create,_O=Bt.create,bO=St.create,vO=Er.create,xO=Bt.createWithPreprocess,SO=Go.create,kO=()=>cv().optional(),wO=()=>uv().optional(),EO=()=>lv().optional(),$O={string:(t=>on.create({...t,coerce:!0})),number:(t=>Zn.create({...t,coerce:!0})),boolean:(t=>qn.create({...t,coerce:!0})),bigint:(t=>Bn.create({...t,coerce:!0})),date:(t=>Vn.create({...t,coerce:!0}))},TO=G});var U={};ze(U,{BRAND:()=>BC,DIRTY:()=>Hn,EMPTY_PATH:()=>SC,INVALID:()=>G,NEVER:()=>TO,OK:()=>at,ParseStatus:()=>Ye,Schema:()=>te,ZodAny:()=>an,ZodArray:()=>Lr,ZodBigInt:()=>Bn,ZodBoolean:()=>qn,ZodBranded:()=>Wo,ZodCatch:()=>rs,ZodDate:()=>Vn,ZodDefault:()=>ts,ZodDiscriminatedUnion:()=>Xa,ZodEffects:()=>Bt,ZodEnum:()=>Qn,ZodError:()=>xt,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>ec,ZodIntersection:()=>Jn,ZodIssueCode:()=>O,ZodLazy:()=>Yn,ZodLiteral:()=>Xn,ZodMap:()=>Hs,ZodNaN:()=>Bs,ZodNativeEnum:()=>es,ZodNever:()=>ar,ZodNull:()=>Gn,ZodNullable:()=>Er,ZodNumber:()=>Zn,ZodObject:()=>kt,ZodOptional:()=>St,ZodParsedType:()=>j,ZodPipeline:()=>Go,ZodPromise:()=>cn,ZodReadonly:()=>ns,ZodRecord:()=>Qa,ZodSchema:()=>te,ZodSet:()=>Zs,ZodString:()=>on,ZodSymbol:()=>Fs,ZodTransformer:()=>Bt,ZodTuple:()=>wr,ZodType:()=>te,ZodUndefined:()=>Wn,ZodUnion:()=>Kn,ZodUnknown:()=>zr,ZodVoid:()=>Us,addIssueToContext:()=>N,any:()=>QC,array:()=>nO,bigint:()=>GC,boolean:()=>lv,coerce:()=>$O,custom:()=>av,date:()=>KC,datetimeRegex:()=>ov,defaultErrorMap:()=>Mr,discriminatedUnion:()=>iO,effect:()=>_O,enum:()=>hO,function:()=>pO,getErrorMap:()=>js,getParsedType:()=>kr,instanceof:()=>VC,intersection:()=>aO,isAborted:()=>Ja,isAsync:()=>zs,isDirty:()=>Ya,isValid:()=>sn,late:()=>qC,lazy:()=>mO,literal:()=>fO,makeIssue:()=>Vo,map:()=>lO,nan:()=>WC,nativeEnum:()=>gO,never:()=>tO,null:()=>XC,nullable:()=>vO,number:()=>uv,object:()=>Jd,objectUtil:()=>qd,oboolean:()=>EO,onumber:()=>wO,optional:()=>bO,ostring:()=>kO,pipeline:()=>SO,preprocess:()=>xO,promise:()=>yO,quotelessJson:()=>bC,record:()=>uO,set:()=>dO,setErrorMap:()=>xC,strictObject:()=>sO,string:()=>cv,symbol:()=>JC,transformer:()=>_O,tuple:()=>cO,undefined:()=>YC,union:()=>oO,unknown:()=>eO,util:()=>ie,void:()=>rO});var tc=x(()=>{Ka();Wd();Qb();qo();dv();Ga()});var Ko=x(()=>{tc()});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(rc,t),rc}var RO,Fr,rc,qs=x(()=>{RO=Object.freeze({status:"aborted"});Fr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},rc={}});var ae={};ze(ae,{BIGINT_FORMAT_RANGES:()=>mv,Class:()=>Xd,NUMBER_FORMAT_RANGES:()=>op,aborted:()=>os,allowsEval:()=>rp,assert:()=>NO,assertEqual:()=>CO,assertIs:()=>IO,assertNever:()=>AO,assertNotEqual:()=>OO,assignProp:()=>tp,cached:()=>Xo,captureStackTrace:()=>sc,cleanEnum:()=>WO,cleanRegex:()=>ei,clone:()=>At,createTransparentProxy:()=>FO,defineLazy:()=>we,esc:()=>ss,escapeRegex:()=>un,extend:()=>ZO,finalizeIssue:()=>cr,floatSafeRemainder:()=>ep,getElementAtPath:()=>DO,getEnumValues:()=>Yo,getLengthableOrigin:()=>ti,getParsedType:()=>LO,getSizableOrigin:()=>fv,isObject:()=>Vs,isPlainObject:()=>Ws,issue:()=>ip,joinValues:()=>nc,jsonStringifyReplacer:()=>Qd,merge:()=>BO,normalizeParams:()=>K,nullish:()=>Qo,numKeys:()=>zO,omit:()=>HO,optionalKeys:()=>sp,partial:()=>qO,pick:()=>UO,prefixIssues:()=>$r,primitiveTypes:()=>pv,promiseAllObject:()=>MO,propertyKeyTypes:()=>np,randomString:()=>jO,required:()=>VO,stringifyPrimitive:()=>oc,unwrapMessage:()=>Jo});function CO(t){return t}function OO(t){return t}function IO(t){}function AO(t){throw new Error}function NO(t){}function Yo(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 nc(t,e="|"){return t.map(r=>oc(r)).join(e)}function Qd(t,e){return typeof e=="bigint"?e.toString():e}function Xo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Qo(t){return t==null}function ei(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ep(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 we(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 tp(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function DO(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function MO(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 jO(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function ss(t){return JSON.stringify(t)}function Vs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ws(t){if(Vs(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Vs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function zO(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function un(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 K(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 FO(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 oc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function sp(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function UO(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 HO(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 ZO(t,e){if(!Ws(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 tp(this,"shape",n),n},checks:[]};return At(t,r)}function BO(t,e){return At(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return tp(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function qO(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 VO(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 os(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function $r(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Jo(t){return typeof t=="string"?t:t?.message}function cr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=Jo(t.inst?._zod.def?.error?.(t))??Jo(e?.error?.(t))??Jo(r.customError?.(t))??Jo(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function fv(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function ti(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function ip(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function WO(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var sc,rp,LO,np,pv,op,mv,Xd,Tr=x(()=>{sc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};rp=Xo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});LO=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}`)}},np=new Set(["string","number","symbol"]),pv=new Set(["string","number","bigint","boolean","symbol","undefined"]);op={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]},mv={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Xd=class{constructor(...e){}}});function ap(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 cp(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 hv,ic,ri,up=x(()=>{qs();Tr();hv=(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,Qd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ic=w("$ZodError",hv),ri=w("$ZodError",hv,{Parent:Error})});var lp,dp,pp,mp,fp,is,hp,as,gp=x(()=>{qs();up();Tr();lp=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 Fr;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>cr(c,o,It())));throw sc(a,s?.callee),a}return i.value},dp=lp(ri),pp=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=>cr(c,o,It())));throw sc(a,s?.callee),a}return i.value},mp=pp(ri),fp=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 Fr;return o.issues.length?{success:!1,error:new(t??ic)(o.issues.map(i=>cr(i,s,It())))}:{success:!0,data:o.value}},is=fp(ri),hp=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=>cr(i,s,It())))}:{success:!0,data:o.value}},as=hp(ri)});function Ev(){return new RegExp(KO,"u")}function Dv(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 Mv(t){return new RegExp(`^${Dv(t)}$`)}function jv(t){let e=Dv({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(`^${Av}T(?:${n})$`)}var gv,yv,_v,bv,vv,xv,Sv,kv,yp,wv,KO,$v,Tv,Pv,Rv,Cv,_p,Ov,Iv,Av,Nv,zv,Lv,Fv,Uv,Hv,Zv,Bv,cc=x(()=>{gv=/^[cC][^\s-]{8,}$/,yv=/^[0-9a-z]+$/,_v=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,bv=/^[0-9a-vA-V]{20}$/,vv=/^[A-Za-z0-9]{27}$/,xv=/^[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)?)?)$/,kv=/^([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})$/,yp=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)$/,wv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,KO="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";$v=/^(?:(?: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])$/,Tv=/^(([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})$/,Pv=/^((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])$/,Rv=/^(([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])$/,Cv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,_p=/^[A-Za-z0-9_-]*$/,Ov=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Iv=/^\+(?:[0-9]){6,14}[0-9]$/,Av="(?:(?:\\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])))",Nv=new RegExp(`^${Av}$`);zv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Lv=/^\d+$/,Fv=/^-?\d+(?:\.\d+)?/i,Uv=/true|false/i,Hv=/null/i,Zv=/^[^A-Z]*$/,Bv=/^[^a-z]*$/});var Xe,qv,bp,vp,Vv,Wv,Gv,Kv,Jv,ni,Yv,Xv,Qv,ex,tx,rx,nx,uc=x(()=>{qs();cc();Tr();Xe=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),qv={number:"number",bigint:"bigint",object:"date"},bp=w("$ZodCheckLessThan",(t,e)=>{Xe.init(t,e);let r=qv[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})}}),vp=w("$ZodCheckGreaterThan",(t,e)=>{Xe.init(t,e);let r=qv[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})}}),Vv=w("$ZodCheckMultipleOf",(t,e)=>{Xe.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):ep(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})}}),Wv=w("$ZodCheckNumberFormat",(t,e)=>{Xe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=op[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=Lv)}),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})}}),Gv=w("$ZodCheckMaxLength",(t,e)=>{var r;Xe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Qo(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=ti(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Kv=w("$ZodCheckMinLength",(t,e)=>{var r;Xe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Qo(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=ti(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),Jv=w("$ZodCheckLengthEquals",(t,e)=>{var r;Xe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Qo(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=ti(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})}}),ni=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Xe.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=()=>{})}),Yv=w("$ZodCheckRegex",(t,e)=>{ni.init(t,e),t._zod.check=r=>{e.pattern.lastIndex=0,!e.pattern.test(r.value)&&r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),Xv=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Zv),ni.init(t,e)}),Qv=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Bv),ni.init(t,e)}),ex=w("$ZodCheckIncludes",(t,e)=>{Xe.init(t,e);let r=un(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})}}),tx=w("$ZodCheckStartsWith",(t,e)=>{Xe.init(t,e);let r=new RegExp(`^${un(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})}}),rx=w("$ZodCheckEndsWith",(t,e)=>{Xe.init(t,e);let r=new RegExp(`.*${un(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})}}),nx=w("$ZodCheckOverwrite",(t,e)=>{Xe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var lc,xp=x(()=>{lc=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
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 Ka={};Ie(Ka,{PLATFORM_ENV_VARS:()=>Ms,__resetClaudeCodePluginCacheForTests:()=>nC,__seedClaudeCodePluginCacheMissForTests:()=>sC,detectPlatform:()=>It,foreignIdentificationEnv:()=>cC,foreignWorkspaceEnv:()=>aC,getAdapter:()=>Vo,getEnvVarNames:()=>iC,getSessionDirSegments:()=>qo,workspaceEnvVarsFor:()=>Bd});import{existsSync as Ot,readFileSync as tC}from"node:fs";import{resolve as vt}from"node:path";import{homedir as Qb}from"node:os";function rC(){if(Hn!==null)return Hn!=="miss"&&Hn.hasCM;try{let t=vt(Qb(),".claude","plugins","installed_plugins.json"),e=tC(t,"utf-8"),r=JSON.parse(e),s=[...Object.keys(r.plugins??{}),...Object.keys(r.enabledPlugins??{})].some(o=>o.includes("context-mode"));return Hn={hasCM:s},s}catch{return Hn="miss",!1}}function nC(){Hn=null}function sC(){Hn="miss"}function iC(t){return(Ms.get(t)??[]).map(e=>e.name)}function Bd(t){return(Ms.get(t)??[]).filter(e=>e.role==="workspace").map(e=>e.name)}function aC(t){let e=new Set;for(let[r,n]of Ms)if(r!==t)for(let s of n)s.role==="workspace"&&e.add(s.name);return e}function cC(t){let e=new Set;for(let[r,n]of Ms)if(r!==t)for(let s of n)s.role==="identification"&&e.add(s.name);return e}function qo(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 It(t){if(t?.name){let n=M_[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 Ms)if(s.some(o=>o.detect!==!1&&process.env[o.name]))return n==="vscode-copilot"&&rC()?{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=Qb();return Ot(vt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ot(vt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ot(vt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ot(vt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ot(vt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Ot(vt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ot(vt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ot(vt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ot(vt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ot(vt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ot(vt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ot(vt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ot(vt(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 Vo(t){let e=t??It().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(od(),sd));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(X_(),Y_));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(rb(),tb));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(ob(),sb));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(db(),lb));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(gb(),hb));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(vb(),bb));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(Rb(),Pb));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(Ib(),Ob));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(Lb(),zb));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(Zb(),Hb));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(Gb(),Wb));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(Jb(),Kb));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(Xb(),Yb));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(od(),sd));return new r}}}var Hn,oC,Ms,on=x(()=>{"use strict";j_();Hn=null;oC=[["claude-code",[{name:"CLAUDE_CODE_ENTRYPOINT",role:"identification"},{name:"CLAUDE_PLUGIN_ROOT",role:"identification"},{name:"CLAUDE_PROJECT_DIR",role:"workspace"},{name:"CLAUDE_SESSION_ID",role:"identification"}]],["antigravity",[{name:"ANTIGRAVITY_CLI_ALIAS",role:"identification"}]],["cursor",[{name:"CURSOR_CWD",role:"workspace"},{name:"CURSOR_TRACE_ID",role:"identification"},{name:"CURSOR_CLI",role:"identification"}]],["kilo",[{name:"KILO",role:"identification"},{name:"KILO_PID",role:"identification"}]],["opencode",[{name:"OPENCODE_PROJECT_DIR",role:"workspace"},{name:"OPENCODE_CLIENT",role:"identification"},{name:"OPENCODE_TERMINAL",role:"identification"},{name:"OPENCODE",role:"identification"},{name:"OPENCODE_PID",role:"identification"}]],["zed",[{name:"ZED_SESSION_ID",role:"identification"},{name:"ZED_TERM",role:"identification"}]],["codex",[{name:"CODEX_THREAD_ID",role:"identification"},{name:"CODEX_CI",role:"identification"}]],["gemini-cli",[{name:"GEMINI_PROJECT_DIR",role:"workspace"},{name:"GEMINI_CLI",role:"identification"}]],["vscode-copilot",[{name:"VSCODE_CWD",role:"workspace"},{name:"VSCODE_PID",role:"identification"}]],["jetbrains-copilot",[{name:"IDEA_INITIAL_DIRECTORY",role:"workspace"}]],["qwen-code",[{name:"QWEN_PROJECT_DIR",role:"workspace"}]],["omp",[{name:"PI_CODING_AGENT_DIR",role:"workspace"}]],["pi",[{name:"PI_WORKSPACE_DIR",role:"workspace",detect:!1},{name:"PI_PROJECT_DIR",role:"workspace",detect:!1},{name:"PI_CONFIG_DIR",role:"identification"},{name:"PI_SESSION_FILE",role:"identification"},{name:"PI_COMPILED",role:"identification"}]]],Ms=new Map(oC)});import{resolve as Wo}from"node:path";import{homedir as qd}from"node:os";function Ze(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?Wo(qd(),e.replace(/^~[/\\]?/,"")):Wo(e):Wo(qd(),".claude")}function uC(t=process.env){return Wo(Ze(t),"settings.json")}function Vd(t=process.env){let e=[],r=It();if(r.platform!=="claude-code"){let s=qo(r.platform);s&&s.length>0&&e.push(Wo(qd(),...s,"settings.json"))}let n=uC(t);return e.includes(n)||e.push(n),e}var rn=x(()=>{"use strict";on()});var ev={};Ie(ev,{discoverSiblingMcpPids:()=>Ja,killSiblingMcpServers:()=>Ya,startupSiblingSweep:()=>vC});import{execFileSync as Wd}from"node:child_process";function pC(t){try{let e=Wd("ps",["-o","ppid=","-p",String(t)],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=Number.parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function mC(t){try{let e=Wd("powershell",["-NoProfile","-Command",`(Get-CimInstance Win32_Process -Filter "ProcessId=${t}").ParentProcessId`],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim(),r=Number.parseInt(e,10);return Number.isFinite(r)?r:NaN}catch{return NaN}}function fC(t){return process.platform==="win32"?mC(t):pC(t)}function _C(t){let e=new Set;for(let r of t.split(/\r?\n/)){let n=r.trim();if(!n||!/^\d+$/.test(n))continue;let s=Number.parseInt(n,10);Number.isFinite(s)&&s>0&&e.add(s)}return[...e]}function Ja(t){let e=t.platform??process.platform,r=t.runCommand??hC,n="";try{e==="win32"?n=r("powershell",["-NoProfile","-Command",dC]):n=r("pgrep",["-f",lC])}catch{return[]}let s=_C(n).filter(i=>i!==t.ownPid&&i!==t.ownPpid);if(!t.sameParentOnly)return s;let o=t.readPpid??fC;return s.filter(i=>{let a=o(i);return Number.isFinite(a)&&a===t.ownPpid})}function bC(t){return new Promise(e=>{setTimeout(e,t)})}async function Ya(t){let e=t.timeoutMs??1500,r=t.pollIntervalMs??100,n=t.isAlive??gC,s=t.sendSignal??yC,o={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0};if(t.pids.length===0)return o;let i=new Set,a=new Set;for(let l of t.pids){n(l)&&(i.add(l),a.add(l));try{s(l,"SIGTERM")}catch(m){m?.code!=="ESRCH"&&a.delete(l)}}let c=Date.now()+e,u=0;for(;a.size>0&&Date.now()<c;){await bC(r);for(let l of[...a])n(l)||(a.delete(l),u++)}let d=0;for(let l of a){try{s(l,"SIGKILL")}catch(m){if(m?.code==="ESRCH"){u++;continue}continue}i.has(l)&&d++}return{terminatedBySigterm:u,terminatedBySigkill:d,totalKilled:u+d}}async function vC(t=process.env){let e={terminatedBySigterm:0,terminatedBySigkill:0,totalKilled:0},r=t.CONTEXT_MODE_STARTUP_SWEEP;if(r==="0"||r==="false")return e;try{let n=Ja({ownPid:process.pid,ownPpid:process.ppid,sameParentOnly:!0});return n.length===0?e:await Ya({pids:n})}catch{return e}}var lC,dC,hC,gC,yC,Gd=x(()=>{"use strict";lC="(node|bun).*(plugins/(cache|marketplaces)/.*context-mode.*start\\.mjs|context-mode/start\\.mjs|context-mode/server\\.bundle\\.mjs|bin/context-mode($|[^a-zA-Z0-9_-]))",dC=`Get-CimInstance Win32_Process -Filter "Name='node.exe' OR Name='bun.exe'" | Where-Object { $_.CommandLine -match 'plugins[\\\\/](cache|marketplaces)[\\\\/].*context-mode.*start\\.mjs|context-mode[\\\\/]start\\.mjs|context-mode[\\\\/]server\\.bundle\\.mjs|bin[\\\\/]context-mode($|[^a-zA-Z0-9_-])' } | Select-Object -ExpandProperty ProcessId`;hC=(t,e)=>Wd(t,[...e],{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}),gC=t=>{try{return process.kill(t,0),!0}catch{return!1}},yC=(t,e)=>{process.kill(t,e)}});var rv={};Ie(rv,{healClaudeJsonMcpArgs:()=>kC,healInstalledPlugins:()=>xC,healMcpJsonArgs:()=>Qa,healPluginJsonMcpServers:()=>Xa,healSettingsEnabledPlugins:()=>SC});import{existsSync as js,readFileSync as zs,writeFileSync as Go}from"node:fs";import{resolve as kr,sep as Jd}from"node:path";function xC({registryPath:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!js(t))return{healed:[],skipped:"no-registry"};let n;try{n=zs(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let s;try{s=JSON.parse(n)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}if(!s||typeof s!="object")return{healed:[],error:"bad-shape"};let o=s.plugins&&s.plugins[r]||[];if(!Array.isArray(o)||o.length===0)return{healed:[],skipped:"no-entry"};let i=[],a=null;for(let c of o){if(!c||typeof c!="object")continue;let u=c.installPath;if(!u||typeof u!="string")continue;let d=kr(u),l=kr(e)+Jd;if(!d.startsWith(l))continue;let m=kr(u,".claude-plugin","plugin.json");if(!js(m))continue;let h=null;try{let p=JSON.parse(zs(m,"utf-8"));p&&typeof p.version=="string"&&p.version&&(h=p.version)}catch{continue}h&&(a=h,c.version!==h&&(c.version=h,i.includes("entry-version")||i.push("entry-version")))}if(a){(!s.enabledPlugins||typeof s.enabledPlugins!="object"||Array.isArray(s.enabledPlugins))&&(s.enabledPlugins={});let c=s.enabledPlugins[r];(c==null||c===!1||c==="")&&(s.enabledPlugins[r]=!0,i.push("enabled-plugins"))}if(i.length>0)try{Go(t,JSON.stringify(s,null,2)+`
34
+ `,"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:i}}function SC({settingsPath:t,pluginKey:e}){if(!t||!js(t))return{healed:[],skipped:"no-settings"};let r;try{r=zs(t,"utf-8")}catch(i){return{healed:[],error:`read-failed: ${i&&i.message||i}`}}let n;try{n=JSON.parse(r)}catch(i){return{healed:[],error:`parse-failed: ${i&&i.message||i}`}}let s=[];(!n.enabledPlugins||typeof n.enabledPlugins!="object"||Array.isArray(n.enabledPlugins))&&(n.enabledPlugins={});let o=n.enabledPlugins[e];if(o===!1)return{healed:[],skipped:"explicit-opt-out"};if(o!==!0&&(n.enabledPlugins[e]=!0,s.push("enabled-plugins")),s.length>0)try{Go(t,JSON.stringify(n,null,2)+`
35
+ `,"utf-8")}catch(i){return{healed:[],error:`write-failed: ${i&&i.message||i}`}}return{healed:s}}function Xa({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=kr(t),s=kr(e)+Jd;if(!n.startsWith(s))return{healed:[],skipped:"outside-cache-root"};let o=kr(t,".claude-plugin","plugin.json");if(!js(o))return{healed:[],skipped:"no-plugin-json"};let i;try{i=zs(o,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],m=d.args,h=m.map(f=>typeof f!="string"?f:tv.test(f)&&/[/\\]start\.mjs$/.test(f)?Kd:f);if(h.some((f,g)=>f!==m[g])){d.args=h,l.push("plugin-json-args");try{Go(o,JSON.stringify(a,null,2)+`
36
+ `,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:l}}function Qa({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=kr(t),s=kr(e)+Jd;if(!n.startsWith(s))return{healed:[],skipped:"outside-cache-root"};let o=kr(t,".mcp.json");if(!js(o))return{healed:[],skipped:"no-mcp-json"};let i;try{i=zs(o,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],m=d.args,h=m.map(f=>typeof f!="string"?f:f==="./start.mjs"||f==="start.mjs"||tv.test(f)&&/[/\\]start\.mjs$/.test(f)?Kd:f);if(h.some((f,g)=>f!==m[g])){d.args=h,l.push("mcp-json-args");try{Go(o,JSON.stringify(a,null,2)+`
37
+ `,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:l}}function kC({dotClaudeJsonPath:t,pluginCacheParent:e,newPluginRoot:r}){if(!t||!js(t))return{healed:[],skipped:"no-claude-json"};let n;try{n=zs(t,"utf-8")}catch(c){return{healed:[],error:`read-failed: ${c&&c.message||c}`}}let s;try{s=JSON.parse(n)}catch(c){return{healed:[],error:`parse-failed: ${c&&c.message||c}`}}let o=s&&s.mcpServers;if(!o||typeof o!="object")return{healed:[],skipped:"no-mcp-servers"};let i=e.replace(/\\/g,"/"),a=!1;for(let c of Object.values(o))if(!(!c||typeof c!="object"||!Array.isArray(c.args)))for(let u=0;u<c.args.length;u++){let d=c.args[u];if(typeof d!="string")continue;let l=d.replace(/\\/g,"/");if(!l.startsWith(i+"/"))continue;let m=l.slice(i.length+1),h=m.indexOf("/");if(h<0)continue;let p=m.slice(h+1),f=kr(r,p);f!==d&&(c.args[u]=f,a=!0)}if(!a)return{healed:[]};try{Go(t,JSON.stringify(s,null,2),"utf-8")}catch(c){return{healed:[],error:`write-failed: ${c&&c.message||c}`}}return{healed:["claude-json-mcp-args"]}}var tv,Kd,Yd=x(()=>{"use strict";tv=/[/\\]context-mode-upgrade-\d+[/\\]/,Kd="${CLAUDE_PLUGIN_ROOT}/start.mjs"});var ae,Xd,j,wr,Ko=x(()=>{(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})(ae||(ae={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Xd||(Xd={}));j=ae.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),wr=t=>{switch(typeof t){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN(t)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":return Array.isArray(t)?j.array:t===null?j.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?j.promise:typeof Map<"u"&&t instanceof Map?j.map:typeof Set<"u"&&t instanceof Set?j.set:typeof Date<"u"&&t instanceof Date?j.date:j.object;default:return j.unknown}}});var O,$C,xt,ec=x(()=>{Ko();O=ae.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"]),$C=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),xt=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,ae.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()}};xt.create=t=>new xt(t)});var TC,jr,Qd=x(()=>{ec();Ko();TC=(t,e)=>{let r;switch(t.code){case O.invalid_type:t.received===j.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case O.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ae.jsonStringifyReplacer)}`;break;case O.unrecognized_keys:r=`Unrecognized key(s) in object: ${ae.joinValues(t.keys,", ")}`;break;case O.invalid_union:r="Invalid input";break;case O.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ae.joinValues(t.options)}`;break;case O.invalid_enum_value:r=`Invalid enum value. Expected ${ae.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}"`:ae.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,ae.assertNever(t)}return{message:r}},jr=TC});function PC(t){sv=t}function Ls(){return sv}var sv,tc=x(()=>{Qd();sv=jr});function N(t,e){let r=Ls(),n=Jo({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===jr?void 0:jr].filter(s=>!!s)});t.common.issues.push(n)}var Jo,RC,Ye,G,Zn,at,rc,nc,an,Fs,ep=x(()=>{tc();Qd();Jo=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}},RC=[];Ye=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 G;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 G;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}}},G=Object.freeze({status:"aborted"}),Zn=t=>({status:"dirty",value:t}),at=t=>({status:"valid",value:t}),rc=t=>t.status==="aborted",nc=t=>t.status==="dirty",an=t=>t.status==="valid",Fs=t=>typeof Promise<"u"&&t instanceof Promise});var ov=x(()=>{});var F,iv=x(()=>{(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 lv(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 VC(t){return new RegExp(`^${lv(t)}$`)}function dv(t){let e=`${uv}T${lv(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 WC(t,e){return!!((e==="v4"||!e)&&LC.test(t)||(e==="v6"||!e)&&UC.test(t))}function GC(t,e){if(!DC.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 KC(t,e){return!!((e==="v4"||!e)&&FC.test(t)||(e==="v6"||!e)&&HC.test(t))}function JC(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 Us(t){if(t instanceof kt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=St.create(Us(n))}return new kt({...t._def,shape:()=>e})}else return t instanceof Fr?new Fr({...t._def,type:Us(t.element)}):t instanceof St?St.create(Us(t.unwrap())):t instanceof $r?$r.create(Us(t.unwrap())):t instanceof Er?Er.create(t.items.map(e=>Us(e))):t}function rp(t,e){let r=wr(t),n=wr(e);if(t===e)return{valid:!0,data:t};if(r===j.object&&n===j.object){let s=ae.objectKeys(e),o=ae.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=rp(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===j.array&&n===j.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=rp(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===j.date&&n===j.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function pv(t,e){return new es({values:t,typeName:I.ZodEnum,...Q(e)})}function cv(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function mv(t,e={},r){return t?un.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=cv(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=cv(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):un.create()}var Bt,av,te,CC,OC,IC,AC,NC,DC,MC,jC,zC,tp,LC,FC,UC,HC,ZC,BC,uv,qC,cn,Bn,qn,Vn,Wn,Hs,Gn,Kn,un,Lr,ar,Zs,Fr,kt,Jn,zr,sc,Yn,Er,oc,Bs,qs,ic,Xn,Qn,es,ts,ln,qt,St,$r,rs,ns,Vs,YC,Yo,Xo,ss,XC,I,QC,fv,hv,eO,tO,gv,rO,nO,sO,oO,iO,aO,cO,uO,lO,np,dO,pO,mO,fO,hO,gO,yO,_O,bO,vO,xO,SO,kO,wO,EO,$O,TO,PO,RO,CO,OO,IO,AO,NO,yv=x(()=>{ec();tc();iv();ep();Ko();Bt=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}},av=(t,e)=>{if(an(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 xt(t.common.issues);return this._error=r,this._error}}};te=class{get description(){return this._def.description}_getType(e){return wr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:wr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ye,ctx:{common:e.parent.common,data:e.data,parsedType:wr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Fs(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:wr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return av(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:wr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return an(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=>an(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:wr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Fs(s)?s:Promise.resolve(s));return av(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 qt({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 St.create(this,this._def)}nullable(){return $r.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Fr.create(this)}promise(){return ln.create(this,this._def)}or(e){return Jn.create([this,e],this._def)}and(e){return Yn.create(this,e,this._def)}transform(e){return new qt({...Q(this._def),schema:this,typeName:I.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new rs({...Q(this._def),innerType:this,defaultValue:r,typeName:I.ZodDefault})}brand(){return new Yo({typeName:I.ZodBranded,type:this,...Q(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new ns({...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 Xo.create(this,e)}readonly(){return ss.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},CC=/^c[^\s-]{8,}$/i,OC=/^[0-9a-z]+$/,IC=/^[0-9A-HJKMNP-TV-Z]{26}$/i,AC=/^[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,NC=/^[a-z0-9_-]{21}$/i,DC=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,MC=/^[-+]?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)?)??$/,jC=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,zC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",LC=/^(?:(?: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])$/,FC=/^(?:(?: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])$/,UC=/^(([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]))$/,HC=/^(([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])$/,ZC=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,BC=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,uv="((\\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])))",qC=new RegExp(`^${uv}$`);cn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==j.string){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:j.string,received:o.parsedType}),G}let n=new Ye,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")jC.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")tp||(tp=new RegExp(zC,"u")),tp.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")AC.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")NC.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")CC.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")OC.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")IC.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"?dv(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"?qC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{code:O.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?VC(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"?MC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"duration",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?WC(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"?GC(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"?KC(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"?ZC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64",code:O.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?BC.test(e.data)||(s=this._getOrReturnCtx(e,s),N(s,{validation:"base64url",code:O.invalid_string,message:o.message}),n.dirty()):ae.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}};cn.create=t=>new cn({checks:[],typeName:I.ZodString,coerce:t?.coerce??!1,...Q(t)});Bn=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)!==j.number){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:j.number,received:o.parsedType}),G}let n,s=new Ye;for(let o of this._def.checks)o.kind==="int"?ae.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"?JC(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()):ae.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"&&ae.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)}};Bn.create=t=>new Bn({checks:[],typeName:I.ZodNumber,coerce:t?.coerce||!1,...Q(t)});qn=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)!==j.bigint)return this._getInvalidInput(e);let n,s=new Ye;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()):ae.assertNever(o);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:j.bigint,received:r.parsedType}),G}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}};qn.create=t=>new qn({checks:[],typeName:I.ZodBigInt,coerce:t?.coerce??!1,...Q(t)});Vn=class extends te{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==j.boolean){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.boolean,received:n.parsedType}),G}return at(e.data)}};Vn.create=t=>new Vn({typeName:I.ZodBoolean,coerce:t?.coerce||!1,...Q(t)});Wn=class t extends te{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==j.date){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_type,expected:j.date,received:o.parsedType}),G}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return N(o,{code:O.invalid_date}),G}let n=new Ye,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()):ae.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}};Wn.create=t=>new Wn({checks:[],coerce:t?.coerce||!1,typeName:I.ZodDate,...Q(t)});Hs=class extends te{_parse(e){if(this._getType(e)!==j.symbol){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.symbol,received:n.parsedType}),G}return at(e.data)}};Hs.create=t=>new Hs({typeName:I.ZodSymbol,...Q(t)});Gn=class extends te{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.undefined,received:n.parsedType}),G}return at(e.data)}};Gn.create=t=>new Gn({typeName:I.ZodUndefined,...Q(t)});Kn=class extends te{_parse(e){if(this._getType(e)!==j.null){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.null,received:n.parsedType}),G}return at(e.data)}};Kn.create=t=>new Kn({typeName:I.ZodNull,...Q(t)});un=class extends te{constructor(){super(...arguments),this._any=!0}_parse(e){return at(e.data)}};un.create=t=>new un({typeName:I.ZodAny,...Q(t)});Lr=class extends te{constructor(){super(...arguments),this._unknown=!0}_parse(e){return at(e.data)}};Lr.create=t=>new Lr({typeName:I.ZodUnknown,...Q(t)});ar=class extends te{_parse(e){let r=this._getOrReturnCtx(e);return N(r,{code:O.invalid_type,expected:j.never,received:r.parsedType}),G}};ar.create=t=>new ar({typeName:I.ZodNever,...Q(t)});Zs=class extends te{_parse(e){if(this._getType(e)!==j.undefined){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.void,received:n.parsedType}),G}return at(e.data)}};Zs.create=t=>new Zs({typeName:I.ZodVoid,...Q(t)});Fr=class t extends te{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==j.array)return N(r,{code:O.invalid_type,expected:j.array,received:r.parsedType}),G;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 Bt(r,i,r.path,a)))).then(i=>Ye.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Bt(r,i,r.path,a)));return Ye.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)}};Fr.create=(t,e)=>new Fr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...Q(e)});kt=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=ae.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==j.object){let u=this._getOrReturnCtx(e);return N(u,{code:O.invalid_type,expected:j.object,received:u.parsedType}),G}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof ar&&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 Bt(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof ar){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 Bt(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,m=await d.value;u.push({key:l,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>Ye.mergeObjectSync(n,u)):Ye.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 ae.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 ae.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return Us(this)}partial(e){let r={};for(let n of ae.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 ae.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof St;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return pv(ae.objectKeys(this.shape))}};kt.create=(t,e)=>new kt({shape:()=>t,unknownKeys:"strip",catchall:ar.create(),typeName:I.ZodObject,...Q(e)});kt.strictCreate=(t,e)=>new kt({shape:()=>t,unknownKeys:"strict",catchall:ar.create(),typeName:I.ZodObject,...Q(e)});kt.lazycreate=(t,e)=>new kt({shape:t,unknownKeys:"strip",catchall:ar.create(),typeName:I.ZodObject,...Q(e)});Jn=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 xt(a.ctx.common.issues));return N(r,{code:O.invalid_union,unionErrors:i}),G}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 xt(c));return N(r,{code:O.invalid_union,unionErrors:a}),G}}get options(){return this._def.options}};Jn.create=(t,e)=>new Jn({options:t,typeName:I.ZodUnion,...Q(e)});zr=t=>t instanceof Xn?zr(t.schema):t instanceof qt?zr(t.innerType()):t instanceof Qn?[t.value]:t instanceof es?t.options:t instanceof ts?ae.objectValues(t.enum):t instanceof rs?zr(t._def.innerType):t instanceof Gn?[void 0]:t instanceof Kn?[null]:t instanceof St?[void 0,...zr(t.unwrap())]:t instanceof $r?[null,...zr(t.unwrap())]:t instanceof Yo||t instanceof ss?zr(t.unwrap()):t instanceof ns?zr(t._def.innerType):[],sc=class t extends te{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.object)return N(r,{code:O.invalid_type,expected:j.object,received:r.parsedType}),G;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]}),G)}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=zr(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)})}};Yn=class extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(rc(o)||rc(i))return G;let a=rp(o.value,i.value);return a.valid?((nc(o)||nc(i))&&r.dirty(),{status:r.value,value:a.data}):(N(n,{code:O.invalid_intersection_types}),G)};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}))}};Yn.create=(t,e,r)=>new Yn({left:t,right:e,typeName:I.ZodIntersection,...Q(r)});Er=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.array)return N(n,{code:O.invalid_type,expected:j.array,received:n.parsedType}),G;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"}),G;!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 Bt(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>Ye.mergeArray(r,i)):Ye.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};Er.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Er({items:t,typeName:I.ZodTuple,rest:null,...Q(e)})};oc=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!==j.object)return N(n,{code:O.invalid_type,expected:j.object,received:n.parsedType}),G;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Bt(n,a,n.path,a)),value:i._parse(new Bt(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ye.mergeObjectAsync(r,s):Ye.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:cn.create(),valueType:e,typeName:I.ZodRecord,...Q(r)})}},Bs=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!==j.map)return N(n,{code:O.invalid_type,expected:j.map,received:n.parsedType}),G;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new Bt(n,a,n.path,[u,"key"])),value:o._parse(new Bt(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 G;(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 G;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Bs.create=(t,e,r)=>new Bs({valueType:e,keyType:t,typeName:I.ZodMap,...Q(r)});qs=class t extends te{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==j.set)return N(n,{code:O.invalid_type,expected:j.set,received:n.parsedType}),G;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 G;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 Bt(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)}};qs.create=(t,e)=>new qs({valueType:t,minSize:null,maxSize:null,typeName:I.ZodSet,...Q(e)});ic=class t extends te{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.function)return N(r,{code:O.invalid_type,expected:j.function,received:r.parsedType}),G;function n(a,c){return Jo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ls(),jr].filter(u=>!!u),issueData:{code:O.invalid_arguments,argumentsError:c}})}function s(a,c){return Jo({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,Ls(),jr].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 ln){let a=this;return at(async function(...c){let u=new xt([]),d=await a._def.args.parseAsync(c,o).catch(h=>{throw u.addIssue(n(c,h)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(h=>{throw u.addIssue(s(l,h)),u})})}else{let a=this;return at(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new xt([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new xt([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:Er.create(e).rest(Lr.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||Er.create([]).rest(Lr.create()),returns:r||Lr.create(),typeName:I.ZodFunction,...Q(n)})}},Xn=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})}};Xn.create=(t,e)=>new Xn({getter:t,typeName:I.ZodLazy,...Q(e)});Qn=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}),G}return{status:"valid",value:e.data}}get value(){return this._def.value}};Qn.create=(t,e)=>new Qn({value:t,typeName:I.ZodLiteral,...Q(e)});es=class t extends te{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return N(r,{expected:ae.joinValues(n),received:r.parsedType,code:O.invalid_type}),G}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}),G}return at(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})}};es.create=pv;ts=class extends te{_parse(e){let r=ae.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==j.string&&n.parsedType!==j.number){let s=ae.objectValues(r);return N(n,{expected:ae.joinValues(s),received:n.parsedType,code:O.invalid_type}),G}if(this._cache||(this._cache=new Set(ae.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ae.objectValues(r);return N(n,{received:n.data,code:O.invalid_enum_value,options:s}),G}return at(e.data)}get enum(){return this._def.values}};ts.create=(t,e)=>new ts({values:t,typeName:I.ZodNativeEnum,...Q(e)});ln=class extends te{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==j.promise&&r.common.async===!1)return N(r,{code:O.invalid_type,expected:j.promise,received:r.parsedType}),G;let n=r.parsedType===j.promise?r.data:Promise.resolve(r.data);return at(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};ln.create=(t,e)=>new ln({type:t,typeName:I.ZodPromise,...Q(e)});qt=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 G;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?G:c.status==="dirty"?Zn(c.value):r.value==="dirty"?Zn(c.value):c});{if(r.value==="aborted")return G;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?G:a.status==="dirty"?Zn(a.value):r.value==="dirty"?Zn(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"?G:(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"?G:(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(!an(i))return G;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=>an(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):G);ae.assertNever(s)}};qt.create=(t,e,r)=>new qt({schema:t,typeName:I.ZodEffects,effect:e,...Q(r)});qt.createWithPreprocess=(t,e,r)=>new qt({schema:e,effect:{type:"preprocess",transform:t},typeName:I.ZodEffects,...Q(r)});St=class extends te{_parse(e){return this._getType(e)===j.undefined?at(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};St.create=(t,e)=>new St({innerType:t,typeName:I.ZodOptional,...Q(e)});$r=class extends te{_parse(e){return this._getType(e)===j.null?at(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$r.create=(t,e)=>new $r({innerType:t,typeName:I.ZodNullable,...Q(e)});rs=class extends te{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===j.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};rs.create=(t,e)=>new rs({innerType:t,typeName:I.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...Q(e)});ns=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 Fs(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new xt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ns.create=(t,e)=>new ns({innerType:t,typeName:I.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...Q(e)});Vs=class extends te{_parse(e){if(this._getType(e)!==j.nan){let n=this._getOrReturnCtx(e);return N(n,{code:O.invalid_type,expected:j.nan,received:n.parsedType}),G}return{status:"valid",value:e.data}}};Vs.create=t=>new Vs({typeName:I.ZodNaN,...Q(t)});YC=Symbol("zod_brand"),Yo=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}},Xo=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"?G:o.status==="dirty"?(r.dirty(),Zn(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"?G: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})}},ss=class extends te{_parse(e){let r=this._def.innerType._parse(e),n=s=>(an(s)&&(s.value=Object.freeze(s.value)),s);return Fs(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};ss.create=(t,e)=>new ss({innerType:t,typeName:I.ZodReadonly,...Q(e)});XC={object:kt.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={}));QC=(t,e={message:`Input not instance of ${t.name}`})=>mv(r=>r instanceof t,e),fv=cn.create,hv=Bn.create,eO=Vs.create,tO=qn.create,gv=Vn.create,rO=Wn.create,nO=Hs.create,sO=Gn.create,oO=Kn.create,iO=un.create,aO=Lr.create,cO=ar.create,uO=Zs.create,lO=Fr.create,np=kt.create,dO=kt.strictCreate,pO=Jn.create,mO=sc.create,fO=Yn.create,hO=Er.create,gO=oc.create,yO=Bs.create,_O=qs.create,bO=ic.create,vO=Xn.create,xO=Qn.create,SO=es.create,kO=ts.create,wO=ln.create,EO=qt.create,$O=St.create,TO=$r.create,PO=qt.createWithPreprocess,RO=Xo.create,CO=()=>fv().optional(),OO=()=>hv().optional(),IO=()=>gv().optional(),AO={string:(t=>cn.create({...t,coerce:!0})),number:(t=>Bn.create({...t,coerce:!0})),boolean:(t=>Vn.create({...t,coerce:!0})),bigint:(t=>qn.create({...t,coerce:!0})),date:(t=>Wn.create({...t,coerce:!0}))},NO=G});var U={};Ie(U,{BRAND:()=>YC,DIRTY:()=>Zn,EMPTY_PATH:()=>RC,INVALID:()=>G,NEVER:()=>NO,OK:()=>at,ParseStatus:()=>Ye,Schema:()=>te,ZodAny:()=>un,ZodArray:()=>Fr,ZodBigInt:()=>qn,ZodBoolean:()=>Vn,ZodBranded:()=>Yo,ZodCatch:()=>ns,ZodDate:()=>Wn,ZodDefault:()=>rs,ZodDiscriminatedUnion:()=>sc,ZodEffects:()=>qt,ZodEnum:()=>es,ZodError:()=>xt,ZodFirstPartyTypeKind:()=>I,ZodFunction:()=>ic,ZodIntersection:()=>Yn,ZodIssueCode:()=>O,ZodLazy:()=>Xn,ZodLiteral:()=>Qn,ZodMap:()=>Bs,ZodNaN:()=>Vs,ZodNativeEnum:()=>ts,ZodNever:()=>ar,ZodNull:()=>Kn,ZodNullable:()=>$r,ZodNumber:()=>Bn,ZodObject:()=>kt,ZodOptional:()=>St,ZodParsedType:()=>j,ZodPipeline:()=>Xo,ZodPromise:()=>ln,ZodReadonly:()=>ss,ZodRecord:()=>oc,ZodSchema:()=>te,ZodSet:()=>qs,ZodString:()=>cn,ZodSymbol:()=>Hs,ZodTransformer:()=>qt,ZodTuple:()=>Er,ZodType:()=>te,ZodUndefined:()=>Gn,ZodUnion:()=>Jn,ZodUnknown:()=>Lr,ZodVoid:()=>Zs,addIssueToContext:()=>N,any:()=>iO,array:()=>lO,bigint:()=>tO,boolean:()=>gv,coerce:()=>AO,custom:()=>mv,date:()=>rO,datetimeRegex:()=>dv,defaultErrorMap:()=>jr,discriminatedUnion:()=>mO,effect:()=>EO,enum:()=>SO,function:()=>bO,getErrorMap:()=>Ls,getParsedType:()=>wr,instanceof:()=>QC,intersection:()=>fO,isAborted:()=>rc,isAsync:()=>Fs,isDirty:()=>nc,isValid:()=>an,late:()=>XC,lazy:()=>vO,literal:()=>xO,makeIssue:()=>Jo,map:()=>yO,nan:()=>eO,nativeEnum:()=>kO,never:()=>cO,null:()=>oO,nullable:()=>TO,number:()=>hv,object:()=>np,objectUtil:()=>Xd,oboolean:()=>IO,onumber:()=>OO,optional:()=>$O,ostring:()=>CO,pipeline:()=>RO,preprocess:()=>PO,promise:()=>wO,quotelessJson:()=>$C,record:()=>gO,set:()=>_O,setErrorMap:()=>PC,strictObject:()=>dO,string:()=>fv,symbol:()=>nO,transformer:()=>EO,tuple:()=>hO,undefined:()=>sO,union:()=>pO,unknown:()=>aO,util:()=>ae,void:()=>uO});var ac=x(()=>{tc();ep();ov();Ko();yv();ec()});var Qo=x(()=>{ac()});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 At(t){return t&&Object.assign(cc,t),cc}var MO,Ur,cc,Ws=x(()=>{MO=Object.freeze({status:"aborted"});Ur=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},cc={}});var ce={};Ie(ce,{BIGINT_FORMAT_RANGES:()=>bv,Class:()=>op,NUMBER_FORMAT_RANGES:()=>pp,aborted:()=>is,allowsEval:()=>up,assert:()=>UO,assertEqual:()=>jO,assertIs:()=>LO,assertNever:()=>FO,assertNotEqual:()=>zO,assignProp:()=>cp,cached:()=>ri,captureStackTrace:()=>lc,cleanEnum:()=>eI,cleanRegex:()=>si,clone:()=>Nt,createTransparentProxy:()=>WO,defineLazy:()=>we,esc:()=>os,escapeRegex:()=>dn,extend:()=>JO,finalizeIssue:()=>cr,floatSafeRemainder:()=>ap,getElementAtPath:()=>HO,getEnumValues:()=>ti,getLengthableOrigin:()=>oi,getParsedType:()=>VO,getSizableOrigin:()=>vv,isObject:()=>Gs,isPlainObject:()=>Ks,issue:()=>mp,joinValues:()=>uc,jsonStringifyReplacer:()=>ip,merge:()=>YO,normalizeParams:()=>K,nullish:()=>ni,numKeys:()=>qO,omit:()=>KO,optionalKeys:()=>dp,partial:()=>XO,pick:()=>GO,prefixIssues:()=>Tr,primitiveTypes:()=>_v,promiseAllObject:()=>ZO,propertyKeyTypes:()=>lp,randomString:()=>BO,required:()=>QO,stringifyPrimitive:()=>dc,unwrapMessage:()=>ei});function jO(t){return t}function zO(t){return t}function LO(t){}function FO(t){throw new Error}function UO(t){}function ti(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 uc(t,e="|"){return t.map(r=>dc(r)).join(e)}function ip(t,e){return typeof e=="bigint"?e.toString():e}function ri(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function ni(t){return t==null}function si(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function ap(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 we(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 cp(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function HO(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function ZO(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 BO(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function os(t){return JSON.stringify(t)}function Gs(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ks(t){if(Gs(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Gs(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function qO(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function dn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Nt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function K(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 WO(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 dc(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function dp(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function GO(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 Nt(t,{...t._zod.def,shape:r,checks:[]})}function KO(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 Nt(t,{...t._zod.def,shape:r,checks:[]})}function JO(t,e){if(!Ks(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 cp(this,"shape",n),n},checks:[]};return Nt(t,r)}function YO(t,e){return Nt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return cp(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function XO(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 Nt(e,{...e._zod.def,shape:s,checks:[]})}function QO(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 Nt(e,{...e._zod.def,shape:s,checks:[]})}function is(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function Tr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function ei(t){return typeof t=="string"?t:t?.message}function cr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=ei(t.inst?._zod.def?.error?.(t))??ei(e?.error?.(t))??ei(r.customError?.(t))??ei(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function vv(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function oi(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function mp(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function eI(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var lc,up,VO,lp,_v,pp,bv,op,Pr=x(()=>{lc=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};up=ri(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});VO=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}`)}},lp=new Set(["string","number","symbol"]),_v=new Set(["string","number","bigint","boolean","symbol","undefined"]);pp={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]},bv={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};op=class{constructor(...e){}}});function fp(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 hp(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 xv,pc,ii,gp=x(()=>{Ws();Pr();xv=(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,ip,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},pc=w("$ZodError",xv),ii=w("$ZodError",xv,{Parent:Error})});var yp,_p,bp,vp,xp,as,Sp,cs,kp=x(()=>{Ws();gp();Pr();yp=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 Ur;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>cr(c,o,At())));throw lc(a,s?.callee),a}return i.value},_p=yp(ii),bp=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=>cr(c,o,At())));throw lc(a,s?.callee),a}return i.value},vp=bp(ii),xp=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 Ur;return o.issues.length?{success:!1,error:new(t??pc)(o.issues.map(i=>cr(i,s,At())))}:{success:!0,data:o.value}},as=xp(ii),Sp=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=>cr(i,s,At())))}:{success:!0,data:o.value}},cs=Sp(ii)});function Ov(){return new RegExp(rI,"u")}function Uv(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 Hv(t){return new RegExp(`^${Uv(t)}$`)}function Zv(t){let e=Uv({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(`^${Lv}T(?:${n})$`)}var Sv,kv,wv,Ev,$v,Tv,Pv,Rv,wp,Cv,rI,Iv,Av,Nv,Dv,Mv,Ep,jv,zv,Lv,Fv,Bv,qv,Vv,Wv,Gv,Kv,Jv,fc=x(()=>{Sv=/^[cC][^\s-]{8,}$/,kv=/^[0-9a-z]+$/,wv=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ev=/^[0-9a-vA-V]{20}$/,$v=/^[A-Za-z0-9]{27}$/,Tv=/^[a-zA-Z0-9_-]{21}$/,Pv=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Rv=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,wp=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/,Cv=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,rI="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Iv=/^(?:(?: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])$/,Av=/^(([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})$/,Nv=/^((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])$/,Mv=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ep=/^[A-Za-z0-9_-]*$/,jv=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,zv=/^\+(?:[0-9]){6,14}[0-9]$/,Lv="(?:(?:\\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])))",Fv=new RegExp(`^${Lv}$`);Bv=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},qv=/^\d+$/,Vv=/^-?\d+(?:\.\d+)?/i,Wv=/true|false/i,Gv=/null/i,Kv=/^[^A-Z]*$/,Jv=/^[^a-z]*$/});var Xe,Yv,$p,Tp,Xv,Qv,ex,tx,rx,ai,nx,sx,ox,ix,ax,cx,ux,hc=x(()=>{Ws();fc();Pr();Xe=w("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),Yv={number:"number",bigint:"bigint",object:"date"},$p=w("$ZodCheckLessThan",(t,e)=>{Xe.init(t,e);let r=Yv[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})}}),Tp=w("$ZodCheckGreaterThan",(t,e)=>{Xe.init(t,e);let r=Yv[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})}}),Xv=w("$ZodCheckMultipleOf",(t,e)=>{Xe.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):ap(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})}}),Qv=w("$ZodCheckNumberFormat",(t,e)=>{Xe.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=pp[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=qv)}),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})}}),ex=w("$ZodCheckMaxLength",(t,e)=>{var r;Xe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!ni(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=oi(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),tx=w("$ZodCheckMinLength",(t,e)=>{var r;Xe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!ni(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=oi(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),rx=w("$ZodCheckLengthEquals",(t,e)=>{var r;Xe.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!ni(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=oi(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})}}),ai=w("$ZodCheckStringFormat",(t,e)=>{var r,n;Xe.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=()=>{})}),nx=w("$ZodCheckRegex",(t,e)=>{ai.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})}}),sx=w("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Kv),ai.init(t,e)}),ox=w("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Jv),ai.init(t,e)}),ix=w("$ZodCheckIncludes",(t,e)=>{Xe.init(t,e);let r=dn(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})}}),ax=w("$ZodCheckStartsWith",(t,e)=>{Xe.init(t,e);let r=new RegExp(`^${dn(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})}}),cx=w("$ZodCheckEndsWith",(t,e)=>{Xe.init(t,e);let r=new RegExp(`.*${dn(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})}}),ux=w("$ZodCheckOverwrite",(t,e)=>{Xe.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var gc,Pp=x(()=>{gc=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
38
  `).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 ox,Sp=x(()=>{ox={major:4,minor:0,patch:0}});function bx(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function JO(t){if(!_p.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return bx(r)}function YO(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 ix(t,e,r){t.issues.length&&e.issues.push(...$r(r,t.issues)),e.value[r]=t.value}function dc(t,e,r){t.issues.length&&e.issues.push(...$r(r,t.issues)),e.value[r]=t.value}function ax(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(...$r(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function cx(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=>cr(o,n,It())))}),e}function kp(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(Ws(t)&&Ws(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=kp(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=kp(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 ux(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),os(t))return t;let n=kp(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 lx(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function dx(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 px(t,e,r){return os(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function mx(t){return t.value=Object.freeze(t.value),t}function fx(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(ip(s))}}var be,si,Ee,wp,Ep,$p,Tp,Pp,Rp,Cp,Op,Ip,Ap,Np,hx,gx,yx,_x,Dp,Mp,jp,zp,Lp,Fp,Up,Hp,pc,Zp,Bp,qp,Vp,Wp,Gp,mc,fc,Kp,Jp,Yp,Xp,Qp,em,tm,rm,nm,sm,om,im,am,cm,um,vx=x(()=>{uc();qs();xp();gp();cc();Tr();Sp();Tr();be=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=ox;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=os(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,m=d._zod.check(o);if(m instanceof Promise&&a?.async===!1)throw new Fr;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,o.issues.length!==l&&(c||(c=os(o,l)))});else{if(o.issues.length===l)continue;c||(c=os(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 Fr;return a.then(c=>s(c,n,i))}return s(a,n,i)}}t["~standard"]={validate:s=>{try{let o=is(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return as(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),si=w("$ZodString",(t,e)=>{be.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??zv(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}}),Ee=w("$ZodStringFormat",(t,e)=>{ni.init(t,e),si.init(t,e)}),wp=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=kv),Ee.init(t,e)}),Ep=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=yp(n))}else e.pattern??(e.pattern=yp());Ee.init(t,e)}),$p=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=wv),Ee.init(t,e)}),Tp=w("$ZodURL",(t,e)=>{Ee.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:Ov.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})}}}),Pp=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Ev()),Ee.init(t,e)}),Rp=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=xv),Ee.init(t,e)}),Cp=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=gv),Ee.init(t,e)}),Op=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=yv),Ee.init(t,e)}),Ip=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=_v),Ee.init(t,e)}),Ap=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=bv),Ee.init(t,e)}),Np=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=vv),Ee.init(t,e)}),hx=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=jv(e)),Ee.init(t,e)}),gx=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Nv),Ee.init(t,e)}),yx=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Mv(e)),Ee.init(t,e)}),_x=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Sv),Ee.init(t,e)}),Dp=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=$v),Ee.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Mp=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Tv),Ee.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})}}}),jp=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Pv),Ee.init(t,e)}),zp=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Rv),Ee.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})}}});Lp=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Cv),Ee.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{bx(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Fp=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=_p),Ee.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{JO(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Up=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Iv),Ee.init(t,e)});Hp=w("$ZodJWT",(t,e)=>{Ee.init(t,e),t._zod.check=r=>{YO(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),pc=w("$ZodNumber",(t,e)=>{be.init(t,e),t._zod.pattern=t._zod.bag.pattern??Fv,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}}),Zp=w("$ZodNumber",(t,e)=>{Wv.init(t,e),pc.init(t,e)}),Bp=w("$ZodBoolean",(t,e)=>{be.init(t,e),t._zod.pattern=Uv,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}}),qp=w("$ZodNull",(t,e)=>{be.init(t,e),t._zod.pattern=Hv,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}}),Vp=w("$ZodUnknown",(t,e)=>{be.init(t,e),t._zod.parse=r=>r}),Wp=w("$ZodNever",(t,e)=>{be.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Gp=w("$ZodArray",(t,e)=>{be.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=>ix(u,r,i))):ix(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});mc=w("$ZodObject",(t,e)=>{be.init(t,e);let r=Xo(()=>{let l=Object.keys(e.shape);for(let h of l)if(!(e.shape[h]instanceof be))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let m=sp(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(m)}});we(t._zod,"propValues",()=>{let l=e.shape,m={};for(let h in l){let p=l[h]._zod;if(p.values){m[h]??(m[h]=new Set);for(let f of p.values)m[h].add(f)}}return m});let n=l=>{let m=new lc(["shape","payload","ctx"]),h=r.value,p=b=>{let _=ss(b);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};m.write("const input = payload.value;");let f=Object.create(null),g=0;for(let b of h.keys)f[b]=`key_${g++}`;m.write("const newResult = {}");for(let b of h.keys)if(h.optionalKeys.has(b)){let _=f[b];m.write(`const ${_} = ${p(b)};`);let S=ss(b);m.write(`
39
+ `))}}});var dx,Rp=x(()=>{dx={major:4,minor:0,patch:0}});function Ex(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function nI(t){if(!Ep.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Ex(r)}function sI(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 px(t,e,r){t.issues.length&&e.issues.push(...Tr(r,t.issues)),e.value[r]=t.value}function yc(t,e,r){t.issues.length&&e.issues.push(...Tr(r,t.issues)),e.value[r]=t.value}function mx(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(...Tr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function fx(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=>cr(o,n,At())))}),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(Ks(t)&&Ks(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 hx(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),is(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 gx(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function yx(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 _x(t,e,r){return is(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function bx(t){return t.value=Object.freeze(t.value),t}function vx(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(mp(s))}}var be,ci,Ee,Op,Ip,Ap,Np,Dp,Mp,jp,zp,Lp,Fp,Up,xx,Sx,kx,wx,Hp,Zp,Bp,qp,Vp,Wp,Gp,Kp,_c,Jp,Yp,Xp,Qp,em,tm,bc,vc,rm,nm,sm,om,im,am,cm,um,lm,dm,pm,mm,fm,hm,gm,$x=x(()=>{hc();Ws();Pp();kp();fc();Pr();Rp();Pr();be=w("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=dx;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=is(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,m=d._zod.check(o);if(m instanceof Promise&&a?.async===!1)throw new Ur;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,o.issues.length!==l&&(c||(c=is(o,l)))});else{if(o.issues.length===l)continue;c||(c=is(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 Ur;return a.then(c=>s(c,n,i))}return s(a,n,i)}}t["~standard"]={validate:s=>{try{let o=as(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return cs(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),ci=w("$ZodString",(t,e)=>{be.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Bv(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}}),Ee=w("$ZodStringFormat",(t,e)=>{ai.init(t,e),ci.init(t,e)}),Op=w("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Rv),Ee.init(t,e)}),Ip=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=wp(n))}else e.pattern??(e.pattern=wp());Ee.init(t,e)}),Ap=w("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Cv),Ee.init(t,e)}),Np=w("$ZodURL",(t,e)=>{Ee.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:jv.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})}}}),Dp=w("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Ov()),Ee.init(t,e)}),Mp=w("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Tv),Ee.init(t,e)}),jp=w("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Sv),Ee.init(t,e)}),zp=w("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=kv),Ee.init(t,e)}),Lp=w("$ZodULID",(t,e)=>{e.pattern??(e.pattern=wv),Ee.init(t,e)}),Fp=w("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Ev),Ee.init(t,e)}),Up=w("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=$v),Ee.init(t,e)}),xx=w("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Zv(e)),Ee.init(t,e)}),Sx=w("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Fv),Ee.init(t,e)}),kx=w("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Hv(e)),Ee.init(t,e)}),wx=w("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Pv),Ee.init(t,e)}),Hp=w("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Iv),Ee.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),Zp=w("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Av),Ee.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})}}}),Bp=w("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Nv),Ee.init(t,e)}),qp=w("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Dv),Ee.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})}}});Vp=w("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Mv),Ee.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Ex(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});Wp=w("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Ep),Ee.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{nI(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),Gp=w("$ZodE164",(t,e)=>{e.pattern??(e.pattern=zv),Ee.init(t,e)});Kp=w("$ZodJWT",(t,e)=>{Ee.init(t,e),t._zod.check=r=>{sI(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),_c=w("$ZodNumber",(t,e)=>{be.init(t,e),t._zod.pattern=t._zod.bag.pattern??Vv,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}}),Jp=w("$ZodNumber",(t,e)=>{Qv.init(t,e),_c.init(t,e)}),Yp=w("$ZodBoolean",(t,e)=>{be.init(t,e),t._zod.pattern=Wv,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}}),Xp=w("$ZodNull",(t,e)=>{be.init(t,e),t._zod.pattern=Gv,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}}),Qp=w("$ZodUnknown",(t,e)=>{be.init(t,e),t._zod.parse=r=>r}),em=w("$ZodNever",(t,e)=>{be.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});tm=w("$ZodArray",(t,e)=>{be.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=>px(u,r,i))):px(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});bc=w("$ZodObject",(t,e)=>{be.init(t,e);let r=ri(()=>{let l=Object.keys(e.shape);for(let h of l)if(!(e.shape[h]instanceof be))throw new Error(`Invalid element at key "${h}": expected a Zod schema`);let m=dp(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(m)}});we(t._zod,"propValues",()=>{let l=e.shape,m={};for(let h in l){let p=l[h]._zod;if(p.values){m[h]??(m[h]=new Set);for(let f of p.values)m[h].add(f)}}return m});let n=l=>{let m=new gc(["shape","payload","ctx"]),h=r.value,p=b=>{let _=os(b);return`shape[${_}]._zod.run({ value: input[${_}], issues: [] }, ctx)`};m.write("const input = payload.value;");let f=Object.create(null),g=0;for(let b of h.keys)f[b]=`key_${g++}`;m.write("const newResult = {}");for(let b of h.keys)if(h.optionalKeys.has(b)){let _=f[b];m.write(`const ${_} = ${p(b)};`);let S=os(b);m.write(`
36
40
  if (${_}.issues.length) {
37
41
  if (input[${S}] === undefined) {
38
42
  if (${S} in input) {
@@ -54,24 +58,24 @@ Use context-mode MCP tools (ctx_execute, ctx_execute_file, ctx_batch_execute, ct
54
58
  `)}else{let _=f[b];m.write(`const ${_} = ${p(b)};`),m.write(`
55
59
  if (${_}.issues.length) payload.issues = payload.issues.concat(${_}.issues.map(iss => ({
56
60
  ...iss,
57
- path: iss.path ? [${ss(b)}, ...iss.path] : [${ss(b)}]
58
- })));`),m.write(`newResult[${ss(b)}] = ${_}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let y=m.compile();return(b,_)=>y(l,b,_)},s,o=Vs,i=!rc.jitless,c=i&&rp.value,u=e.catchall,d;t._zod.parse=(l,m)=>{d??(d=r.value);let h=l.value;if(!o(h))return l.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),l;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)s||(s=n(e.shape)),l=s(l,m);else{l.value={};let _=d.shape;for(let S of d.keys){let v=_[S],R=v._zod.run({value:h[S],issues:[]},m),$=v._zod.optin==="optional"&&v._zod.optout==="optional";R instanceof Promise?p.push(R.then(T=>$?ax(T,l,S,h):dc(T,l,S))):$?ax(R,l,S,h):dc(R,l,S)}}if(!u)return p.length?Promise.all(p).then(()=>l):l;let f=[],g=d.keySet,y=u._zod,b=y.def.type;for(let _ of Object.keys(h)){if(g.has(_))continue;if(b==="never"){f.push(_);continue}let S=y.run({value:h[_],issues:[]},m);S instanceof Promise?p.push(S.then(v=>dc(v,l,_))):dc(S,l,_)}return f.length&&l.issues.push({code:"unrecognized_keys",keys:f,input:h,inst:t}),p.length?Promise.all(p).then(()=>l):l}});fc=w("$ZodUnion",(t,e)=>{be.init(t,e),we(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),we(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),we(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),we(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=>ei(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=>cx(i,r,t,n)):cx(o,r,t,n)}}),Kp=w("$ZodDiscriminatedUnion",(t,e)=>{fc.init(t,e);let r=t._zod.parse;we(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=Xo(()=>{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(!Vs(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)=>{be.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])=>ux(r,c,u)):ux(r,o,i)}});Yp=w("$ZodRecord",(t,e)=>{be.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Ws(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(...$r(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...$r(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=>cr(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(...$r(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...$r(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),Xp=w("$ZodEnum",(t,e)=>{be.init(t,e);let r=Yo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>np.has(typeof n)).map(n=>typeof n=="string"?un(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}}),Qp=w("$ZodLiteral",(t,e)=>{be.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?un(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}}),em=w("$ZodTransform",(t,e)=>{be.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 Fr;return r.value=s,r}}),tm=w("$ZodOptional",(t,e)=>{be.init(t,e),t._zod.optin="optional",t._zod.optout="optional",we(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),we(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ei(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)}),rm=w("$ZodNullable",(t,e)=>{be.init(t,e),we(t._zod,"optin",()=>e.innerType._zod.optin),we(t._zod,"optout",()=>e.innerType._zod.optout),we(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${ei(r.source)}|null)$`):void 0}),we(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)}),nm=w("$ZodDefault",(t,e)=>{be.init(t,e),t._zod.optin="optional",we(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=>lx(o,e)):lx(s,e)}});sm=w("$ZodPrefault",(t,e)=>{be.init(t,e),t._zod.optin="optional",we(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))}),om=w("$ZodNonOptional",(t,e)=>{be.init(t,e),we(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=>dx(o,t)):dx(s,t)}});im=w("$ZodCatch",(t,e)=>{be.init(t,e),t._zod.optin="optional",we(t._zod,"optout",()=>e.innerType._zod.optout),we(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=>cr(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=>cr(o,n,It()))},input:r.value}),r.issues=[]),r)}}),am=w("$ZodPipe",(t,e)=>{be.init(t,e),we(t._zod,"values",()=>e.in._zod.values),we(t._zod,"optin",()=>e.in._zod.optin),we(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=>px(o,e,n)):px(s,e,n)}});cm=w("$ZodReadonly",(t,e)=>{be.init(t,e),we(t._zod,"propValues",()=>e.innerType._zod.propValues),we(t._zod,"values",()=>e.innerType._zod.values),we(t._zod,"optin",()=>e.innerType._zod.optin),we(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(mx):mx(s)}});um=w("$ZodCustom",(t,e)=>{Xe.init(t,e),be.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=>fx(o,r,n,t));fx(s,r,n,t)}})});function xx(){return{localeError:QO()}}var XO,QO,Sx=x(()=>{Tr();XO=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},QO=()=>{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 ${XO(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${oc(n.values[0])}`:`Invalid option: expected one of ${nc(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":""}: ${nc(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 hc=x(()=>{});function kx(){return new oi}var oi,ln,dm=x(()=>{oi=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)}};ln=kx()});function pm(t,e){return new t({type:"string",...K(e)})}function mm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...K(e)})}function gc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...K(e)})}function fm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...K(e)})}function hm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...K(e)})}function gm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...K(e)})}function ym(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...K(e)})}function _m(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...K(e)})}function bm(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...K(e)})}function vm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...K(e)})}function xm(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...K(e)})}function Sm(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...K(e)})}function km(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...K(e)})}function wm(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...K(e)})}function Em(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...K(e)})}function $m(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...K(e)})}function Tm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...K(e)})}function Pm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...K(e)})}function Rm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...K(e)})}function Cm(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...K(e)})}function Om(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...K(e)})}function Im(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...K(e)})}function Am(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...K(e)})}function wx(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...K(e)})}function Ex(t,e){return new t({type:"string",format:"date",check:"string_format",...K(e)})}function $x(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...K(e)})}function Tx(t,e){return new t({type:"string",format:"duration",check:"string_format",...K(e)})}function Nm(t,e){return new t({type:"number",checks:[],...K(e)})}function Dm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...K(e)})}function Mm(t,e){return new t({type:"boolean",...K(e)})}function jm(t,e){return new t({type:"null",...K(e)})}function zm(t){return new t({type:"unknown"})}function Lm(t,e){return new t({type:"never",...K(e)})}function yc(t,e){return new bp({check:"less_than",...K(e),value:t,inclusive:!1})}function ii(t,e){return new bp({check:"less_than",...K(e),value:t,inclusive:!0})}function _c(t,e){return new vp({check:"greater_than",...K(e),value:t,inclusive:!1})}function ai(t,e){return new vp({check:"greater_than",...K(e),value:t,inclusive:!0})}function bc(t,e){return new Vv({check:"multiple_of",...K(e),value:t})}function vc(t,e){return new Gv({check:"max_length",...K(e),maximum:t})}function Gs(t,e){return new Kv({check:"min_length",...K(e),minimum:t})}function xc(t,e){return new Jv({check:"length_equals",...K(e),length:t})}function Fm(t,e){return new Yv({check:"string_format",format:"regex",...K(e),pattern:t})}function Um(t){return new Xv({check:"string_format",format:"lowercase",...K(t)})}function Hm(t){return new Qv({check:"string_format",format:"uppercase",...K(t)})}function Zm(t,e){return new ex({check:"string_format",format:"includes",...K(e),includes:t})}function Bm(t,e){return new tx({check:"string_format",format:"starts_with",...K(e),prefix:t})}function qm(t,e){return new rx({check:"string_format",format:"ends_with",...K(e),suffix:t})}function cs(t){return new nx({check:"overwrite",tx:t})}function Vm(t){return cs(e=>e.normalize(t))}function Wm(){return cs(t=>t.trim())}function Gm(){return cs(t=>t.toLowerCase())}function Km(){return cs(t=>t.toUpperCase())}function Px(t,e,r){return new t({type:"array",element:e,...K(r)})}function Jm(t,e,r){let n=K(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Ym(t,e,r){return new t({type:"custom",check:"custom",fn:e,...K(r)})}var Rx=x(()=>{uc();Tr()});var Cx=x(()=>{});function Xm(t,e){if(t instanceof oi){let n=new Sc(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 Sc(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 Sc,Ox=x(()=>{dm();Tr();Sc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??ln,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},m=e._zod.parent;if(m)a.ref=m,this.process(m,l),this.seen.get(m).isParent=!0;else{let h=a.schema;switch(s.type){case"string":{let p=h;p.type="string";let{minimum:f,maximum:g,format:y,patterns:b,contentEncoding:_}=e._zod.bag;if(typeof f=="number"&&(p.minLength=f),typeof g=="number"&&(p.maxLength=g),y&&(p.format=o[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),b&&b.size>0){let S=[...b];S.length===1?p.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(v=>({...this.target==="draft-7"?{type:"string"}:{},pattern:v.source}))])}break}case"number":{let p=h,{minimum:f,maximum:g,format:y,multipleOf:b,exclusiveMaximum:_,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof S=="number"&&(p.exclusiveMinimum=S),typeof f=="number"&&(p.minimum=f,typeof S=="number"&&(S>=f?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof b=="number"&&(p.multipleOf=b);break}case"boolean":{let p=h;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=h,{minimum:f,maximum:g}=e._zod.bag;typeof f=="number"&&(p.minItems=f),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=h;p.type="object",p.properties={};let f=s.shape;for(let b in f)p.properties[b]=this.process(f[b],{...l,path:[...l.path,"properties",b]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(b=>{let _=s.shape[b]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=h;p.anyOf=s.options.map((f,g)=>this.process(f,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let p=h,f=this.process(s.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(s.right,{...l,path:[...l.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,b=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];p.allOf=b;break}case"tuple":{let p=h;p.type="array";let f=s.items.map((b,_)=>this.process(b,{...l,path:[...l.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?p.prefixItems=f:p.items=f,s.rest){let b=this.process(s.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=b:p.additionalItems=b}s.rest&&(p.items=this.process(s.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=h;p.type="object",p.propertyNames=this.process(s.keyType,{...l,path:[...l.path,"propertyNames"]}),p.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 p=h,f=Yo(s.entries);f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),p.enum=f;break}case"literal":{let p=h,f=[];for(let g of 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");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];p.type=g===null?"null":typeof g,p.const=g}else f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),f.every(g=>typeof g=="boolean")&&(p.type="string"),f.every(g=>g===null)&&(p.type="null"),p.enum=f;break}case"file":{let p=h,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:b}=e._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),b?b.length===1?(f.contentMediaType=b[0],Object.assign(p,f)):p.anyOf=b.map(_=>({...f,contentMediaType:_})):Object.assign(p,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(s.innerType,l);h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"success":{let p=h;p.type="boolean";break}case"default":{this.process(s.innerType,l),a.ref=s.innerType,h.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,l),a.ref=s.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,l),a.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=h,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=f.source;break}case"pipe":{let p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,l),a.ref=p;break}case"readonly":{this.process(s.innerType,l),a.ref=s.innerType,h.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 p=e._zod.innerType;this.process(p,l),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&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 f=n.external.registry.get(d[0])?.id,g=n.external.uri??(b=>b);if(f)return{ref:g(f)};let y=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=y,{defId:y,ref:`${g("__shared")}#/${l}/${y}`}}if(d[1]===s)return{ref:"#"};let h=`#/${l}/`,p=d[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:h+p}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:m,defId:h}=o(d);l.def={...l.schema},h&&(l.defId=h);let p=l.schema;for(let f in p)delete p[f];p.$ref=m};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
61
+ path: iss.path ? [${os(b)}, ...iss.path] : [${os(b)}]
62
+ })));`),m.write(`newResult[${os(b)}] = ${_}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let y=m.compile();return(b,_)=>y(l,b,_)},s,o=Gs,i=!cc.jitless,c=i&&up.value,u=e.catchall,d;t._zod.parse=(l,m)=>{d??(d=r.value);let h=l.value;if(!o(h))return l.issues.push({expected:"object",code:"invalid_type",input:h,inst:t}),l;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)s||(s=n(e.shape)),l=s(l,m);else{l.value={};let _=d.shape;for(let S of d.keys){let v=_[S],P=v._zod.run({value:h[S],issues:[]},m),T=v._zod.optin==="optional"&&v._zod.optout==="optional";P instanceof Promise?p.push(P.then($=>T?mx($,l,S,h):yc($,l,S))):T?mx(P,l,S,h):yc(P,l,S)}}if(!u)return p.length?Promise.all(p).then(()=>l):l;let f=[],g=d.keySet,y=u._zod,b=y.def.type;for(let _ of Object.keys(h)){if(g.has(_))continue;if(b==="never"){f.push(_);continue}let S=y.run({value:h[_],issues:[]},m);S instanceof Promise?p.push(S.then(v=>yc(v,l,_))):yc(S,l,_)}return f.length&&l.issues.push({code:"unrecognized_keys",keys:f,input:h,inst:t}),p.length?Promise.all(p).then(()=>l):l}});vc=w("$ZodUnion",(t,e)=>{be.init(t,e),we(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),we(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),we(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),we(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=>si(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=>fx(i,r,t,n)):fx(o,r,t,n)}}),rm=w("$ZodDiscriminatedUnion",(t,e)=>{vc.init(t,e);let r=t._zod.parse;we(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=ri(()=>{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(!Gs(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)}}),nm=w("$ZodIntersection",(t,e)=>{be.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])=>hx(r,c,u)):hx(r,o,i)}});sm=w("$ZodRecord",(t,e)=>{be.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Ks(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(...Tr(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...Tr(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=>cr(u,n,At())),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(...Tr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...Tr(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),om=w("$ZodEnum",(t,e)=>{be.init(t,e);let r=ti(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>lp.has(typeof n)).map(n=>typeof n=="string"?dn(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}}),im=w("$ZodLiteral",(t,e)=>{be.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?dn(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}}),am=w("$ZodTransform",(t,e)=>{be.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 Ur;return r.value=s,r}}),cm=w("$ZodOptional",(t,e)=>{be.init(t,e),t._zod.optin="optional",t._zod.optout="optional",we(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),we(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${si(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)}),um=w("$ZodNullable",(t,e)=>{be.init(t,e),we(t._zod,"optin",()=>e.innerType._zod.optin),we(t._zod,"optout",()=>e.innerType._zod.optout),we(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${si(r.source)}|null)$`):void 0}),we(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)}),lm=w("$ZodDefault",(t,e)=>{be.init(t,e),t._zod.optin="optional",we(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=>gx(o,e)):gx(s,e)}});dm=w("$ZodPrefault",(t,e)=>{be.init(t,e),t._zod.optin="optional",we(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))}),pm=w("$ZodNonOptional",(t,e)=>{be.init(t,e),we(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=>yx(o,t)):yx(s,t)}});mm=w("$ZodCatch",(t,e)=>{be.init(t,e),t._zod.optin="optional",we(t._zod,"optout",()=>e.innerType._zod.optout),we(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=>cr(i,n,At()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>cr(o,n,At()))},input:r.value}),r.issues=[]),r)}}),fm=w("$ZodPipe",(t,e)=>{be.init(t,e),we(t._zod,"values",()=>e.in._zod.values),we(t._zod,"optin",()=>e.in._zod.optin),we(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=>_x(o,e,n)):_x(s,e,n)}});hm=w("$ZodReadonly",(t,e)=>{be.init(t,e),we(t._zod,"propValues",()=>e.innerType._zod.propValues),we(t._zod,"values",()=>e.innerType._zod.values),we(t._zod,"optin",()=>e.innerType._zod.optin),we(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(bx):bx(s)}});gm=w("$ZodCustom",(t,e)=>{Xe.init(t,e),be.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=>vx(o,r,n,t));vx(s,r,n,t)}})});function Tx(){return{localeError:iI()}}var oI,iI,Px=x(()=>{Pr();oI=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},iI=()=>{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 ${oI(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${dc(n.values[0])}`:`Invalid option: expected one of ${uc(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":""}: ${uc(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 xc=x(()=>{});function Rx(){return new ui}var ui,pn,_m=x(()=>{ui=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)}};pn=Rx()});function bm(t,e){return new t({type:"string",...K(e)})}function vm(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...K(e)})}function Sc(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...K(e)})}function xm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...K(e)})}function Sm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...K(e)})}function km(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...K(e)})}function wm(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...K(e)})}function Em(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...K(e)})}function $m(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...K(e)})}function Tm(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...K(e)})}function Pm(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...K(e)})}function Rm(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...K(e)})}function Cm(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...K(e)})}function Om(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...K(e)})}function Im(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...K(e)})}function Am(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...K(e)})}function Nm(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...K(e)})}function Dm(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...K(e)})}function Mm(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...K(e)})}function jm(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...K(e)})}function zm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...K(e)})}function Lm(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...K(e)})}function Fm(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...K(e)})}function Cx(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...K(e)})}function Ox(t,e){return new t({type:"string",format:"date",check:"string_format",...K(e)})}function Ix(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...K(e)})}function Ax(t,e){return new t({type:"string",format:"duration",check:"string_format",...K(e)})}function Um(t,e){return new t({type:"number",checks:[],...K(e)})}function Hm(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...K(e)})}function Zm(t,e){return new t({type:"boolean",...K(e)})}function Bm(t,e){return new t({type:"null",...K(e)})}function qm(t){return new t({type:"unknown"})}function Vm(t,e){return new t({type:"never",...K(e)})}function kc(t,e){return new $p({check:"less_than",...K(e),value:t,inclusive:!1})}function li(t,e){return new $p({check:"less_than",...K(e),value:t,inclusive:!0})}function wc(t,e){return new Tp({check:"greater_than",...K(e),value:t,inclusive:!1})}function di(t,e){return new Tp({check:"greater_than",...K(e),value:t,inclusive:!0})}function Ec(t,e){return new Xv({check:"multiple_of",...K(e),value:t})}function $c(t,e){return new ex({check:"max_length",...K(e),maximum:t})}function Js(t,e){return new tx({check:"min_length",...K(e),minimum:t})}function Tc(t,e){return new rx({check:"length_equals",...K(e),length:t})}function Wm(t,e){return new nx({check:"string_format",format:"regex",...K(e),pattern:t})}function Gm(t){return new sx({check:"string_format",format:"lowercase",...K(t)})}function Km(t){return new ox({check:"string_format",format:"uppercase",...K(t)})}function Jm(t,e){return new ix({check:"string_format",format:"includes",...K(e),includes:t})}function Ym(t,e){return new ax({check:"string_format",format:"starts_with",...K(e),prefix:t})}function Xm(t,e){return new cx({check:"string_format",format:"ends_with",...K(e),suffix:t})}function us(t){return new ux({check:"overwrite",tx:t})}function Qm(t){return us(e=>e.normalize(t))}function ef(){return us(t=>t.trim())}function tf(){return us(t=>t.toLowerCase())}function rf(){return us(t=>t.toUpperCase())}function Nx(t,e,r){return new t({type:"array",element:e,...K(r)})}function nf(t,e,r){let n=K(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function sf(t,e,r){return new t({type:"custom",check:"custom",fn:e,...K(r)})}var Dx=x(()=>{hc();Pr()});var Mx=x(()=>{});function of(t,e){if(t instanceof ui){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,jx=x(()=>{_m();Pr();Pc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??pn,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},m=e._zod.parent;if(m)a.ref=m,this.process(m,l),this.seen.get(m).isParent=!0;else{let h=a.schema;switch(s.type){case"string":{let p=h;p.type="string";let{minimum:f,maximum:g,format:y,patterns:b,contentEncoding:_}=e._zod.bag;if(typeof f=="number"&&(p.minLength=f),typeof g=="number"&&(p.maxLength=g),y&&(p.format=o[y]??y,p.format===""&&delete p.format),_&&(p.contentEncoding=_),b&&b.size>0){let S=[...b];S.length===1?p.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(v=>({...this.target==="draft-7"?{type:"string"}:{},pattern:v.source}))])}break}case"number":{let p=h,{minimum:f,maximum:g,format:y,multipleOf:b,exclusiveMaximum:_,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof S=="number"&&(p.exclusiveMinimum=S),typeof f=="number"&&(p.minimum=f,typeof S=="number"&&(S>=f?delete p.minimum:delete p.exclusiveMinimum)),typeof _=="number"&&(p.exclusiveMaximum=_),typeof g=="number"&&(p.maximum=g,typeof _=="number"&&(_<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof b=="number"&&(p.multipleOf=b);break}case"boolean":{let p=h;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{h.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{h.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=h,{minimum:f,maximum:g}=e._zod.bag;typeof f=="number"&&(p.minItems=f),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=h;p.type="object",p.properties={};let f=s.shape;for(let b in f)p.properties[b]=this.process(f[b],{...l,path:[...l.path,"properties",b]});let g=new Set(Object.keys(f)),y=new Set([...g].filter(b=>{let _=s.shape[b]._zod;return this.io==="input"?_.optin===void 0:_.optout===void 0}));y.size>0&&(p.required=Array.from(y)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...l,path:[...l.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{let p=h;p.anyOf=s.options.map((f,g)=>this.process(f,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let p=h,f=this.process(s.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(s.right,{...l,path:[...l.path,"allOf",1]}),y=_=>"allOf"in _&&Object.keys(_).length===1,b=[...y(f)?f.allOf:[f],...y(g)?g.allOf:[g]];p.allOf=b;break}case"tuple":{let p=h;p.type="array";let f=s.items.map((b,_)=>this.process(b,{...l,path:[...l.path,"prefixItems",_]}));if(this.target==="draft-2020-12"?p.prefixItems=f:p.items=f,s.rest){let b=this.process(s.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=b:p.additionalItems=b}s.rest&&(p.items=this.process(s.rest,{...l,path:[...l.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{let p=h;p.type="object",p.propertyNames=this.process(s.keyType,{...l,path:[...l.path,"propertyNames"]}),p.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 p=h,f=ti(s.entries);f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),p.enum=f;break}case"literal":{let p=h,f=[];for(let g of 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");f.push(Number(g))}else f.push(g);if(f.length!==0)if(f.length===1){let g=f[0];p.type=g===null?"null":typeof g,p.const=g}else f.every(g=>typeof g=="number")&&(p.type="number"),f.every(g=>typeof g=="string")&&(p.type="string"),f.every(g=>typeof g=="boolean")&&(p.type="string"),f.every(g=>g===null)&&(p.type="null"),p.enum=f;break}case"file":{let p=h,f={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:b}=e._zod.bag;g!==void 0&&(f.minLength=g),y!==void 0&&(f.maxLength=y),b?b.length===1?(f.contentMediaType=b[0],Object.assign(p,f)):p.anyOf=b.map(_=>({...f,contentMediaType:_})):Object.assign(p,f);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(s.innerType,l);h.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"success":{let p=h;p.type="boolean";break}case"default":{this.process(s.innerType,l),a.ref=s.innerType,h.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,l),a.ref=s.innerType,this.io==="input"&&(h._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,l),a.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}h.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=h,f=e._zod.pattern;if(!f)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=f.source;break}case"pipe":{let p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,l),a.ref=p;break}case"readonly":{this.process(s.innerType,l),a.ref=s.innerType,h.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 p=e._zod.innerType;this.process(p,l),a.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&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 f=n.external.registry.get(d[0])?.id,g=n.external.uri??(b=>b);if(f)return{ref:g(f)};let y=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=y,{defId:y,ref:`${g("__shared")}#/${l}/${y}`}}if(d[1]===s)return{ref:"#"};let h=`#/${l}/`,p=d[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:h+p}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:m,defId:h}=o(d);l.def={...l.schema},h&&(l.defId=h);let p=l.schema;for(let f in p)delete p[f];p.$ref=m};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
59
63
 
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 h=n.external.registry.get(d[0])?.id;if(e!==d[0]&&h){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let m=this.seen.get(d),h=m.def??m.schema,p={...h};if(m.ref===null)return;let f=m.ref;if(m.ref=null,f){a(f,l);let g=this.seen.get(f).schema;g.$ref&&l.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,p))}m.isParent||this.override({zodSchema:d,jsonSchema:h,path:m.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,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 Ix=x(()=>{});var ft=x(()=>{qs();gp();up();vx();uc();Sp();Tr();cc();hc();dm();xp();Cx();Rx();Ox();Ix()});var Qm=x(()=>{ft()});function ef(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new DI(r)}var NI,DI,Ax=x(()=>{ft();ft();Qm();NI=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");be.init(t,e),t.def=e,t.parse=(r,n)=>dp(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>is(t,r,n),t.parseAsync=async(r,n)=>mp(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>as(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))}),DI=w("ZodMiniObject",(t,e)=>{mc.init(t,e),NI.init(t,e),ae.defineLazy(t,"shape",()=>e.shape)})});var Nx=x(()=>{});var Dx=x(()=>{});var Mx=x(()=>{});var jx=x(()=>{ft();Qm();Ax();Nx();ft();hc();Dx();Mx()});var zx=x(()=>{jx()});var tf=x(()=>{zx()});function qt(t){return!!t._zod}function ls(t){let e=Object.values(t);if(e.length===0)return ef({});let r=e.every(qt),n=e.every(s=>!qt(s));if(r)return ef(t);if(n)return Jd(t);throw new Error("Mixed Zod versions detected in object shape.")}function dn(t,e){return qt(t)?is(t,e):t.safeParse(e)}async function kc(t,e){return qt(t)?await as(t,e):await t.safeParseAsync(e)}function pn(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 Ks(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 ls(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 wc(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 Fx(t){return t.description}function Ux(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 Ec(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 ci=x(()=>{Ko();tf()});var rf=x(()=>{ft()});var ui={};ze(ui,{ZodISODate:()=>Zx,ZodISODateTime:()=>Hx,ZodISODuration:()=>qx,ZodISOTime:()=>Bx,date:()=>sf,datetime:()=>nf,duration:()=>af,time:()=>of});function nf(t){return wx(Hx,t)}function sf(t){return Ex(Zx,t)}function of(t){return $x(Bx,t)}function af(t){return Tx(qx,t)}var Hx,Zx,Bx,qx,cf=x(()=>{ft();uf();Hx=w("ZodISODateTime",(t,e)=>{hx.init(t,e),Ae.init(t,e)});Zx=w("ZodISODate",(t,e)=>{gx.init(t,e),Ae.init(t,e)});Bx=w("ZodISOTime",(t,e)=>{yx.init(t,e),Ae.init(t,e)});qx=w("ZodISODuration",(t,e)=>{_x.init(t,e),Ae.init(t,e)})});var Vx,H4,li,lf=x(()=>{ft();ft();Vx=(t,e)=>{ic.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>cp(t,r)},flatten:{value:r=>ap(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},H4=w("ZodError",Vx),li=w("ZodError",Vx,{Parent:Error})});var Wx,Gx,Kx,Jx,df=x(()=>{ft();lf();Wx=lp(li),Gx=pp(li),Kx=fp(li),Jx=hp(li)});function k(t){return pm(qI,t)}function ge(t){return Nm(tS,t)}function Xx(t){return Dm(uA,t)}function Ke(t){return Mm(lA,t)}function rS(t){return jm(dA,t)}function Ne(){return zm(pA)}function fA(t){return Lm(mA,t)}function ue(t,e){return Px(hA,t,e)}function z(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new nS(r)}function ht(t,e){return new nS({type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},catchall:Ne(),...ae.normalizeParams(e)})}function Pe(t,e){return new sS({type:"union",options:t,...ae.normalizeParams(e)})}function ff(t,e,r){return new gA({type:"union",options:e,discriminator:t,...ae.normalizeParams(r)})}function Tc(t,e){return new yA({type:"intersection",left:t,right:e})}function $e(t,e,r){return new _A({type:"record",keyType:t,valueType:e,...ae.normalizeParams(r)})}function wt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new pf({type:"enum",entries:r,...ae.normalizeParams(e)})}function Z(t,e){return new bA({type:"literal",values:Array.isArray(t)?t:[t],...ae.normalizeParams(e)})}function oS(t){return new vA({type:"transform",transform:t})}function De(t){return new iS({type:"optional",innerType:t})}function Qx(t){return new xA({type:"nullable",innerType:t})}function kA(t,e){return new SA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function EA(t,e){return new wA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function $A(t,e){return new aS({type:"nonoptional",innerType:t,...ae.normalizeParams(e)})}function PA(t,e){return new TA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function mf(t,e){return new RA({type:"pipe",in:t,out:e})}function OA(t){return new CA({type:"readonly",innerType:t})}function IA(t){let e=new Xe({check:"custom"});return e._zod.check=t,e}function uS(t,e){return Jm(cS,t??(()=>!0),e)}function AA(t,e={}){return Ym(cS,t,e)}function NA(t){let e=IA(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(ae.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(ae.issue(s))}},t(r.value,r)));return e}function hf(t,e){return mf(oS(t),e)}var Fe,eS,qI,Ae,VI,Yx,$c,WI,GI,KI,JI,YI,XI,QI,eA,tA,rA,nA,sA,oA,iA,aA,cA,tS,uA,lA,dA,pA,mA,hA,nS,sS,gA,yA,_A,pf,bA,vA,iS,xA,SA,wA,aS,TA,RA,CA,cS,uf=x(()=>{ft();ft();rf();cf();df();Fe=w("ZodType",(t,e)=>(be.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)=>Wx(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Kx(t,r,n),t.parseAsync=async(r,n)=>Gx(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Jx(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(AA(r,n)),t.superRefine=r=>t.check(NA(r)),t.overwrite=r=>t.check(cs(r)),t.optional=()=>De(t),t.nullable=()=>Qx(t),t.nullish=()=>De(Qx(t)),t.nonoptional=r=>$A(t,r),t.array=()=>ue(t),t.or=r=>Pe([t,r]),t.and=r=>Tc(t,r),t.transform=r=>mf(t,oS(r)),t.default=r=>kA(t,r),t.prefault=r=>EA(t,r),t.catch=r=>PA(t,r),t.pipe=r=>mf(t,r),t.readonly=()=>OA(t),t.describe=r=>{let n=t.clone();return ln.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return ln.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return ln.get(t);let n=t.clone();return ln.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),eS=w("_ZodString",(t,e)=>{si.init(t,e),Fe.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(Fm(...n)),t.includes=(...n)=>t.check(Zm(...n)),t.startsWith=(...n)=>t.check(Bm(...n)),t.endsWith=(...n)=>t.check(qm(...n)),t.min=(...n)=>t.check(Gs(...n)),t.max=(...n)=>t.check(vc(...n)),t.length=(...n)=>t.check(xc(...n)),t.nonempty=(...n)=>t.check(Gs(1,...n)),t.lowercase=n=>t.check(Um(n)),t.uppercase=n=>t.check(Hm(n)),t.trim=()=>t.check(Wm()),t.normalize=(...n)=>t.check(Vm(...n)),t.toLowerCase=()=>t.check(Gm()),t.toUpperCase=()=>t.check(Km())}),qI=w("ZodString",(t,e)=>{si.init(t,e),eS.init(t,e),t.email=r=>t.check(mm(VI,r)),t.url=r=>t.check(_m(WI,r)),t.jwt=r=>t.check(Am(cA,r)),t.emoji=r=>t.check(bm(GI,r)),t.guid=r=>t.check(gc(Yx,r)),t.uuid=r=>t.check(fm($c,r)),t.uuidv4=r=>t.check(hm($c,r)),t.uuidv6=r=>t.check(gm($c,r)),t.uuidv7=r=>t.check(ym($c,r)),t.nanoid=r=>t.check(vm(KI,r)),t.guid=r=>t.check(gc(Yx,r)),t.cuid=r=>t.check(xm(JI,r)),t.cuid2=r=>t.check(Sm(YI,r)),t.ulid=r=>t.check(km(XI,r)),t.base64=r=>t.check(Cm(oA,r)),t.base64url=r=>t.check(Om(iA,r)),t.xid=r=>t.check(wm(QI,r)),t.ksuid=r=>t.check(Em(eA,r)),t.ipv4=r=>t.check($m(tA,r)),t.ipv6=r=>t.check(Tm(rA,r)),t.cidrv4=r=>t.check(Pm(nA,r)),t.cidrv6=r=>t.check(Rm(sA,r)),t.e164=r=>t.check(Im(aA,r)),t.datetime=r=>t.check(nf(r)),t.date=r=>t.check(sf(r)),t.time=r=>t.check(of(r)),t.duration=r=>t.check(af(r))});Ae=w("ZodStringFormat",(t,e)=>{Ee.init(t,e),eS.init(t,e)}),VI=w("ZodEmail",(t,e)=>{$p.init(t,e),Ae.init(t,e)}),Yx=w("ZodGUID",(t,e)=>{wp.init(t,e),Ae.init(t,e)}),$c=w("ZodUUID",(t,e)=>{Ep.init(t,e),Ae.init(t,e)}),WI=w("ZodURL",(t,e)=>{Tp.init(t,e),Ae.init(t,e)}),GI=w("ZodEmoji",(t,e)=>{Pp.init(t,e),Ae.init(t,e)}),KI=w("ZodNanoID",(t,e)=>{Rp.init(t,e),Ae.init(t,e)}),JI=w("ZodCUID",(t,e)=>{Cp.init(t,e),Ae.init(t,e)}),YI=w("ZodCUID2",(t,e)=>{Op.init(t,e),Ae.init(t,e)}),XI=w("ZodULID",(t,e)=>{Ip.init(t,e),Ae.init(t,e)}),QI=w("ZodXID",(t,e)=>{Ap.init(t,e),Ae.init(t,e)}),eA=w("ZodKSUID",(t,e)=>{Np.init(t,e),Ae.init(t,e)}),tA=w("ZodIPv4",(t,e)=>{Dp.init(t,e),Ae.init(t,e)}),rA=w("ZodIPv6",(t,e)=>{Mp.init(t,e),Ae.init(t,e)}),nA=w("ZodCIDRv4",(t,e)=>{jp.init(t,e),Ae.init(t,e)}),sA=w("ZodCIDRv6",(t,e)=>{zp.init(t,e),Ae.init(t,e)}),oA=w("ZodBase64",(t,e)=>{Lp.init(t,e),Ae.init(t,e)}),iA=w("ZodBase64URL",(t,e)=>{Fp.init(t,e),Ae.init(t,e)}),aA=w("ZodE164",(t,e)=>{Up.init(t,e),Ae.init(t,e)}),cA=w("ZodJWT",(t,e)=>{Hp.init(t,e),Ae.init(t,e)}),tS=w("ZodNumber",(t,e)=>{pc.init(t,e),Fe.init(t,e),t.gt=(n,s)=>t.check(_c(n,s)),t.gte=(n,s)=>t.check(ai(n,s)),t.min=(n,s)=>t.check(ai(n,s)),t.lt=(n,s)=>t.check(yc(n,s)),t.lte=(n,s)=>t.check(ii(n,s)),t.max=(n,s)=>t.check(ii(n,s)),t.int=n=>t.check(Xx(n)),t.safe=n=>t.check(Xx(n)),t.positive=n=>t.check(_c(0,n)),t.nonnegative=n=>t.check(ai(0,n)),t.negative=n=>t.check(yc(0,n)),t.nonpositive=n=>t.check(ii(0,n)),t.multipleOf=(n,s)=>t.check(bc(n,s)),t.step=(n,s)=>t.check(bc(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});uA=w("ZodNumberFormat",(t,e)=>{Zp.init(t,e),tS.init(t,e)});lA=w("ZodBoolean",(t,e)=>{Bp.init(t,e),Fe.init(t,e)});dA=w("ZodNull",(t,e)=>{qp.init(t,e),Fe.init(t,e)});pA=w("ZodUnknown",(t,e)=>{Vp.init(t,e),Fe.init(t,e)});mA=w("ZodNever",(t,e)=>{Wp.init(t,e),Fe.init(t,e)});hA=w("ZodArray",(t,e)=>{Gp.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Gs(r,n)),t.nonempty=r=>t.check(Gs(1,r)),t.max=(r,n)=>t.check(vc(r,n)),t.length=(r,n)=>t.check(xc(r,n)),t.unwrap=()=>t.element});nS=w("ZodObject",(t,e)=>{mc.init(t,e),Fe.init(t,e),ae.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>wt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ne()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ne()}),t.strict=()=>t.clone({...t._zod.def,catchall:fA()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>ae.extend(t,r),t.merge=r=>ae.merge(t,r),t.pick=r=>ae.pick(t,r),t.omit=r=>ae.omit(t,r),t.partial=(...r)=>ae.partial(iS,t,r[0]),t.required=(...r)=>ae.required(aS,t,r[0])});sS=w("ZodUnion",(t,e)=>{fc.init(t,e),Fe.init(t,e),t.options=e.options});gA=w("ZodDiscriminatedUnion",(t,e)=>{sS.init(t,e),Kp.init(t,e)});yA=w("ZodIntersection",(t,e)=>{Jp.init(t,e),Fe.init(t,e)});_A=w("ZodRecord",(t,e)=>{Yp.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});pf=w("ZodEnum",(t,e)=>{Xp.init(t,e),Fe.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 pf({...e,checks:[],...ae.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 pf({...e,checks:[],...ae.normalizeParams(s),entries:o})}});bA=w("ZodLiteral",(t,e)=>{Qp.init(t,e),Fe.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]}})});vA=w("ZodTransform",(t,e)=>{em.init(t,e),Fe.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=o=>{if(typeof o=="string")r.issues.push(ae.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(ae.issue(i))}};let s=e.transform(r.value,r);return s instanceof Promise?s.then(o=>(r.value=o,r)):(r.value=s,r)}});iS=w("ZodOptional",(t,e)=>{tm.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});xA=w("ZodNullable",(t,e)=>{rm.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});SA=w("ZodDefault",(t,e)=>{nm.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});wA=w("ZodPrefault",(t,e)=>{sm.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});aS=w("ZodNonOptional",(t,e)=>{om.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});TA=w("ZodCatch",(t,e)=>{im.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});RA=w("ZodPipe",(t,e)=>{am.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});CA=w("ZodReadonly",(t,e)=>{cm.init(t,e),Fe.init(t,e)});cS=w("ZodCustom",(t,e)=>{um.init(t,e),Fe.init(t,e)})});var lS=x(()=>{});var dS=x(()=>{});var pS=x(()=>{ft();uf();rf();lf();df();lS();ft();Sx();hc();cf();dS();It(xx())});var mS=x(()=>{pS()});var fS=x(()=>{mS()});function OS(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function IS(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var yf,hS,mn,Rc,We,gS,yS,s9,jA,zA,_f,Nt,di,_S,Qe,Vt,Wt,et,Cc,bS,bf,vS,xS,vf,pi,V,xf,SS,kS,o9,Oc,LA,Ic,FA,mi,Js,wS,UA,HA,ZA,BA,qA,VA,Sf,WA,GA,kf,Ac,KA,JA,Nc,YA,fi,hi,XA,gi,Ys,QA,yi,Dc,Mc,jc,i9,zc,Lc,Fc,ES,$S,TS,wf,PS,_i,Xs,RS,eN,Qs,tN,eo,rN,Ef,nN,Uc,sN,oN,iN,aN,cN,uN,lN,dN,pN,mN,to,fN,hN,Hc,$f,Tf,Pf,gN,yN,_N,Rf,bN,vN,xN,SN,kN,CS,Zc,wN,Bc,a9,EN,ro,$N,c9,bi,TN,Cf,PN,RN,CN,ON,IN,AN,NN,Pc,DN,MN,jN,vi,Of,zN,LN,FN,UN,HN,ZN,BN,qN,VN,WN,GN,KN,JN,YN,XN,QN,e1,t1,no,r1,n1,s1,qc,o1,i1,a1,If,c1,u9,l9,d9,p9,m9,f9,H,gf,ds=x(()=>{fS();yf="2025-11-25",hS=[yf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],mn="io.modelcontextprotocol/related-task",Rc="2.0",We=uS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),gS=Pe([k(),ge().int()]),yS=k(),s9=ht({ttl:ge().optional(),pollInterval:ge().optional()}),jA=z({ttl:ge().optional()}),zA=z({taskId:k()}),_f=ht({progressToken:gS.optional(),[mn]:zA.optional()}),Nt=z({_meta:_f.optional()}),di=Nt.extend({task:jA.optional()}),_S=t=>di.safeParse(t).success,Qe=z({method:k(),params:Nt.loose().optional()}),Vt=z({_meta:_f.optional()}),Wt=z({method:k(),params:Vt.loose().optional()}),et=ht({_meta:_f.optional()}),Cc=Pe([k(),ge().int()]),bS=z({jsonrpc:Z(Rc),id:Cc,...Qe.shape}).strict(),bf=t=>bS.safeParse(t).success,vS=z({jsonrpc:Z(Rc),...Wt.shape}).strict(),xS=t=>vS.safeParse(t).success,vf=z({jsonrpc:Z(Rc),id:Cc,result:et}).strict(),pi=t=>vf.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={}));xf=z({jsonrpc:Z(Rc),id:Cc.optional(),error:z({code:ge().int(),message:k(),data:Ne().optional()})}).strict(),SS=t=>xf.safeParse(t).success,kS=Pe([bS,vS,vf,xf]),o9=Pe([vf,xf]),Oc=et.strict(),LA=Vt.extend({requestId:Cc.optional(),reason:k().optional()}),Ic=Wt.extend({method:Z("notifications/cancelled"),params:LA}),FA=z({src:k(),mimeType:k().optional(),sizes:ue(k()).optional(),theme:wt(["light","dark"]).optional()}),mi=z({icons:ue(FA).optional()}),Js=z({name:k(),title:k().optional()}),wS=Js.extend({...Js.shape,...mi.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),UA=Tc(z({applyDefaults:Ke().optional()}),$e(k(),Ne())),HA=hf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Tc(z({form:UA.optional(),url:We.optional()}),$e(k(),Ne()).optional())),ZA=ht({list:We.optional(),cancel:We.optional(),requests:ht({sampling:ht({createMessage:We.optional()}).optional(),elicitation:ht({create:We.optional()}).optional()}).optional()}),BA=ht({list:We.optional(),cancel:We.optional(),requests:ht({tools:ht({call:We.optional()}).optional()}).optional()}),qA=z({experimental:$e(k(),We).optional(),sampling:z({context:We.optional(),tools:We.optional()}).optional(),elicitation:HA.optional(),roots:z({listChanged:Ke().optional()}).optional(),tasks:ZA.optional(),extensions:$e(k(),We).optional()}),VA=Nt.extend({protocolVersion:k(),capabilities:qA,clientInfo:wS}),Sf=Qe.extend({method:Z("initialize"),params:VA}),WA=z({experimental:$e(k(),We).optional(),logging:We.optional(),completions:We.optional(),prompts:z({listChanged:Ke().optional()}).optional(),resources:z({subscribe:Ke().optional(),listChanged:Ke().optional()}).optional(),tools:z({listChanged:Ke().optional()}).optional(),tasks:BA.optional(),extensions:$e(k(),We).optional()}),GA=et.extend({protocolVersion:k(),capabilities:WA,serverInfo:wS,instructions:k().optional()}),kf=Wt.extend({method:Z("notifications/initialized"),params:Vt.optional()}),Ac=Qe.extend({method:Z("ping"),params:Nt.optional()}),KA=z({progress:ge(),total:De(ge()),message:De(k())}),JA=z({...Vt.shape,...KA.shape,progressToken:gS}),Nc=Wt.extend({method:Z("notifications/progress"),params:JA}),YA=Nt.extend({cursor:yS.optional()}),fi=Qe.extend({params:YA.optional()}),hi=et.extend({nextCursor:yS.optional()}),XA=wt(["working","input_required","completed","failed","cancelled"]),gi=z({taskId:k(),status:XA,ttl:Pe([ge(),rS()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:De(ge()),statusMessage:De(k())}),Ys=et.extend({task:gi}),QA=Vt.merge(gi),yi=Wt.extend({method:Z("notifications/tasks/status"),params:QA}),Dc=Qe.extend({method:Z("tasks/get"),params:Nt.extend({taskId:k()})}),Mc=et.merge(gi),jc=Qe.extend({method:Z("tasks/result"),params:Nt.extend({taskId:k()})}),i9=et.loose(),zc=fi.extend({method:Z("tasks/list")}),Lc=hi.extend({tasks:ue(gi)}),Fc=Qe.extend({method:Z("tasks/cancel"),params:Nt.extend({taskId:k()})}),ES=et.merge(gi),$S=z({uri:k(),mimeType:De(k()),_meta:$e(k(),Ne()).optional()}),TS=$S.extend({text:k()}),wf=k().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),PS=$S.extend({blob:wf}),_i=wt(["user","assistant"]),Xs=z({audience:ue(_i).optional(),priority:ge().min(0).max(1).optional(),lastModified:ui.datetime({offset:!0}).optional()}),RS=z({...Js.shape,...mi.shape,uri:k(),description:De(k()),mimeType:De(k()),size:De(ge()),annotations:Xs.optional(),_meta:De(ht({}))}),eN=z({...Js.shape,...mi.shape,uriTemplate:k(),description:De(k()),mimeType:De(k()),annotations:Xs.optional(),_meta:De(ht({}))}),Qs=fi.extend({method:Z("resources/list")}),tN=hi.extend({resources:ue(RS)}),eo=fi.extend({method:Z("resources/templates/list")}),rN=hi.extend({resourceTemplates:ue(eN)}),Ef=Nt.extend({uri:k()}),nN=Ef,Uc=Qe.extend({method:Z("resources/read"),params:nN}),sN=et.extend({contents:ue(Pe([TS,PS]))}),oN=Wt.extend({method:Z("notifications/resources/list_changed"),params:Vt.optional()}),iN=Ef,aN=Qe.extend({method:Z("resources/subscribe"),params:iN}),cN=Ef,uN=Qe.extend({method:Z("resources/unsubscribe"),params:cN}),lN=Vt.extend({uri:k()}),dN=Wt.extend({method:Z("notifications/resources/updated"),params:lN}),pN=z({name:k(),description:De(k()),required:De(Ke())}),mN=z({...Js.shape,...mi.shape,description:De(k()),arguments:De(ue(pN)),_meta:De(ht({}))}),to=fi.extend({method:Z("prompts/list")}),fN=hi.extend({prompts:ue(mN)}),hN=Nt.extend({name:k(),arguments:$e(k(),k()).optional()}),Hc=Qe.extend({method:Z("prompts/get"),params:hN}),$f=z({type:Z("text"),text:k(),annotations:Xs.optional(),_meta:$e(k(),Ne()).optional()}),Tf=z({type:Z("image"),data:wf,mimeType:k(),annotations:Xs.optional(),_meta:$e(k(),Ne()).optional()}),Pf=z({type:Z("audio"),data:wf,mimeType:k(),annotations:Xs.optional(),_meta:$e(k(),Ne()).optional()}),gN=z({type:Z("tool_use"),name:k(),id:k(),input:$e(k(),Ne()),_meta:$e(k(),Ne()).optional()}),yN=z({type:Z("resource"),resource:Pe([TS,PS]),annotations:Xs.optional(),_meta:$e(k(),Ne()).optional()}),_N=RS.extend({type:Z("resource_link")}),Rf=Pe([$f,Tf,Pf,_N,yN]),bN=z({role:_i,content:Rf}),vN=et.extend({description:k().optional(),messages:ue(bN)}),xN=Wt.extend({method:Z("notifications/prompts/list_changed"),params:Vt.optional()}),SN=z({title:k().optional(),readOnlyHint:Ke().optional(),destructiveHint:Ke().optional(),idempotentHint:Ke().optional(),openWorldHint:Ke().optional()}),kN=z({taskSupport:wt(["required","optional","forbidden"]).optional()}),CS=z({...Js.shape,...mi.shape,description:k().optional(),inputSchema:z({type:Z("object"),properties:$e(k(),We).optional(),required:ue(k()).optional()}).catchall(Ne()),outputSchema:z({type:Z("object"),properties:$e(k(),We).optional(),required:ue(k()).optional()}).catchall(Ne()).optional(),annotations:SN.optional(),execution:kN.optional(),_meta:$e(k(),Ne()).optional()}),Zc=fi.extend({method:Z("tools/list")}),wN=hi.extend({tools:ue(CS)}),Bc=et.extend({content:ue(Rf).default([]),structuredContent:$e(k(),Ne()).optional(),isError:Ke().optional()}),a9=Bc.or(et.extend({toolResult:Ne()})),EN=di.extend({name:k(),arguments:$e(k(),Ne()).optional()}),ro=Qe.extend({method:Z("tools/call"),params:EN}),$N=Wt.extend({method:Z("notifications/tools/list_changed"),params:Vt.optional()}),c9=z({autoRefresh:Ke().default(!0),debounceMs:ge().int().nonnegative().default(300)}),bi=wt(["debug","info","notice","warning","error","critical","alert","emergency"]),TN=Nt.extend({level:bi}),Cf=Qe.extend({method:Z("logging/setLevel"),params:TN}),PN=Vt.extend({level:bi,logger:k().optional(),data:Ne()}),RN=Wt.extend({method:Z("notifications/message"),params:PN}),CN=z({name:k().optional()}),ON=z({hints:ue(CN).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),IN=z({mode:wt(["auto","required","none"]).optional()}),AN=z({type:Z("tool_result"),toolUseId:k().describe("The unique identifier for the corresponding tool call."),content:ue(Rf).default([]),structuredContent:z({}).loose().optional(),isError:Ke().optional(),_meta:$e(k(),Ne()).optional()}),NN=ff("type",[$f,Tf,Pf]),Pc=ff("type",[$f,Tf,Pf,gN,AN]),DN=z({role:_i,content:Pe([Pc,ue(Pc)]),_meta:$e(k(),Ne()).optional()}),MN=di.extend({messages:ue(DN),modelPreferences:ON.optional(),systemPrompt:k().optional(),includeContext:wt(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:ue(k()).optional(),metadata:We.optional(),tools:ue(CS).optional(),toolChoice:IN.optional()}),jN=Qe.extend({method:Z("sampling/createMessage"),params:MN}),vi=et.extend({model:k(),stopReason:De(wt(["endTurn","stopSequence","maxTokens"]).or(k())),role:_i,content:NN}),Of=et.extend({model:k(),stopReason:De(wt(["endTurn","stopSequence","maxTokens","toolUse"]).or(k())),role:_i,content:Pe([Pc,ue(Pc)])}),zN=z({type:Z("boolean"),title:k().optional(),description:k().optional(),default:Ke().optional()}),LN=z({type:Z("string"),title:k().optional(),description:k().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:wt(["email","uri","date","date-time"]).optional(),default:k().optional()}),FN=z({type:wt(["number","integer"]),title:k().optional(),description:k().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),UN=z({type:Z("string"),title:k().optional(),description:k().optional(),enum:ue(k()),default:k().optional()}),HN=z({type:Z("string"),title:k().optional(),description:k().optional(),oneOf:ue(z({const:k(),title:k()})),default:k().optional()}),ZN=z({type:Z("string"),title:k().optional(),description:k().optional(),enum:ue(k()),enumNames:ue(k()).optional(),default:k().optional()}),BN=Pe([UN,HN]),qN=z({type:Z("array"),title:k().optional(),description:k().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({type:Z("string"),enum:ue(k())}),default:ue(k()).optional()}),VN=z({type:Z("array"),title:k().optional(),description:k().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({anyOf:ue(z({const:k(),title:k()}))}),default:ue(k()).optional()}),WN=Pe([qN,VN]),GN=Pe([ZN,BN,WN]),KN=Pe([GN,zN,LN,FN]),JN=di.extend({mode:Z("form").optional(),message:k(),requestedSchema:z({type:Z("object"),properties:$e(k(),KN),required:ue(k()).optional()})}),YN=di.extend({mode:Z("url"),message:k(),elicitationId:k(),url:k().url()}),XN=Pe([JN,YN]),QN=Qe.extend({method:Z("elicitation/create"),params:XN}),e1=Vt.extend({elicitationId:k()}),t1=Wt.extend({method:Z("notifications/elicitation/complete"),params:e1}),no=et.extend({action:wt(["accept","decline","cancel"]),content:hf(t=>t===null?void 0:t,$e(k(),Pe([k(),ge(),Ke(),ue(k())])).optional())}),r1=z({type:Z("ref/resource"),uri:k()}),n1=z({type:Z("ref/prompt"),name:k()}),s1=Nt.extend({ref:Pe([n1,r1]),argument:z({name:k(),value:k()}),context:z({arguments:$e(k(),k()).optional()}).optional()}),qc=Qe.extend({method:Z("completion/complete"),params:s1});o1=et.extend({completion:ht({values:ue(k()).max(100),total:De(ge().int()),hasMore:De(Ke())})}),i1=z({uri:k().startsWith("file://"),name:k().optional(),_meta:$e(k(),Ne()).optional()}),a1=Qe.extend({method:Z("roots/list"),params:Nt.optional()}),If=et.extend({roots:ue(i1)}),c1=Wt.extend({method:Z("notifications/roots/list_changed"),params:Vt.optional()}),u9=Pe([Ac,Sf,qc,Cf,Hc,to,Qs,eo,Uc,aN,uN,ro,Zc,Dc,jc,zc,Fc]),l9=Pe([Ic,Nc,kf,c1,yi]),d9=Pe([Oc,vi,Of,no,If,Mc,Lc,Ys]),p9=Pe([Ac,jN,QN,a1,Dc,jc,zc,Fc]),m9=Pe([Ic,Nc,RN,dN,oN,$N,xN,yi,t1]),f9=Pe([Oc,GA,o1,vN,fN,tN,rN,sN,Bc,wN,Mc,Lc,Ys]),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 gf(s.elicitations,r)}return new t(e,r,n)}},gf=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 fn(t){return t==="completed"||t==="failed"||t==="cancelled"}var AS=x(()=>{});var DS,NS,MS,Vc=x(()=>{DS=Symbol("Let zodToJsonSchema decide on which parser to use"),NS={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"},MS=t=>typeof t=="string"?{...NS,name:t}:{...NS,...t}});var jS,Af=x(()=>{Vc();jS=t=>{let e=MS(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 Nf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function le(t,e,r,n,s){t[e]=r,Nf(t,e,n,s)}var hn=x(()=>{});var Wc,Gc=x(()=>{Wc=(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 Me(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Wc(e,t.currentPath):e.join("/")}}var Gt=x(()=>{Gc()});function zS(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&&le(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&le(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(le(r,"minItems",t.exactLength.value,t.exactLength.message,e),le(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Df=x(()=>{Ko();hn();qe()});function LS(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?le(r,"minimum",n.value,n.message,e):le(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(r,"maximum",n.value,n.message,e):le(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",n.value,n.message,e));break;case"multipleOf":le(r,"multipleOf",n.value,n.message,e);break}return r}var Mf=x(()=>{hn()});function FS(){return{type:"boolean"}}var jf=x(()=>{});function Kc(t,e){return J(t.type._def,e)}var Jc=x(()=>{qe()});var US,zf=x(()=>{qe();US=(t,e)=>J(t.innerType._def,e)});function Lf(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Lf(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 u1(t,e)}}var u1,Ff=x(()=>{hn();u1=(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":le(r,"minimum",n.value,n.message,e);break;case"max":le(r,"maximum",n.value,n.message,e);break}return r}});function HS(t,e){return{...J(t.innerType._def,e),default:t.defaultValue()}}var Uf=x(()=>{qe()});function ZS(t,e){return e.effectStrategy==="input"?J(t.schema._def,e):Me(e)}var Hf=x(()=>{qe();Gt()});function BS(t){return{type:"string",enum:Array.from(t.values)}}var Zf=x(()=>{});function qS(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(l1(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 l1,Bf=x(()=>{qe();l1=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function VS(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 qf=x(()=>{});function Yc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":le(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":lr(r,"email",n.message,e);break;case"format:idn-email":lr(r,"idn-email",n.message,e);break;case"pattern:zod":gt(r,ur.email,n.message,e);break}break;case"url":lr(r,"uri",n.message,e);break;case"uuid":lr(r,"uuid",n.message,e);break;case"regex":gt(r,n.regex,n.message,e);break;case"cuid":gt(r,ur.cuid,n.message,e);break;case"cuid2":gt(r,ur.cuid2,n.message,e);break;case"startsWith":gt(r,RegExp(`^${Wf(n.value,e)}`),n.message,e);break;case"endsWith":gt(r,RegExp(`${Wf(n.value,e)}$`),n.message,e);break;case"datetime":lr(r,"date-time",n.message,e);break;case"date":lr(r,"date",n.message,e);break;case"time":lr(r,"time",n.message,e);break;case"duration":lr(r,"duration",n.message,e);break;case"length":le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{gt(r,RegExp(Wf(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&lr(r,"ipv4",n.message,e),n.version!=="v4"&&lr(r,"ipv6",n.message,e);break}case"base64url":gt(r,ur.base64url,n.message,e);break;case"jwt":gt(r,ur.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&gt(r,ur.ipv4Cidr,n.message,e),n.version!=="v4"&&gt(r,ur.ipv6Cidr,n.message,e);break}case"emoji":gt(r,ur.emoji(),n.message,e);break;case"ulid":{gt(r,ur.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{lr(r,"binary",n.message,e);break}case"contentEncoding:base64":{le(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{gt(r,ur.base64,n.message,e);break}}break}case"nanoid":gt(r,ur.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Wf(t,e){return e.patternStrategy==="escape"?p1(t):t}function p1(t){let e="";for(let r=0;r<t.length;r++)d1.has(t[r])||(e+="\\"),e+=t[r];return e}function lr(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}}})):le(t,"format",e,r,n)}function gt(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:WS(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):le(t,"pattern",WS(e,n),r,n)}function WS(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
64
+ 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 h=n.external.registry.get(d[0])?.id;if(e!==d[0]&&h){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let m=this.seen.get(d),h=m.def??m.schema,p={...h};if(m.ref===null)return;let f=m.ref;if(m.ref=null,f){a(f,l);let g=this.seen.get(f).schema;g.$ref&&l.target==="draft-7"?(h.allOf=h.allOf??[],h.allOf.push(g)):(Object.assign(h,g),Object.assign(h,p))}m.isParent||this.override({zodSchema:d,jsonSchema:h,path:m.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,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 zx=x(()=>{});var ft=x(()=>{Ws();kp();gp();$x();hc();Rp();Pr();fc();xc();_m();Pp();Mx();Dx();jx();zx()});var af=x(()=>{ft()});function cf(t,e){let r={type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},...ce.normalizeParams(e)};return new HI(r)}var UI,HI,Lx=x(()=>{ft();ft();af();UI=w("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");be.init(t,e),t.def=e,t.parse=(r,n)=>_p(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>as(t,r,n),t.parseAsync=async(r,n)=>vp(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>cs(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)=>Nt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),HI=w("ZodMiniObject",(t,e)=>{bc.init(t,e),UI.init(t,e),ce.defineLazy(t,"shape",()=>e.shape)})});var Fx=x(()=>{});var Ux=x(()=>{});var Hx=x(()=>{});var Zx=x(()=>{ft();af();Lx();Fx();ft();xc();Ux();Hx()});var Bx=x(()=>{Zx()});var uf=x(()=>{Bx()});function Vt(t){return!!t._zod}function ds(t){let e=Object.values(t);if(e.length===0)return cf({});let r=e.every(Vt),n=e.every(s=>!Vt(s));if(r)return cf(t);if(n)return np(t);throw new Error("Mixed Zod versions detected in object shape.")}function mn(t,e){return Vt(t)?as(t,e):t.safeParse(e)}async function Rc(t,e){return Vt(t)?await cs(t,e):await t.safeParseAsync(e)}function fn(t){if(!t)return;let e;if(Vt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Ys(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 ds(t)}}if(Vt(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 Cc(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 Vx(t){return t.description}function Wx(t){if(Vt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Oc(t){if(Vt(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 pi=x(()=>{Qo();uf()});var lf=x(()=>{ft()});var mi={};Ie(mi,{ZodISODate:()=>Kx,ZodISODateTime:()=>Gx,ZodISODuration:()=>Yx,ZodISOTime:()=>Jx,date:()=>pf,datetime:()=>df,duration:()=>ff,time:()=>mf});function df(t){return Cx(Gx,t)}function pf(t){return Ox(Kx,t)}function mf(t){return Ix(Jx,t)}function ff(t){return Ax(Yx,t)}var Gx,Kx,Jx,Yx,hf=x(()=>{ft();gf();Gx=w("ZodISODateTime",(t,e)=>{xx.init(t,e),Ne.init(t,e)});Kx=w("ZodISODate",(t,e)=>{Sx.init(t,e),Ne.init(t,e)});Jx=w("ZodISOTime",(t,e)=>{kx.init(t,e),Ne.init(t,e)});Yx=w("ZodISODuration",(t,e)=>{wx.init(t,e),Ne.init(t,e)})});var Xx,G4,fi,yf=x(()=>{ft();ft();Xx=(t,e)=>{pc.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>hp(t,r)},flatten:{value:r=>fp(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},G4=w("ZodError",Xx),fi=w("ZodError",Xx,{Parent:Error})});var Qx,eS,tS,rS,_f=x(()=>{ft();yf();Qx=yp(fi),eS=bp(fi),tS=xp(fi),rS=Sp(fi)});function k(t){return bm(XI,t)}function ge(t){return Um(aS,t)}function sS(t){return Hm(gA,t)}function Ke(t){return Zm(yA,t)}function cS(t){return Bm(_A,t)}function De(){return qm(bA)}function xA(t){return Vm(vA,t)}function ue(t,e){return Nx(SA,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 uS(r)}function ht(t,e){return new uS({type:"object",get shape(){return ce.assignProp(this,"shape",{...t}),this.shape},catchall:De(),...ce.normalizeParams(e)})}function Pe(t,e){return new lS({type:"union",options:t,...ce.normalizeParams(e)})}function xf(t,e,r){return new kA({type:"union",options:e,discriminator:t,...ce.normalizeParams(r)})}function Ac(t,e){return new wA({type:"intersection",left:t,right:e})}function $e(t,e,r){return new EA({type:"record",keyType:t,valueType:e,...ce.normalizeParams(r)})}function wt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new bf({type:"enum",entries:r,...ce.normalizeParams(e)})}function Z(t,e){return new $A({type:"literal",values:Array.isArray(t)?t:[t],...ce.normalizeParams(e)})}function dS(t){return new TA({type:"transform",transform:t})}function Me(t){return new pS({type:"optional",innerType:t})}function oS(t){return new PA({type:"nullable",innerType:t})}function CA(t,e){return new RA({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function IA(t,e){return new OA({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function AA(t,e){return new mS({type:"nonoptional",innerType:t,...ce.normalizeParams(e)})}function DA(t,e){return new NA({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function vf(t,e){return new MA({type:"pipe",in:t,out:e})}function zA(t){return new jA({type:"readonly",innerType:t})}function LA(t){let e=new Xe({check:"custom"});return e._zod.check=t,e}function hS(t,e){return nf(fS,t??(()=>!0),e)}function FA(t,e={}){return sf(fS,t,e)}function UA(t){let e=LA(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 Sf(t,e){return vf(dS(t),e)}var Fe,iS,XI,Ne,QI,nS,Ic,eA,tA,rA,nA,sA,oA,iA,aA,cA,uA,lA,dA,pA,mA,fA,hA,aS,gA,yA,_A,bA,vA,SA,uS,lS,kA,wA,EA,bf,$A,TA,pS,PA,RA,OA,mS,NA,MA,jA,fS,gf=x(()=>{ft();ft();lf();hf();_f();Fe=w("ZodType",(t,e)=>(be.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)=>Nt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>Qx(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>tS(t,r,n),t.parseAsync=async(r,n)=>eS(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>rS(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(FA(r,n)),t.superRefine=r=>t.check(UA(r)),t.overwrite=r=>t.check(us(r)),t.optional=()=>Me(t),t.nullable=()=>oS(t),t.nullish=()=>Me(oS(t)),t.nonoptional=r=>AA(t,r),t.array=()=>ue(t),t.or=r=>Pe([t,r]),t.and=r=>Ac(t,r),t.transform=r=>vf(t,dS(r)),t.default=r=>CA(t,r),t.prefault=r=>IA(t,r),t.catch=r=>DA(t,r),t.pipe=r=>vf(t,r),t.readonly=()=>zA(t),t.describe=r=>{let n=t.clone();return pn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return pn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return pn.get(t);let n=t.clone();return pn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),iS=w("_ZodString",(t,e)=>{ci.init(t,e),Fe.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(Wm(...n)),t.includes=(...n)=>t.check(Jm(...n)),t.startsWith=(...n)=>t.check(Ym(...n)),t.endsWith=(...n)=>t.check(Xm(...n)),t.min=(...n)=>t.check(Js(...n)),t.max=(...n)=>t.check($c(...n)),t.length=(...n)=>t.check(Tc(...n)),t.nonempty=(...n)=>t.check(Js(1,...n)),t.lowercase=n=>t.check(Gm(n)),t.uppercase=n=>t.check(Km(n)),t.trim=()=>t.check(ef()),t.normalize=(...n)=>t.check(Qm(...n)),t.toLowerCase=()=>t.check(tf()),t.toUpperCase=()=>t.check(rf())}),XI=w("ZodString",(t,e)=>{ci.init(t,e),iS.init(t,e),t.email=r=>t.check(vm(QI,r)),t.url=r=>t.check(Em(eA,r)),t.jwt=r=>t.check(Fm(hA,r)),t.emoji=r=>t.check($m(tA,r)),t.guid=r=>t.check(Sc(nS,r)),t.uuid=r=>t.check(xm(Ic,r)),t.uuidv4=r=>t.check(Sm(Ic,r)),t.uuidv6=r=>t.check(km(Ic,r)),t.uuidv7=r=>t.check(wm(Ic,r)),t.nanoid=r=>t.check(Tm(rA,r)),t.guid=r=>t.check(Sc(nS,r)),t.cuid=r=>t.check(Pm(nA,r)),t.cuid2=r=>t.check(Rm(sA,r)),t.ulid=r=>t.check(Cm(oA,r)),t.base64=r=>t.check(jm(pA,r)),t.base64url=r=>t.check(zm(mA,r)),t.xid=r=>t.check(Om(iA,r)),t.ksuid=r=>t.check(Im(aA,r)),t.ipv4=r=>t.check(Am(cA,r)),t.ipv6=r=>t.check(Nm(uA,r)),t.cidrv4=r=>t.check(Dm(lA,r)),t.cidrv6=r=>t.check(Mm(dA,r)),t.e164=r=>t.check(Lm(fA,r)),t.datetime=r=>t.check(df(r)),t.date=r=>t.check(pf(r)),t.time=r=>t.check(mf(r)),t.duration=r=>t.check(ff(r))});Ne=w("ZodStringFormat",(t,e)=>{Ee.init(t,e),iS.init(t,e)}),QI=w("ZodEmail",(t,e)=>{Ap.init(t,e),Ne.init(t,e)}),nS=w("ZodGUID",(t,e)=>{Op.init(t,e),Ne.init(t,e)}),Ic=w("ZodUUID",(t,e)=>{Ip.init(t,e),Ne.init(t,e)}),eA=w("ZodURL",(t,e)=>{Np.init(t,e),Ne.init(t,e)}),tA=w("ZodEmoji",(t,e)=>{Dp.init(t,e),Ne.init(t,e)}),rA=w("ZodNanoID",(t,e)=>{Mp.init(t,e),Ne.init(t,e)}),nA=w("ZodCUID",(t,e)=>{jp.init(t,e),Ne.init(t,e)}),sA=w("ZodCUID2",(t,e)=>{zp.init(t,e),Ne.init(t,e)}),oA=w("ZodULID",(t,e)=>{Lp.init(t,e),Ne.init(t,e)}),iA=w("ZodXID",(t,e)=>{Fp.init(t,e),Ne.init(t,e)}),aA=w("ZodKSUID",(t,e)=>{Up.init(t,e),Ne.init(t,e)}),cA=w("ZodIPv4",(t,e)=>{Hp.init(t,e),Ne.init(t,e)}),uA=w("ZodIPv6",(t,e)=>{Zp.init(t,e),Ne.init(t,e)}),lA=w("ZodCIDRv4",(t,e)=>{Bp.init(t,e),Ne.init(t,e)}),dA=w("ZodCIDRv6",(t,e)=>{qp.init(t,e),Ne.init(t,e)}),pA=w("ZodBase64",(t,e)=>{Vp.init(t,e),Ne.init(t,e)}),mA=w("ZodBase64URL",(t,e)=>{Wp.init(t,e),Ne.init(t,e)}),fA=w("ZodE164",(t,e)=>{Gp.init(t,e),Ne.init(t,e)}),hA=w("ZodJWT",(t,e)=>{Kp.init(t,e),Ne.init(t,e)}),aS=w("ZodNumber",(t,e)=>{_c.init(t,e),Fe.init(t,e),t.gt=(n,s)=>t.check(wc(n,s)),t.gte=(n,s)=>t.check(di(n,s)),t.min=(n,s)=>t.check(di(n,s)),t.lt=(n,s)=>t.check(kc(n,s)),t.lte=(n,s)=>t.check(li(n,s)),t.max=(n,s)=>t.check(li(n,s)),t.int=n=>t.check(sS(n)),t.safe=n=>t.check(sS(n)),t.positive=n=>t.check(wc(0,n)),t.nonnegative=n=>t.check(di(0,n)),t.negative=n=>t.check(kc(0,n)),t.nonpositive=n=>t.check(li(0,n)),t.multipleOf=(n,s)=>t.check(Ec(n,s)),t.step=(n,s)=>t.check(Ec(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});gA=w("ZodNumberFormat",(t,e)=>{Jp.init(t,e),aS.init(t,e)});yA=w("ZodBoolean",(t,e)=>{Yp.init(t,e),Fe.init(t,e)});_A=w("ZodNull",(t,e)=>{Xp.init(t,e),Fe.init(t,e)});bA=w("ZodUnknown",(t,e)=>{Qp.init(t,e),Fe.init(t,e)});vA=w("ZodNever",(t,e)=>{em.init(t,e),Fe.init(t,e)});SA=w("ZodArray",(t,e)=>{tm.init(t,e),Fe.init(t,e),t.element=e.element,t.min=(r,n)=>t.check(Js(r,n)),t.nonempty=r=>t.check(Js(1,r)),t.max=(r,n)=>t.check($c(r,n)),t.length=(r,n)=>t.check(Tc(r,n)),t.unwrap=()=>t.element});uS=w("ZodObject",(t,e)=>{bc.init(t,e),Fe.init(t,e),ce.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>wt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:De()}),t.loose=()=>t.clone({...t._zod.def,catchall:De()}),t.strict=()=>t.clone({...t._zod.def,catchall:xA()}),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(pS,t,r[0]),t.required=(...r)=>ce.required(mS,t,r[0])});lS=w("ZodUnion",(t,e)=>{vc.init(t,e),Fe.init(t,e),t.options=e.options});kA=w("ZodDiscriminatedUnion",(t,e)=>{lS.init(t,e),rm.init(t,e)});wA=w("ZodIntersection",(t,e)=>{nm.init(t,e),Fe.init(t,e)});EA=w("ZodRecord",(t,e)=>{sm.init(t,e),Fe.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});bf=w("ZodEnum",(t,e)=>{om.init(t,e),Fe.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 bf({...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 bf({...e,checks:[],...ce.normalizeParams(s),entries:o})}});$A=w("ZodLiteral",(t,e)=>{im.init(t,e),Fe.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]}})});TA=w("ZodTransform",(t,e)=>{am.init(t,e),Fe.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)}});pS=w("ZodOptional",(t,e)=>{cm.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});PA=w("ZodNullable",(t,e)=>{um.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});RA=w("ZodDefault",(t,e)=>{lm.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});OA=w("ZodPrefault",(t,e)=>{dm.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});mS=w("ZodNonOptional",(t,e)=>{pm.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType});NA=w("ZodCatch",(t,e)=>{mm.init(t,e),Fe.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});MA=w("ZodPipe",(t,e)=>{fm.init(t,e),Fe.init(t,e),t.in=e.in,t.out=e.out});jA=w("ZodReadonly",(t,e)=>{hm.init(t,e),Fe.init(t,e)});fS=w("ZodCustom",(t,e)=>{gm.init(t,e),Fe.init(t,e)})});var gS=x(()=>{});var yS=x(()=>{});var _S=x(()=>{ft();gf();lf();yf();_f();gS();ft();Px();xc();hf();yS();At(Tx())});var bS=x(()=>{_S()});var vS=x(()=>{bS()});function jS(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function zS(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var wf,xS,hn,Dc,We,SS,kS,l9,BA,qA,Ef,Dt,hi,wS,Qe,Wt,Gt,et,Mc,ES,$f,$S,TS,Tf,gi,V,Pf,PS,RS,d9,jc,VA,zc,WA,yi,Xs,CS,GA,KA,JA,YA,XA,QA,Rf,eN,tN,Cf,Lc,rN,nN,Fc,sN,_i,bi,oN,vi,Qs,iN,xi,Uc,Hc,Zc,p9,Bc,qc,Vc,OS,IS,AS,Of,NS,Si,eo,DS,aN,to,cN,ro,uN,If,lN,Wc,dN,pN,mN,fN,hN,gN,yN,_N,bN,vN,no,xN,SN,Gc,Af,Nf,Df,kN,wN,EN,Mf,$N,TN,PN,RN,CN,MS,Kc,ON,Jc,m9,IN,so,AN,f9,ki,NN,jf,DN,MN,jN,zN,LN,FN,UN,Nc,HN,ZN,BN,wi,zf,qN,VN,WN,GN,KN,JN,YN,XN,QN,e1,t1,r1,n1,s1,o1,i1,a1,c1,oo,u1,l1,d1,Yc,p1,m1,f1,Lf,h1,h9,g9,y9,_9,b9,v9,H,kf,ps=x(()=>{vS();wf="2025-11-25",xS=[wf,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],hn="io.modelcontextprotocol/related-task",Dc="2.0",We=hS(t=>t!==null&&(typeof t=="object"||typeof t=="function")),SS=Pe([k(),ge().int()]),kS=k(),l9=ht({ttl:ge().optional(),pollInterval:ge().optional()}),BA=z({ttl:ge().optional()}),qA=z({taskId:k()}),Ef=ht({progressToken:SS.optional(),[hn]:qA.optional()}),Dt=z({_meta:Ef.optional()}),hi=Dt.extend({task:BA.optional()}),wS=t=>hi.safeParse(t).success,Qe=z({method:k(),params:Dt.loose().optional()}),Wt=z({_meta:Ef.optional()}),Gt=z({method:k(),params:Wt.loose().optional()}),et=ht({_meta:Ef.optional()}),Mc=Pe([k(),ge().int()]),ES=z({jsonrpc:Z(Dc),id:Mc,...Qe.shape}).strict(),$f=t=>ES.safeParse(t).success,$S=z({jsonrpc:Z(Dc),...Gt.shape}).strict(),TS=t=>$S.safeParse(t).success,Tf=z({jsonrpc:Z(Dc),id:Mc,result:et}).strict(),gi=t=>Tf.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={}));Pf=z({jsonrpc:Z(Dc),id:Mc.optional(),error:z({code:ge().int(),message:k(),data:De().optional()})}).strict(),PS=t=>Pf.safeParse(t).success,RS=Pe([ES,$S,Tf,Pf]),d9=Pe([Tf,Pf]),jc=et.strict(),VA=Wt.extend({requestId:Mc.optional(),reason:k().optional()}),zc=Gt.extend({method:Z("notifications/cancelled"),params:VA}),WA=z({src:k(),mimeType:k().optional(),sizes:ue(k()).optional(),theme:wt(["light","dark"]).optional()}),yi=z({icons:ue(WA).optional()}),Xs=z({name:k(),title:k().optional()}),CS=Xs.extend({...Xs.shape,...yi.shape,version:k(),websiteUrl:k().optional(),description:k().optional()}),GA=Ac(z({applyDefaults:Ke().optional()}),$e(k(),De())),KA=Sf(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Ac(z({form:GA.optional(),url:We.optional()}),$e(k(),De()).optional())),JA=ht({list:We.optional(),cancel:We.optional(),requests:ht({sampling:ht({createMessage:We.optional()}).optional(),elicitation:ht({create:We.optional()}).optional()}).optional()}),YA=ht({list:We.optional(),cancel:We.optional(),requests:ht({tools:ht({call:We.optional()}).optional()}).optional()}),XA=z({experimental:$e(k(),We).optional(),sampling:z({context:We.optional(),tools:We.optional()}).optional(),elicitation:KA.optional(),roots:z({listChanged:Ke().optional()}).optional(),tasks:JA.optional(),extensions:$e(k(),We).optional()}),QA=Dt.extend({protocolVersion:k(),capabilities:XA,clientInfo:CS}),Rf=Qe.extend({method:Z("initialize"),params:QA}),eN=z({experimental:$e(k(),We).optional(),logging:We.optional(),completions:We.optional(),prompts:z({listChanged:Ke().optional()}).optional(),resources:z({subscribe:Ke().optional(),listChanged:Ke().optional()}).optional(),tools:z({listChanged:Ke().optional()}).optional(),tasks:YA.optional(),extensions:$e(k(),We).optional()}),tN=et.extend({protocolVersion:k(),capabilities:eN,serverInfo:CS,instructions:k().optional()}),Cf=Gt.extend({method:Z("notifications/initialized"),params:Wt.optional()}),Lc=Qe.extend({method:Z("ping"),params:Dt.optional()}),rN=z({progress:ge(),total:Me(ge()),message:Me(k())}),nN=z({...Wt.shape,...rN.shape,progressToken:SS}),Fc=Gt.extend({method:Z("notifications/progress"),params:nN}),sN=Dt.extend({cursor:kS.optional()}),_i=Qe.extend({params:sN.optional()}),bi=et.extend({nextCursor:kS.optional()}),oN=wt(["working","input_required","completed","failed","cancelled"]),vi=z({taskId:k(),status:oN,ttl:Pe([ge(),cS()]),createdAt:k(),lastUpdatedAt:k(),pollInterval:Me(ge()),statusMessage:Me(k())}),Qs=et.extend({task:vi}),iN=Wt.merge(vi),xi=Gt.extend({method:Z("notifications/tasks/status"),params:iN}),Uc=Qe.extend({method:Z("tasks/get"),params:Dt.extend({taskId:k()})}),Hc=et.merge(vi),Zc=Qe.extend({method:Z("tasks/result"),params:Dt.extend({taskId:k()})}),p9=et.loose(),Bc=_i.extend({method:Z("tasks/list")}),qc=bi.extend({tasks:ue(vi)}),Vc=Qe.extend({method:Z("tasks/cancel"),params:Dt.extend({taskId:k()})}),OS=et.merge(vi),IS=z({uri:k(),mimeType:Me(k()),_meta:$e(k(),De()).optional()}),AS=IS.extend({text:k()}),Of=k().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),NS=IS.extend({blob:Of}),Si=wt(["user","assistant"]),eo=z({audience:ue(Si).optional(),priority:ge().min(0).max(1).optional(),lastModified:mi.datetime({offset:!0}).optional()}),DS=z({...Xs.shape,...yi.shape,uri:k(),description:Me(k()),mimeType:Me(k()),size:Me(ge()),annotations:eo.optional(),_meta:Me(ht({}))}),aN=z({...Xs.shape,...yi.shape,uriTemplate:k(),description:Me(k()),mimeType:Me(k()),annotations:eo.optional(),_meta:Me(ht({}))}),to=_i.extend({method:Z("resources/list")}),cN=bi.extend({resources:ue(DS)}),ro=_i.extend({method:Z("resources/templates/list")}),uN=bi.extend({resourceTemplates:ue(aN)}),If=Dt.extend({uri:k()}),lN=If,Wc=Qe.extend({method:Z("resources/read"),params:lN}),dN=et.extend({contents:ue(Pe([AS,NS]))}),pN=Gt.extend({method:Z("notifications/resources/list_changed"),params:Wt.optional()}),mN=If,fN=Qe.extend({method:Z("resources/subscribe"),params:mN}),hN=If,gN=Qe.extend({method:Z("resources/unsubscribe"),params:hN}),yN=Wt.extend({uri:k()}),_N=Gt.extend({method:Z("notifications/resources/updated"),params:yN}),bN=z({name:k(),description:Me(k()),required:Me(Ke())}),vN=z({...Xs.shape,...yi.shape,description:Me(k()),arguments:Me(ue(bN)),_meta:Me(ht({}))}),no=_i.extend({method:Z("prompts/list")}),xN=bi.extend({prompts:ue(vN)}),SN=Dt.extend({name:k(),arguments:$e(k(),k()).optional()}),Gc=Qe.extend({method:Z("prompts/get"),params:SN}),Af=z({type:Z("text"),text:k(),annotations:eo.optional(),_meta:$e(k(),De()).optional()}),Nf=z({type:Z("image"),data:Of,mimeType:k(),annotations:eo.optional(),_meta:$e(k(),De()).optional()}),Df=z({type:Z("audio"),data:Of,mimeType:k(),annotations:eo.optional(),_meta:$e(k(),De()).optional()}),kN=z({type:Z("tool_use"),name:k(),id:k(),input:$e(k(),De()),_meta:$e(k(),De()).optional()}),wN=z({type:Z("resource"),resource:Pe([AS,NS]),annotations:eo.optional(),_meta:$e(k(),De()).optional()}),EN=DS.extend({type:Z("resource_link")}),Mf=Pe([Af,Nf,Df,EN,wN]),$N=z({role:Si,content:Mf}),TN=et.extend({description:k().optional(),messages:ue($N)}),PN=Gt.extend({method:Z("notifications/prompts/list_changed"),params:Wt.optional()}),RN=z({title:k().optional(),readOnlyHint:Ke().optional(),destructiveHint:Ke().optional(),idempotentHint:Ke().optional(),openWorldHint:Ke().optional()}),CN=z({taskSupport:wt(["required","optional","forbidden"]).optional()}),MS=z({...Xs.shape,...yi.shape,description:k().optional(),inputSchema:z({type:Z("object"),properties:$e(k(),We).optional(),required:ue(k()).optional()}).catchall(De()),outputSchema:z({type:Z("object"),properties:$e(k(),We).optional(),required:ue(k()).optional()}).catchall(De()).optional(),annotations:RN.optional(),execution:CN.optional(),_meta:$e(k(),De()).optional()}),Kc=_i.extend({method:Z("tools/list")}),ON=bi.extend({tools:ue(MS)}),Jc=et.extend({content:ue(Mf).default([]),structuredContent:$e(k(),De()).optional(),isError:Ke().optional()}),m9=Jc.or(et.extend({toolResult:De()})),IN=hi.extend({name:k(),arguments:$e(k(),De()).optional()}),so=Qe.extend({method:Z("tools/call"),params:IN}),AN=Gt.extend({method:Z("notifications/tools/list_changed"),params:Wt.optional()}),f9=z({autoRefresh:Ke().default(!0),debounceMs:ge().int().nonnegative().default(300)}),ki=wt(["debug","info","notice","warning","error","critical","alert","emergency"]),NN=Dt.extend({level:ki}),jf=Qe.extend({method:Z("logging/setLevel"),params:NN}),DN=Wt.extend({level:ki,logger:k().optional(),data:De()}),MN=Gt.extend({method:Z("notifications/message"),params:DN}),jN=z({name:k().optional()}),zN=z({hints:ue(jN).optional(),costPriority:ge().min(0).max(1).optional(),speedPriority:ge().min(0).max(1).optional(),intelligencePriority:ge().min(0).max(1).optional()}),LN=z({mode:wt(["auto","required","none"]).optional()}),FN=z({type:Z("tool_result"),toolUseId:k().describe("The unique identifier for the corresponding tool call."),content:ue(Mf).default([]),structuredContent:z({}).loose().optional(),isError:Ke().optional(),_meta:$e(k(),De()).optional()}),UN=xf("type",[Af,Nf,Df]),Nc=xf("type",[Af,Nf,Df,kN,FN]),HN=z({role:Si,content:Pe([Nc,ue(Nc)]),_meta:$e(k(),De()).optional()}),ZN=hi.extend({messages:ue(HN),modelPreferences:zN.optional(),systemPrompt:k().optional(),includeContext:wt(["none","thisServer","allServers"]).optional(),temperature:ge().optional(),maxTokens:ge().int(),stopSequences:ue(k()).optional(),metadata:We.optional(),tools:ue(MS).optional(),toolChoice:LN.optional()}),BN=Qe.extend({method:Z("sampling/createMessage"),params:ZN}),wi=et.extend({model:k(),stopReason:Me(wt(["endTurn","stopSequence","maxTokens"]).or(k())),role:Si,content:UN}),zf=et.extend({model:k(),stopReason:Me(wt(["endTurn","stopSequence","maxTokens","toolUse"]).or(k())),role:Si,content:Pe([Nc,ue(Nc)])}),qN=z({type:Z("boolean"),title:k().optional(),description:k().optional(),default:Ke().optional()}),VN=z({type:Z("string"),title:k().optional(),description:k().optional(),minLength:ge().optional(),maxLength:ge().optional(),format:wt(["email","uri","date","date-time"]).optional(),default:k().optional()}),WN=z({type:wt(["number","integer"]),title:k().optional(),description:k().optional(),minimum:ge().optional(),maximum:ge().optional(),default:ge().optional()}),GN=z({type:Z("string"),title:k().optional(),description:k().optional(),enum:ue(k()),default:k().optional()}),KN=z({type:Z("string"),title:k().optional(),description:k().optional(),oneOf:ue(z({const:k(),title:k()})),default:k().optional()}),JN=z({type:Z("string"),title:k().optional(),description:k().optional(),enum:ue(k()),enumNames:ue(k()).optional(),default:k().optional()}),YN=Pe([GN,KN]),XN=z({type:Z("array"),title:k().optional(),description:k().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({type:Z("string"),enum:ue(k())}),default:ue(k()).optional()}),QN=z({type:Z("array"),title:k().optional(),description:k().optional(),minItems:ge().optional(),maxItems:ge().optional(),items:z({anyOf:ue(z({const:k(),title:k()}))}),default:ue(k()).optional()}),e1=Pe([XN,QN]),t1=Pe([JN,YN,e1]),r1=Pe([t1,qN,VN,WN]),n1=hi.extend({mode:Z("form").optional(),message:k(),requestedSchema:z({type:Z("object"),properties:$e(k(),r1),required:ue(k()).optional()})}),s1=hi.extend({mode:Z("url"),message:k(),elicitationId:k(),url:k().url()}),o1=Pe([n1,s1]),i1=Qe.extend({method:Z("elicitation/create"),params:o1}),a1=Wt.extend({elicitationId:k()}),c1=Gt.extend({method:Z("notifications/elicitation/complete"),params:a1}),oo=et.extend({action:wt(["accept","decline","cancel"]),content:Sf(t=>t===null?void 0:t,$e(k(),Pe([k(),ge(),Ke(),ue(k())])).optional())}),u1=z({type:Z("ref/resource"),uri:k()}),l1=z({type:Z("ref/prompt"),name:k()}),d1=Dt.extend({ref:Pe([l1,u1]),argument:z({name:k(),value:k()}),context:z({arguments:$e(k(),k()).optional()}).optional()}),Yc=Qe.extend({method:Z("completion/complete"),params:d1});p1=et.extend({completion:ht({values:ue(k()).max(100),total:Me(ge().int()),hasMore:Me(Ke())})}),m1=z({uri:k().startsWith("file://"),name:k().optional(),_meta:$e(k(),De()).optional()}),f1=Qe.extend({method:Z("roots/list"),params:Dt.optional()}),Lf=et.extend({roots:ue(m1)}),h1=Gt.extend({method:Z("notifications/roots/list_changed"),params:Wt.optional()}),h9=Pe([Lc,Rf,Yc,jf,Gc,no,to,ro,Wc,fN,gN,so,Kc,Uc,Zc,Bc,Vc]),g9=Pe([zc,Fc,Cf,h1,xi]),y9=Pe([jc,wi,zf,oo,Lf,Hc,qc,Qs]),_9=Pe([Lc,BN,i1,f1,Uc,Zc,Bc,Vc]),b9=Pe([zc,Fc,MN,_N,pN,AN,PN,xi,c1]),v9=Pe([jc,tN,p1,TN,xN,cN,uN,dN,Jc,ON,Hc,qc,Qs]),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 kf(s.elicitations,r)}return new t(e,r,n)}},kf=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 gn(t){return t==="completed"||t==="failed"||t==="cancelled"}var LS=x(()=>{});var US,FS,HS,Xc=x(()=>{US=Symbol("Let zodToJsonSchema decide on which parser to use"),FS={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"},HS=t=>typeof t=="string"?{...FS,name:t}:{...FS,...t}});var ZS,Ff=x(()=>{Xc();ZS=t=>{let e=HS(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 Uf(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function le(t,e,r,n,s){t[e]=r,Uf(t,e,n,s)}var yn=x(()=>{});var Qc,eu=x(()=>{Qc=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")}});function je(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Qc(e,t.currentPath):e.join("/")}}var Kt=x(()=>{eu()});function BS(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&&le(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&le(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(le(r,"minItems",t.exactLength.value,t.exactLength.message,e),le(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var Hf=x(()=>{Qo();yn();qe()});function qS(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?le(r,"minimum",n.value,n.message,e):le(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(r,"maximum",n.value,n.message,e):le(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",n.value,n.message,e));break;case"multipleOf":le(r,"multipleOf",n.value,n.message,e);break}return r}var Zf=x(()=>{yn()});function VS(){return{type:"boolean"}}var Bf=x(()=>{});function tu(t,e){return J(t.type._def,e)}var ru=x(()=>{qe()});var WS,qf=x(()=>{qe();WS=(t,e)=>J(t.innerType._def,e)});function Vf(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>Vf(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 g1(t,e)}}var g1,Wf=x(()=>{yn();g1=(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":le(r,"minimum",n.value,n.message,e);break;case"max":le(r,"maximum",n.value,n.message,e);break}return r}});function GS(t,e){return{...J(t.innerType._def,e),default:t.defaultValue()}}var Gf=x(()=>{qe()});function KS(t,e){return e.effectStrategy==="input"?J(t.schema._def,e):je(e)}var Kf=x(()=>{qe();Kt()});function JS(t){return{type:"string",enum:Array.from(t.values)}}var Jf=x(()=>{});function YS(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(y1(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 y1,Yf=x(()=>{qe();y1=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function XS(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 Xf=x(()=>{});function nu(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":le(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":lr(r,"email",n.message,e);break;case"format:idn-email":lr(r,"idn-email",n.message,e);break;case"pattern:zod":gt(r,ur.email,n.message,e);break}break;case"url":lr(r,"uri",n.message,e);break;case"uuid":lr(r,"uuid",n.message,e);break;case"regex":gt(r,n.regex,n.message,e);break;case"cuid":gt(r,ur.cuid,n.message,e);break;case"cuid2":gt(r,ur.cuid2,n.message,e);break;case"startsWith":gt(r,RegExp(`^${eh(n.value,e)}`),n.message,e);break;case"endsWith":gt(r,RegExp(`${eh(n.value,e)}$`),n.message,e);break;case"datetime":lr(r,"date-time",n.message,e);break;case"date":lr(r,"date",n.message,e);break;case"time":lr(r,"time",n.message,e);break;case"duration":lr(r,"duration",n.message,e);break;case"length":le(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),le(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{gt(r,RegExp(eh(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&lr(r,"ipv4",n.message,e),n.version!=="v4"&&lr(r,"ipv6",n.message,e);break}case"base64url":gt(r,ur.base64url,n.message,e);break;case"jwt":gt(r,ur.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&gt(r,ur.ipv4Cidr,n.message,e),n.version!=="v4"&&gt(r,ur.ipv6Cidr,n.message,e);break}case"emoji":gt(r,ur.emoji(),n.message,e);break;case"ulid":{gt(r,ur.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{lr(r,"binary",n.message,e);break}case"contentEncoding:base64":{le(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{gt(r,ur.base64,n.message,e);break}}break}case"nanoid":gt(r,ur.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function eh(t,e){return e.patternStrategy==="escape"?b1(t):t}function b1(t){let e="";for(let r=0;r<t.length;r++)_1.has(t[r])||(e+="\\"),e+=t[r];return e}function lr(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}}})):le(t,"format",e,r,n)}function gt(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:QS(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):le(t,"pattern",QS(e,n),r,n)}function QS(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
65
  ]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
62
66
  ]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
63
67
  `:`[${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 Vf,ur,d1,Xc=x(()=>{hn();ur={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:()=>(Vf===void 0&&(Vf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Vf),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-_]*$/};d1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Qc(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]})??Me(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}=Yc(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}=Kc(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var eu=x(()=>{Ko();qe();Xc();Jc();Gt()});function GS(t,e){if(e.mapStrategy==="record")return Qc(t,e);let r=J(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Me(e),n=J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Me(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Gf=x(()=>{qe();eu();Gt()});function KS(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 Kf=x(()=>{});function JS(t){return t.target==="openAi"?void 0:{not:Me({...t,currentPath:[...t.currentPath,"not"]})}}var Jf=x(()=>{Gt()});function YS(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Yf=x(()=>{});function QS(t,e){if(e.target==="openApi3")return XS(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in xi&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=xi[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 XS(t,e)}var xi,XS,tu=x(()=>{qe();xi={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};XS=(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 ek(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:xi[t.innerType._def.typeName],nullable:!0}:{type:[xi[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=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 Xf=x(()=>{qe();tu()});function tk(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",Nf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?le(r,"minimum",n.value,n.message,e):le(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(r,"maximum",n.value,n.message,e):le(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",n.value,n.message,e));break;case"multipleOf":le(r,"multipleOf",n.value,n.message,e);break}return r}var Qf=x(()=>{hn()});function rk(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=f1(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=m1(t,e);return i!==void 0&&(n.additionalProperties=i),n}function m1(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 f1(t){try{return t.isOptional()}catch{return!0}}var eh=x(()=>{qe()});var nk,th=x(()=>{qe();Gt();nk=(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:Me(e)},r]}:Me(e)}});var sk,rh=x(()=>{qe();sk=(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 ok(t,e){return J(t.type._def,e)}var nh=x(()=>{qe()});function ik(t,e){let n={type:"array",uniqueItems:!0,items:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&le(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&le(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var sh=x(()=>{hn();qe()});function ak(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 oh=x(()=>{qe()});function ck(t){return{not:Me(t)}}var ih=x(()=>{Gt()});function uk(t){return Me(t)}var ah=x(()=>{Gt()});var lk,ch=x(()=>{qe();lk=(t,e)=>J(t.innerType._def,e)});var dk,uh=x(()=>{Ko();Gt();Df();Mf();jf();Jc();zf();Ff();Uf();Hf();Zf();Bf();qf();Gf();Kf();Jf();Yf();Xf();Qf();eh();th();rh();nh();eu();sh();Xc();oh();ih();tu();ah();ch();dk=(t,e,r)=>{switch(e){case I.ZodString:return Yc(t,r);case I.ZodNumber:return tk(t,r);case I.ZodObject:return rk(t,r);case I.ZodBigInt:return LS(t,r);case I.ZodBoolean:return FS();case I.ZodDate:return Lf(t,r);case I.ZodUndefined:return ck(r);case I.ZodNull:return YS(r);case I.ZodArray:return zS(t,r);case I.ZodUnion:case I.ZodDiscriminatedUnion:return QS(t,r);case I.ZodIntersection:return qS(t,r);case I.ZodTuple:return ak(t,r);case I.ZodRecord:return Qc(t,r);case I.ZodLiteral:return VS(t,r);case I.ZodEnum:return BS(t);case I.ZodNativeEnum:return KS(t);case I.ZodNullable:return ek(t,r);case I.ZodOptional:return nk(t,r);case I.ZodMap:return GS(t,r);case I.ZodSet:return ik(t,r);case I.ZodLazy:return()=>t.getter()._def;case I.ZodPromise:return ok(t,r);case I.ZodNaN:case I.ZodNever:return JS(r);case I.ZodEffects:return ZS(t,r);case I.ZodAny:return Me(r);case I.ZodUnknown:return uk(r);case I.ZodDefault:return HS(t,r);case I.ZodBranded:return Kc(t,r);case I.ZodReadonly:return lk(t,r);case I.ZodCatch:return US(t,r);case I.ZodPipeline:return sk(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!==DS)return a}if(n&&!r){let a=h1(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=dk(t,t.typeName,e),i=typeof o=="function"?J(o(),e):o;if(i&&g1(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var h1,g1,qe=x(()=>{Vc();uh();Gc();Gt();h1=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Wc(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`),Me(e)):e.$refStrategy==="seen"?Me(e):void 0}},g1=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var pk=x(()=>{});var lh,dh=x(()=>{qe();Af();Gt();lh=(t,e)=>{let r=jS(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)??Me(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)??Me(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 mk=x(()=>{Vc();Af();hn();Gc();qe();pk();Gt();Df();Mf();jf();Jc();zf();Ff();Uf();Hf();Zf();Bf();qf();Gf();Kf();Jf();Yf();Xf();Qf();eh();th();rh();nh();ch();eu();sh();Xc();oh();ih();tu();ah();uh();dh();dh()});function y1(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function ph(t,e){return qt(t)?Xm(t,{target:y1(e?.target),io:e?.pipeStrategy??"input"}):lh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function mh(t){let r=pn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ec(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function fh(t,e){let r=dn(t,e);if(!r.success)throw r.error;return r.data}var hh=x(()=>{tf();ci();mk()});function fk(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function hk(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];fk(i)&&fk(o)?r[s]={...i,...o}:r[s]=o}return r}var _1,ru,gk=x(()=>{ci();ds();AS();hh();_1=6e4,ru=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(Ic,r=>{this._oncancel(r)}),this.setNotificationHandler(Nc,r=>{this._onprogress(r)}),this.setRequestHandler(Ac,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Dc,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(jc,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,m=new H(l.error.code,l.error.message,l.error.data);d(m)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new H(V.InvalidParams,`Task not found: ${o}`);if(!fn(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(fn(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[mn]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(zc,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(Fc,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(fn(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),pi(o)||SS(o)?this._onresponse(o):bf(o)?this._onrequest(o,i):xS(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?.[mn]?.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=_S(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,m)=>{if(i.signal.aborted)throw new H(V.ConnectionClosed,"Request was cancelled");let h={...m,relatedRequestId:e.id};o&&!h.relatedTask&&(h.relatedTask={taskId:o});let p=h.relatedTask?.taskId??o;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,h)},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),pi(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(pi(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),pi(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,Ys,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},fn(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=b=>{d(b)};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(b){l(b);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[mn]:c}});let p=b=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(b)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let _=b instanceof H?b:new H(V.RequestTimeout,String(b));d(_)};this._responseHandlers.set(m,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return d(b);try{let _=dn(r,b.result);_.success?u(_.data):d(_.error)}catch(_){d(_)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let f=n?.timeout??_1,g=()=>p(H.fromError(V.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(m,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let b=_=>{let S=this._responseHandlers.get(m);S?S(_):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,b),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(m),d(_)})}else this._transport.send(h,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(m),d(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Mc,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},Lc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},ES,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||{},[mn]: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||{},[mn]: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||{},[mn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=mh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=fh(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=mh(e);this._notificationHandlers.set(n,s=>{let o=fh(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"&&bf(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=yi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),fn(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(fn(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=yi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),fn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var wi=M(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var Si=class{};he._CodeOrName=Si;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ps=class extends Si{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=ps;var Kt=class extends Si{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 ps&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Kt;he.nil=new Kt("");function yk(t,...e){let r=[t[0]],n=0;for(;n<e.length;)yh(r,e[n]),r.push(t[++n]);return new Kt(r)}he._=yk;var gh=new Kt("+");function _k(t,...e){let r=[ki(t[0])],n=0;for(;n<e.length;)r.push(gh),yh(r,e[n]),r.push(gh,ki(t[++n]));return b1(r),new Kt(r)}he.str=_k;function yh(t,e){e instanceof Kt?t.push(...e._items):e instanceof ps?t.push(e):t.push(S1(e))}he.addCodeArg=yh;function b1(t){let e=1;for(;e<t.length-1;){if(t[e]===gh){let r=v1(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function v1(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ps||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 ps))return`"${t}${e.slice(1)}`}function x1(t,e){return e.emptyStr()?t:t.emptyStr()?e:_k`${t}${e}`}he.strConcat=x1;function S1(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ki(Array.isArray(t)?t.join(","):t)}function k1(t){return new Kt(ki(t))}he.stringify=k1;function ki(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=ki;function w1(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Kt(`.${t}`):yk`[${t}]`}he.getProperty=w1;function E1(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=E1;function $1(t){return new Kt(t.toString())}he.regexpCode=$1});var vh=M($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.ValueScope=$t.ValueScopeName=$t.Scope=$t.varKinds=$t.UsedValueState=void 0;var Et=wi(),_h=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},nu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(nu||($t.UsedValueState=nu={}));$t.varKinds={const:new Et.Name("const"),let:new Et.Name("let"),var:new Et.Name("var")};var su=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Et.Name?e:this.name(e)}name(e){return new Et.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}}};$t.Scope=su;var ou=class extends Et.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Et._)`.${new Et.Name(r)}[${n}]`}};$t.ValueScopeName=ou;var T1=(0,Et._)`\n`,bh=class extends su{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?T1:Et.nil}}get(){return this._scope}name(e){return new ou(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,Et._)`${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=Et.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,nu.Started);let d=r(u);if(d){let l=this.opts.es5?$t.varKinds.var:$t.varKinds.const;o=(0,Et._)`${o}${l} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,Et._)`${o}${d}${this.opts._n}`;else throw new _h(u);c.set(u,nu.Completed)})}return o}};$t.ValueScope=bh});var re=M(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 de=wi(),dr=vh(),gn=wi();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return gn._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return gn.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return gn.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return gn.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return gn.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return gn.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return gn.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return gn.Name}});var uu=vh();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return uu.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return uu.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return uu.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return uu.varKinds}});ne.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var Ur=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},xh=class extends Ur{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?dr.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=oo(this.rhs,e,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},iu=class extends Ur{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 de.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=oo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof de.Name?{}:{...this.lhs.names};return cu(e,this.rhs)}},Sh=class extends iu{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},kh=class extends Ur{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},wh=class extends Ur{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Eh=class extends Ur{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},$h=class extends Ur{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=oo(this.code,e,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},Ei=class extends Ur{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)||(P1(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>hs(e,r.names),{})}},Hr=class extends Ei{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Th=class extends Ei{},so=class extends Hr{};so.kind="else";var ms=class t extends Hr{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 so(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(bk(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=oo(this.condition,e,r),this}get names(){let e=super.names;return cu(e,this.condition),this.else&&hs(e,this.else.names),e}};ms.kind="if";var fs=class extends Hr{};fs.kind="for";var Ph=class extends fs{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=oo(this.iteration,e,r),this}get names(){return hs(super.names,this.iteration.names)}},Rh=class extends fs{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?dr.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=cu(super.names,this.from);return cu(e,this.to)}},au=class extends fs{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=oo(this.iterable,e,r),this}get names(){return hs(super.names,this.iterable.names)}},$i=class extends Hr{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)}};$i.kind="func";var Ti=class extends Ei{render(e){return"return "+super.render(e)}};Ti.kind="return";var Ch=class extends Hr{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&&hs(e,this.catch.names),this.finally&&hs(e,this.finally.names),e}},Pi=class extends Hr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Pi.kind="catch";var Ri=class extends Hr{render(e){return"finally"+super.render(e)}};Ri.kind="finally";var Oh=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
65
- `:""},this._extScope=e,this._scope=new dr.Scope({parent:e}),this._nodes=[new Th]}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 xh(e,o,n)),o}const(e,r,n){return this._def(dr.varKinds.const,e,r,n)}let(e,r,n){return this._def(dr.varKinds.let,e,r,n)}var(e,r,n){return this._def(dr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new iu(e,r,n))}add(e,r){return this._leafNode(new Sh(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==de.nil&&this._leafNode(new $h(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,de.addCodeArg)(r,s));return r.push("}"),new de._Code(r)}if(e,r,n){if(this._blockNode(new ms(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 ms(e))}else(){return this._elseNode(new so)}endIf(){return this._endBlockNode(ms,so)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Ph(e),r)}forRange(e,r,n,s,o=this.opts.es5?dr.varKinds.var:dr.varKinds.let){let i=this._scope.toName(e);return this._for(new Rh(o,i,r,n),()=>s(i))}forOf(e,r,n,s=dr.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${i}.length`,a=>{this.var(o,(0,de._)`${i}[${a}]`),n(o)})}return this._for(new au("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?dr.varKinds.var:dr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,de._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new au("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(fs)}label(e){return this._leafNode(new kh(e))}break(e){return this._leafNode(new wh(e))}return(e){let r=new Ti;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Ti)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new Ch;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new Pi(o),r(o)}return n&&(this._currNode=s.finally=new Ri,this.code(n)),this._endBlockNode(Pi,Ri)}throw(e){return this._leafNode(new Eh(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=de.nil,n,s){return this._blockNode(new $i(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode($i)}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 ms))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=Oh;function hs(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function cu(t,e){return e instanceof de._CodeOrName?hs(t,e.names):t}function oo(t,e,r){if(t instanceof de.Name)return n(t);if(!s(t))return t;return new de._Code(t._items.reduce((o,i)=>(i instanceof de.Name&&(i=n(i)),i instanceof de._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 de._Code&&o._items.some(i=>i instanceof de.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function P1(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function bk(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,de._)`!${Ih(t)}`}ne.not=bk;var R1=vk(ne.operators.AND);function C1(...t){return t.reduce(R1)}ne.and=C1;var O1=vk(ne.operators.OR);function I1(...t){return t.reduce(O1)}ne.or=I1;function vk(t){return(e,r)=>e===de.nil?r:r===de.nil?e:(0,de._)`${Ih(e)} ${t} ${Ih(r)}`}function Ih(t){return t instanceof de.Name?t:(0,de._)`(${t})`}});var pe=M(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.checkStrictMode=se.getErrorPath=se.Type=se.useFunc=se.setEvaluated=se.evaluatedPropsToName=se.mergeEvaluated=se.eachItem=se.unescapeJsonPointer=se.escapeJsonPointer=se.escapeFragment=se.unescapeFragment=se.schemaRefOrVal=se.schemaHasRulesButRef=se.schemaHasRules=se.checkUnknownRules=se.alwaysValidSchema=se.toHash=void 0;var Se=re(),A1=wi();function N1(t){let e={};for(let r of t)e[r]=!0;return e}se.toHash=N1;function D1(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(kk(t,e),!wk(e,t.self.RULES.all))}se.alwaysValidSchema=D1;function kk(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]||Tk(t,`unknown keyword: "${o}"`)}se.checkUnknownRules=kk;function wk(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}se.schemaHasRules=wk;function M1(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=M1;function j1({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Se._)`${r}`}return(0,Se._)`${t}${e}${(0,Se.getProperty)(n)}`}se.schemaRefOrVal=j1;function z1(t){return Ek(decodeURIComponent(t))}se.unescapeFragment=z1;function L1(t){return encodeURIComponent(Nh(t))}se.escapeFragment=L1;function Nh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=Nh;function Ek(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=Ek;function F1(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}se.eachItem=F1;function xk({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof Se.Name?(o instanceof Se.Name?t(s,o,i):e(s,o,i),i):o instanceof Se.Name?(e(s,i,o),o):r(o,i);return a===Se.Name&&!(c instanceof Se.Name)?n(s,c):c}}se.mergeEvaluated={props:xk({mergeNames:(t,e,r)=>t.if((0,Se._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Se._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Se._)`${r} || {}`).code((0,Se._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Se._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Se._)`${r} || {}`),Dh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:$k}),items:xk({mergeNames:(t,e,r)=>t.if((0,Se._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Se._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Se._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Se._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function $k(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Se._)`{}`);return e!==void 0&&Dh(t,r,e),r}se.evaluatedPropsToName=$k;function Dh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Se._)`${e}${(0,Se.getProperty)(n)}`,!0))}se.setEvaluated=Dh;var Sk={};function U1(t,e){return t.scopeValue("func",{ref:e,code:Sk[e.code]||(Sk[e.code]=new A1._Code(e.code))})}se.useFunc=U1;var Ah;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Ah||(se.Type=Ah={}));function H1(t,e,r){if(t instanceof Se.Name){let n=e===Ah.Num;return r?n?(0,Se._)`"[" + ${t} + "]"`:(0,Se._)`"['" + ${t} + "']"`:n?(0,Se._)`"/" + ${t}`:(0,Se._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Se.getProperty)(t).toString():"/"+Nh(t)}se.getErrorPath=H1;function Tk(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=Tk});var Zr=M(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var ct=re(),Z1={data:new ct.Name("data"),valCxt:new ct.Name("valCxt"),instancePath:new ct.Name("instancePath"),parentData:new ct.Name("parentData"),parentDataProperty:new ct.Name("parentDataProperty"),rootData:new ct.Name("rootData"),dynamicAnchors:new ct.Name("dynamicAnchors"),vErrors:new ct.Name("vErrors"),errors:new ct.Name("errors"),this:new ct.Name("this"),self:new ct.Name("self"),scope:new ct.Name("scope"),json:new ct.Name("json"),jsonPos:new ct.Name("jsonPos"),jsonLen:new ct.Name("jsonLen"),jsonPart:new ct.Name("jsonPart")};Mh.default=Z1});var Ci=M(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.extendErrors=ut.resetErrorsCount=ut.reportExtraError=ut.reportError=ut.keyword$DataError=ut.keywordError=void 0;var me=re(),lu=pe(),yt=Zr();ut.keywordError={message:({keyword:t})=>(0,me.str)`must pass "${t}" keyword validation`};ut.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,me.str)`"${t}" keyword must be ${e} ($data)`:(0,me.str)`"${t}" keyword is invalid ($data)`};function B1(t,e=ut.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=Ck(t,e,r);n??(i||a)?Pk(o,c):Rk(s,(0,me._)`[${c}]`)}ut.reportError=B1;function q1(t,e=ut.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=Ck(t,e,r);Pk(s,a),o||i||Rk(n,yt.default.vErrors)}ut.reportExtraError=q1;function V1(t,e){t.assign(yt.default.errors,e),t.if((0,me._)`${yt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,me._)`${yt.default.vErrors}.length`,e),()=>t.assign(yt.default.vErrors,null)))}ut.resetErrorsCount=V1;function W1({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,yt.default.errors,a=>{t.const(i,(0,me._)`${yt.default.vErrors}[${a}]`),t.if((0,me._)`${i}.instancePath === undefined`,()=>t.assign((0,me._)`${i}.instancePath`,(0,me.strConcat)(yt.default.instancePath,o.errorPath))),t.assign((0,me._)`${i}.schemaPath`,(0,me.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,me._)`${i}.schema`,r),t.assign((0,me._)`${i}.data`,n))})}ut.extendErrors=W1;function Pk(t,e){let r=t.const("err",e);t.if((0,me._)`${yt.default.vErrors} === null`,()=>t.assign(yt.default.vErrors,(0,me._)`[${r}]`),(0,me._)`${yt.default.vErrors}.push(${r})`),t.code((0,me._)`${yt.default.errors}++`)}function Rk(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,me._)`new ${t.ValidationError}(${e})`):(r.assign((0,me._)`${n}.errors`,e),r.return(!1))}var gs={keyword:new me.Name("keyword"),schemaPath:new me.Name("schemaPath"),params:new me.Name("params"),propertyName:new me.Name("propertyName"),message:new me.Name("message"),schema:new me.Name("schema"),parentSchema:new me.Name("parentSchema")};function Ck(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,me._)`{}`:G1(t,e,r)}function G1(t,e,r={}){let{gen:n,it:s}=t,o=[K1(s,r),J1(t,r)];return Y1(t,e,o),n.object(...o)}function K1({errorPath:t},{instancePath:e}){let r=e?(0,me.str)`${t}${(0,lu.getErrorPath)(e,lu.Type.Str)}`:t;return[yt.default.instancePath,(0,me.strConcat)(yt.default.instancePath,r)]}function J1({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,me.str)`${e}/${t}`;return r&&(s=(0,me.str)`${s}${(0,lu.getErrorPath)(r,lu.Type.Str)}`),[gs.schemaPath,s]}function Y1(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([gs.keyword,s],[gs.params,typeof e=="function"?e(t):e||(0,me._)`{}`]),c.messages&&n.push([gs.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([gs.schema,i],[gs.parentSchema,(0,me._)`${d}${l}`],[yt.default.data,o]),u&&n.push([gs.propertyName,u])}});var Ik=M(io=>{"use strict";Object.defineProperty(io,"__esModule",{value:!0});io.boolOrEmptySchema=io.topBoolOrEmptySchema=void 0;var X1=Ci(),Q1=re(),eD=Zr(),tD={message:"boolean schema is false"};function rD(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Ok(t,!1):typeof r=="object"&&r.$async===!0?e.return(eD.default.data):(e.assign((0,Q1._)`${n}.errors`,null),e.return(!0))}io.topBoolOrEmptySchema=rD;function nD(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Ok(t)):r.var(e,!0)}io.boolOrEmptySchema=nD;function Ok(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,X1.reportError)(s,tD,void 0,e)}});var jh=M(ao=>{"use strict";Object.defineProperty(ao,"__esModule",{value:!0});ao.getRules=ao.isJSONType=void 0;var sD=["string","number","integer","boolean","null","object","array"],oD=new Set(sD);function iD(t){return typeof t=="string"&&oD.has(t)}ao.isJSONType=iD;function aD(){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:{}}}ao.getRules=aD});var zh=M(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.shouldUseRule=yn.shouldUseGroup=yn.schemaHasRulesForType=void 0;function cD({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Ak(t,n)}yn.schemaHasRulesForType=cD;function Ak(t,e){return e.rules.some(r=>Nk(t,r))}yn.shouldUseGroup=Ak;function Nk(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))}yn.shouldUseRule=Nk});var Oi=M(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.reportTypeError=lt.checkDataTypes=lt.checkDataType=lt.coerceAndCheckDataType=lt.getJSONTypes=lt.getSchemaTypes=lt.DataType=void 0;var uD=jh(),lD=zh(),dD=Ci(),ee=re(),Dk=pe(),co;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(co||(lt.DataType=co={}));function pD(t){let e=Mk(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}lt.getSchemaTypes=pD;function Mk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(uD.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}lt.getJSONTypes=Mk;function mD(t,e){let{gen:r,data:n,opts:s}=t,o=fD(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,lD.schemaHasRulesForType)(t,e[0]));if(i){let a=Fh(e,n,s.strictNumbers,co.Wrong);r.if(a,()=>{o.length?hD(t,e,o):Uh(t)})}return i}lt.coerceAndCheckDataType=mD;var jk=new Set(["string","number","integer","boolean","null"]);function fD(t,e){return e?t.filter(r=>jk.has(r)||e==="array"&&r==="array"):[]}function hD(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(Fh(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,ee._)`${a} !== undefined`);for(let u of r)(jk.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),Uh(t),n.endIf(),n.if((0,ee._)`${a} !== undefined`,()=>{n.assign(s,a),gD(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
68
+ ]`;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 Qf,ur,_1,su=x(()=>{yn();ur={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:()=>(Qf===void 0&&(Qf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Qf),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-_]*$/};_1=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function ou(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]})??je(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}=nu(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}=tu(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var iu=x(()=>{Qo();qe();su();ru();Kt()});function ek(t,e){if(e.mapStrategy==="record")return ou(t,e);let r=J(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||je(e),n=J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||je(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var th=x(()=>{qe();iu();Kt()});function tk(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 rh=x(()=>{});function rk(t){return t.target==="openAi"?void 0:{not:je({...t,currentPath:[...t.currentPath,"not"]})}}var nh=x(()=>{Kt()});function nk(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var sh=x(()=>{});function ok(t,e){if(e.target==="openApi3")return sk(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Ei&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=Ei[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 sk(t,e)}var Ei,sk,au=x(()=>{qe();Ei={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};sk=(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 ik(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:Ei[t.innerType._def.typeName],nullable:!0}:{type:[Ei[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 oh=x(()=>{qe();au()});function ak(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",Uf(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?le(r,"minimum",n.value,n.message,e):le(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),le(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?le(r,"maximum",n.value,n.message,e):le(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),le(r,"maximum",n.value,n.message,e));break;case"multipleOf":le(r,"multipleOf",n.value,n.message,e);break}return r}var ih=x(()=>{yn()});function ck(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=x1(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=v1(t,e);return i!==void 0&&(n.additionalProperties=i),n}function v1(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 x1(t){try{return t.isOptional()}catch{return!0}}var ah=x(()=>{qe()});var uk,ch=x(()=>{qe();Kt();uk=(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:je(e)},r]}:je(e)}});var lk,uh=x(()=>{qe();lk=(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 dk(t,e){return J(t.type._def,e)}var lh=x(()=>{qe()});function pk(t,e){let n={type:"array",uniqueItems:!0,items:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&le(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&le(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var dh=x(()=>{yn();qe()});function mk(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 ph=x(()=>{qe()});function fk(t){return{not:je(t)}}var mh=x(()=>{Kt()});function hk(t){return je(t)}var fh=x(()=>{Kt()});var gk,hh=x(()=>{qe();gk=(t,e)=>J(t.innerType._def,e)});var yk,gh=x(()=>{Qo();Kt();Hf();Zf();Bf();ru();qf();Wf();Gf();Kf();Jf();Yf();Xf();th();rh();nh();sh();oh();ih();ah();ch();uh();lh();iu();dh();su();ph();mh();au();fh();hh();yk=(t,e,r)=>{switch(e){case I.ZodString:return nu(t,r);case I.ZodNumber:return ak(t,r);case I.ZodObject:return ck(t,r);case I.ZodBigInt:return qS(t,r);case I.ZodBoolean:return VS();case I.ZodDate:return Vf(t,r);case I.ZodUndefined:return fk(r);case I.ZodNull:return nk(r);case I.ZodArray:return BS(t,r);case I.ZodUnion:case I.ZodDiscriminatedUnion:return ok(t,r);case I.ZodIntersection:return YS(t,r);case I.ZodTuple:return mk(t,r);case I.ZodRecord:return ou(t,r);case I.ZodLiteral:return XS(t,r);case I.ZodEnum:return JS(t);case I.ZodNativeEnum:return tk(t);case I.ZodNullable:return ik(t,r);case I.ZodOptional:return uk(t,r);case I.ZodMap:return ek(t,r);case I.ZodSet:return pk(t,r);case I.ZodLazy:return()=>t.getter()._def;case I.ZodPromise:return dk(t,r);case I.ZodNaN:case I.ZodNever:return rk(r);case I.ZodEffects:return KS(t,r);case I.ZodAny:return je(r);case I.ZodUnknown:return hk(r);case I.ZodDefault:return GS(t,r);case I.ZodBranded:return tu(t,r);case I.ZodReadonly:return gk(t,r);case I.ZodCatch:return WS(t,r);case I.ZodPipeline:return lk(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!==US)return a}if(n&&!r){let a=S1(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=yk(t,t.typeName,e),i=typeof o=="function"?J(o(),e):o;if(i&&k1(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var S1,k1,qe=x(()=>{Xc();gh();eu();Kt();S1=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Qc(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,n)=>e.currentPath[n]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),je(e)):e.$refStrategy==="seen"?je(e):void 0}},k1=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var _k=x(()=>{});var yh,_h=x(()=>{qe();Ff();Kt();yh=(t,e)=>{let r=ZS(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)??je(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)??je(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 bk=x(()=>{Xc();Ff();yn();eu();qe();_k();Kt();Hf();Zf();Bf();ru();qf();Wf();Gf();Kf();Jf();Yf();Xf();th();rh();nh();sh();oh();ih();ah();ch();uh();lh();hh();iu();dh();su();ph();mh();au();fh();gh();_h();_h()});function w1(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function bh(t,e){return Vt(t)?of(t,{target:w1(e?.target),io:e?.pipeStrategy??"input"}):yh(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function vh(t){let r=fn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Oc(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function xh(t,e){let r=mn(t,e);if(!r.success)throw r.error;return r.data}var Sh=x(()=>{uf();pi();bk()});function vk(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function xk(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];vk(i)&&vk(o)?r[s]={...i,...o}:r[s]=o}return r}var E1,cu,Sk=x(()=>{pi();ps();LS();Sh();E1=6e4,cu=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this._taskProgressTokens=new Map,this._requestResolvers=new Map,this.setNotificationHandler(zc,r=>{this._oncancel(r)}),this.setNotificationHandler(Fc,r=>{this._onprogress(r)}),this.setRequestHandler(Lc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Uc,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(Zc,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,m=new H(l.error.code,l.error.message,l.error.data);d(m)}else{let l=a.type==="response"?"Response":"Error";this._onerror(new Error(`${l} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(o,n.sessionId);if(!i)throw new H(V.InvalidParams,`Task not found: ${o}`);if(!gn(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(gn(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[hn]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(Bc,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(Vc,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(gn(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),gi(o)||PS(o)?this._onresponse(o):$f(o)?this._onrequest(o,i):TS(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?.[hn]?.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=wS(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,m)=>{if(i.signal.aborted)throw new H(V.ConnectionClosed,"Request was cancelled");let h={...m,relatedRequestId:e.id};o&&!h.relatedTask&&(h.relatedTask={taskId:o});let p=h.relatedTask?.taskId??o;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,h)},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),gi(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(gi(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),gi(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,Qs,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},gn(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=b=>{d(b)};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(b){l(b);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,h={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),h.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(h.params={...h.params,task:a}),c&&(h.params={...h.params,_meta:{...h.params?._meta||{},[hn]:c}});let p=b=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(b)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let _=b instanceof H?b:new H(V.RequestTimeout,String(b));d(_)};this._responseHandlers.set(m,b=>{if(!n?.signal?.aborted){if(b instanceof Error)return d(b);try{let _=mn(r,b.result);_.success?u(_.data):d(_.error)}catch(_){d(_)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let f=n?.timeout??E1,g=()=>p(H.fromError(V.RequestTimeout,"Request timed out",{timeout:f}));this._setupTimeout(m,f,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let b=_=>{let S=this._responseHandlers.get(m);S?S(_):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,b),this._enqueueTaskMessage(y,{type:"request",message:h,timestamp:Date.now()}).catch(_=>{this._cleanupTimeout(m),d(_)})}else this._transport.send(h,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(b=>{this._cleanupTimeout(m),d(b)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Hc,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},qc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},OS,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||{},[hn]: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||{},[hn]: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||{},[hn]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=vh(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=xh(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=vh(e);this._notificationHandlers.set(n,s=>{let o=xh(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"&&$f(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=xi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),gn(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(gn(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=xi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),gn(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var Pi=M(he=>{"use strict";Object.defineProperty(he,"__esModule",{value:!0});he.regexpCode=he.getEsmExportName=he.getProperty=he.safeStringify=he.stringify=he.strConcat=he.addCodeArg=he.str=he._=he.nil=he._Code=he.Name=he.IDENTIFIER=he._CodeOrName=void 0;var $i=class{};he._CodeOrName=$i;he.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var ms=class extends $i{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=ms;var Jt=class extends $i{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 ms&&(r[n.str]=(r[n.str]||0)+1),r),{})}};he._Code=Jt;he.nil=new Jt("");function kk(t,...e){let r=[t[0]],n=0;for(;n<e.length;)wh(r,e[n]),r.push(t[++n]);return new Jt(r)}he._=kk;var kh=new Jt("+");function wk(t,...e){let r=[Ti(t[0])],n=0;for(;n<e.length;)r.push(kh),wh(r,e[n]),r.push(kh,Ti(t[++n]));return $1(r),new Jt(r)}he.str=wk;function wh(t,e){e instanceof Jt?t.push(...e._items):e instanceof ms?t.push(e):t.push(R1(e))}he.addCodeArg=wh;function $1(t){let e=1;for(;e<t.length-1;){if(t[e]===kh){let r=T1(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function T1(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof ms||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 ms))return`"${t}${e.slice(1)}`}function P1(t,e){return e.emptyStr()?t:t.emptyStr()?e:wk`${t}${e}`}he.strConcat=P1;function R1(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:Ti(Array.isArray(t)?t.join(","):t)}function C1(t){return new Jt(Ti(t))}he.stringify=C1;function Ti(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}he.safeStringify=Ti;function O1(t){return typeof t=="string"&&he.IDENTIFIER.test(t)?new Jt(`.${t}`):kk`[${t}]`}he.getProperty=O1;function I1(t){if(typeof t=="string"&&he.IDENTIFIER.test(t))return new Jt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}he.getEsmExportName=I1;function A1(t){return new Jt(t.toString())}he.regexpCode=A1});var Th=M($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.ValueScope=$t.ValueScopeName=$t.Scope=$t.varKinds=$t.UsedValueState=void 0;var Et=Pi(),Eh=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},uu;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(uu||($t.UsedValueState=uu={}));$t.varKinds={const:new Et.Name("const"),let:new Et.Name("let"),var:new Et.Name("var")};var lu=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof Et.Name?e:this.name(e)}name(e){return new Et.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}}};$t.Scope=lu;var du=class extends Et.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,Et._)`.${new Et.Name(r)}[${n}]`}};$t.ValueScopeName=du;var N1=(0,Et._)`\n`,$h=class extends lu{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?N1:Et.nil}}get(){return this._scope}name(e){return new du(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,Et._)`${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=Et.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,uu.Started);let d=r(u);if(d){let l=this.opts.es5?$t.varKinds.var:$t.varKinds.const;o=(0,Et._)`${o}${l} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,Et._)`${o}${d}${this.opts._n}`;else throw new Eh(u);c.set(u,uu.Completed)})}return o}};$t.ValueScope=$h});var re=M(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 de=Pi(),dr=Th(),_n=Pi();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return _n._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return _n.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return _n.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return _n.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return _n.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return _n.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return _n.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return _n.Name}});var hu=Th();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return hu.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return hu.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return hu.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return hu.varKinds}});ne.operators={GT:new de._Code(">"),GTE:new de._Code(">="),LT:new de._Code("<"),LTE:new de._Code("<="),EQ:new de._Code("==="),NEQ:new de._Code("!=="),NOT:new de._Code("!"),OR:new de._Code("||"),AND:new de._Code("&&"),ADD:new de._Code("+")};var Hr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},Ph=class extends Hr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?dr.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=ao(this.rhs,e,r)),this}get names(){return this.rhs instanceof de._CodeOrName?this.rhs.names:{}}},pu=class extends Hr{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 de.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=ao(this.rhs,e,r),this}get names(){let e=this.lhs instanceof de.Name?{}:{...this.lhs.names};return fu(e,this.rhs)}},Rh=class extends pu{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 Hr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Oh=class extends Hr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Ih=class extends Hr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Ah=class extends Hr{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=ao(this.code,e,r),this}get names(){return this.code instanceof de._CodeOrName?this.code.names:{}}},Ri=class extends Hr{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)||(D1(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>gs(e,r.names),{})}},Zr=class extends Ri{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Nh=class extends Ri{},io=class extends Zr{};io.kind="else";var fs=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 io(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=ao(this.condition,e,r),this}get names(){let e=super.names;return fu(e,this.condition),this.else&&gs(e,this.else.names),e}};fs.kind="if";var hs=class extends Zr{};hs.kind="for";var Dh=class extends hs{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=ao(this.iteration,e,r),this}get names(){return gs(super.names,this.iteration.names)}},Mh=class extends hs{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?dr.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=fu(super.names,this.from);return fu(e,this.to)}},mu=class extends hs{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=ao(this.iterable,e,r),this}get names(){return gs(super.names,this.iterable.names)}},Ci=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)}};Ci.kind="func";var Oi=class extends Ri{render(e){return"return "+super.render(e)}};Oi.kind="return";var jh=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&&gs(e,this.catch.names),this.finally&&gs(e,this.finally.names),e}},Ii=class extends Zr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};Ii.kind="catch";var Ai=class extends Zr{render(e){return"finally"+super.render(e)}};Ai.kind="finally";var zh=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
69
+ `:""},this._extScope=e,this._scope=new dr.Scope({parent:e}),this._nodes=[new Nh]}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 Ph(e,o,n)),o}const(e,r,n){return this._def(dr.varKinds.const,e,r,n)}let(e,r,n){return this._def(dr.varKinds.let,e,r,n)}var(e,r,n){return this._def(dr.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new pu(e,r,n))}add(e,r){return this._leafNode(new Rh(e,ne.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==de.nil&&this._leafNode(new Ah(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,de.addCodeArg)(r,s));return r.push("}"),new de._Code(r)}if(e,r,n){if(this._blockNode(new fs(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 fs(e))}else(){return this._elseNode(new io)}endIf(){return this._endBlockNode(fs,io)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Dh(e),r)}forRange(e,r,n,s,o=this.opts.es5?dr.varKinds.var:dr.varKinds.let){let i=this._scope.toName(e);return this._for(new Mh(o,i,r,n),()=>s(i))}forOf(e,r,n,s=dr.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof de.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,de._)`${i}.length`,a=>{this.var(o,(0,de._)`${i}[${a}]`),n(o)})}return this._for(new mu("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?dr.varKinds.var:dr.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,de._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new mu("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(hs)}label(e){return this._leafNode(new Ch(e))}break(e){return this._leafNode(new Oh(e))}return(e){let r=new Oi;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(Oi)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new jh;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new Ii(o),r(o)}return n&&(this._currNode=s.finally=new Ai,this.code(n)),this._endBlockNode(Ii,Ai)}throw(e){return this._leafNode(new Ih(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=de.nil,n,s){return this._blockNode(new Ci(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(Ci)}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 fs))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=zh;function gs(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function fu(t,e){return e instanceof de._CodeOrName?gs(t,e.names):t}function ao(t,e,r){if(t instanceof de.Name)return n(t);if(!s(t))return t;return new de._Code(t._items.reduce((o,i)=>(i instanceof de.Name&&(i=n(i)),i instanceof de._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 de._Code&&o._items.some(i=>i instanceof de.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function D1(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,de._)`!${Lh(t)}`}ne.not=Ek;var M1=$k(ne.operators.AND);function j1(...t){return t.reduce(M1)}ne.and=j1;var z1=$k(ne.operators.OR);function L1(...t){return t.reduce(z1)}ne.or=L1;function $k(t){return(e,r)=>e===de.nil?r:r===de.nil?e:(0,de._)`${Lh(e)} ${t} ${Lh(r)}`}function Lh(t){return t instanceof de.Name?t:(0,de._)`(${t})`}});var pe=M(se=>{"use strict";Object.defineProperty(se,"__esModule",{value:!0});se.checkStrictMode=se.getErrorPath=se.Type=se.useFunc=se.setEvaluated=se.evaluatedPropsToName=se.mergeEvaluated=se.eachItem=se.unescapeJsonPointer=se.escapeJsonPointer=se.escapeFragment=se.unescapeFragment=se.schemaRefOrVal=se.schemaHasRulesButRef=se.schemaHasRules=se.checkUnknownRules=se.alwaysValidSchema=se.toHash=void 0;var Se=re(),F1=Pi();function U1(t){let e={};for(let r of t)e[r]=!0;return e}se.toHash=U1;function H1(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Rk(t,e),!Ck(e,t.self.RULES.all))}se.alwaysValidSchema=H1;function Rk(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]||Ak(t,`unknown keyword: "${o}"`)}se.checkUnknownRules=Rk;function Ck(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}se.schemaHasRules=Ck;function Z1(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=Z1;function B1({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,Se._)`${r}`}return(0,Se._)`${t}${e}${(0,Se.getProperty)(n)}`}se.schemaRefOrVal=B1;function q1(t){return Ok(decodeURIComponent(t))}se.unescapeFragment=q1;function V1(t){return encodeURIComponent(Uh(t))}se.escapeFragment=V1;function Uh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}se.escapeJsonPointer=Uh;function Ok(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}se.unescapeJsonPointer=Ok;function W1(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}se.eachItem=W1;function Tk({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof Se.Name?(o instanceof Se.Name?t(s,o,i):e(s,o,i),i):o instanceof Se.Name?(e(s,i,o),o):r(o,i);return a===Se.Name&&!(c instanceof Se.Name)?n(s,c):c}}se.mergeEvaluated={props:Tk({mergeNames:(t,e,r)=>t.if((0,Se._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,Se._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,Se._)`${r} || {}`).code((0,Se._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,Se._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,Se._)`${r} || {}`),Hh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:Ik}),items:Tk({mergeNames:(t,e,r)=>t.if((0,Se._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,Se._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,Se._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,Se._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function Ik(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,Se._)`{}`);return e!==void 0&&Hh(t,r,e),r}se.evaluatedPropsToName=Ik;function Hh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,Se._)`${e}${(0,Se.getProperty)(n)}`,!0))}se.setEvaluated=Hh;var Pk={};function G1(t,e){return t.scopeValue("func",{ref:e,code:Pk[e.code]||(Pk[e.code]=new F1._Code(e.code))})}se.useFunc=G1;var Fh;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(Fh||(se.Type=Fh={}));function K1(t,e,r){if(t instanceof Se.Name){let n=e===Fh.Num;return r?n?(0,Se._)`"[" + ${t} + "]"`:(0,Se._)`"['" + ${t} + "']"`:n?(0,Se._)`"/" + ${t}`:(0,Se._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,Se.getProperty)(t).toString():"/"+Uh(t)}se.getErrorPath=K1;function Ak(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=Ak});var Br=M(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var ct=re(),J1={data:new ct.Name("data"),valCxt:new ct.Name("valCxt"),instancePath:new ct.Name("instancePath"),parentData:new ct.Name("parentData"),parentDataProperty:new ct.Name("parentDataProperty"),rootData:new ct.Name("rootData"),dynamicAnchors:new ct.Name("dynamicAnchors"),vErrors:new ct.Name("vErrors"),errors:new ct.Name("errors"),this:new ct.Name("this"),self:new ct.Name("self"),scope:new ct.Name("scope"),json:new ct.Name("json"),jsonPos:new ct.Name("jsonPos"),jsonLen:new ct.Name("jsonLen"),jsonPart:new ct.Name("jsonPart")};Zh.default=J1});var Ni=M(ut=>{"use strict";Object.defineProperty(ut,"__esModule",{value:!0});ut.extendErrors=ut.resetErrorsCount=ut.reportExtraError=ut.reportError=ut.keyword$DataError=ut.keywordError=void 0;var me=re(),gu=pe(),yt=Br();ut.keywordError={message:({keyword:t})=>(0,me.str)`must pass "${t}" keyword validation`};ut.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,me.str)`"${t}" keyword must be ${e} ($data)`:(0,me.str)`"${t}" keyword is invalid ($data)`};function Y1(t,e=ut.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=Mk(t,e,r);n??(i||a)?Nk(o,c):Dk(s,(0,me._)`[${c}]`)}ut.reportError=Y1;function X1(t,e=ut.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=Mk(t,e,r);Nk(s,a),o||i||Dk(n,yt.default.vErrors)}ut.reportExtraError=X1;function Q1(t,e){t.assign(yt.default.errors,e),t.if((0,me._)`${yt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,me._)`${yt.default.vErrors}.length`,e),()=>t.assign(yt.default.vErrors,null)))}ut.resetErrorsCount=Q1;function eD({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,yt.default.errors,a=>{t.const(i,(0,me._)`${yt.default.vErrors}[${a}]`),t.if((0,me._)`${i}.instancePath === undefined`,()=>t.assign((0,me._)`${i}.instancePath`,(0,me.strConcat)(yt.default.instancePath,o.errorPath))),t.assign((0,me._)`${i}.schemaPath`,(0,me.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,me._)`${i}.schema`,r),t.assign((0,me._)`${i}.data`,n))})}ut.extendErrors=eD;function Nk(t,e){let r=t.const("err",e);t.if((0,me._)`${yt.default.vErrors} === null`,()=>t.assign(yt.default.vErrors,(0,me._)`[${r}]`),(0,me._)`${yt.default.vErrors}.push(${r})`),t.code((0,me._)`${yt.default.errors}++`)}function Dk(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,me._)`new ${t.ValidationError}(${e})`):(r.assign((0,me._)`${n}.errors`,e),r.return(!1))}var ys={keyword:new me.Name("keyword"),schemaPath:new me.Name("schemaPath"),params:new me.Name("params"),propertyName:new me.Name("propertyName"),message:new me.Name("message"),schema:new me.Name("schema"),parentSchema:new me.Name("parentSchema")};function Mk(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,me._)`{}`:tD(t,e,r)}function tD(t,e,r={}){let{gen:n,it:s}=t,o=[rD(s,r),nD(t,r)];return sD(t,e,o),n.object(...o)}function rD({errorPath:t},{instancePath:e}){let r=e?(0,me.str)`${t}${(0,gu.getErrorPath)(e,gu.Type.Str)}`:t;return[yt.default.instancePath,(0,me.strConcat)(yt.default.instancePath,r)]}function nD({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,me.str)`${e}/${t}`;return r&&(s=(0,me.str)`${s}${(0,gu.getErrorPath)(r,gu.Type.Str)}`),[ys.schemaPath,s]}function sD(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([ys.keyword,s],[ys.params,typeof e=="function"?e(t):e||(0,me._)`{}`]),c.messages&&n.push([ys.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([ys.schema,i],[ys.parentSchema,(0,me._)`${d}${l}`],[yt.default.data,o]),u&&n.push([ys.propertyName,u])}});var zk=M(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.boolOrEmptySchema=co.topBoolOrEmptySchema=void 0;var oD=Ni(),iD=re(),aD=Br(),cD={message:"boolean schema is false"};function uD(t){let{gen:e,schema:r,validateName:n}=t;r===!1?jk(t,!1):typeof r=="object"&&r.$async===!0?e.return(aD.default.data):(e.assign((0,iD._)`${n}.errors`,null),e.return(!0))}co.topBoolOrEmptySchema=uD;function lD(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),jk(t)):r.var(e,!0)}co.boolOrEmptySchema=lD;function jk(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,oD.reportError)(s,cD,void 0,e)}});var Bh=M(uo=>{"use strict";Object.defineProperty(uo,"__esModule",{value:!0});uo.getRules=uo.isJSONType=void 0;var dD=["string","number","integer","boolean","null","object","array"],pD=new Set(dD);function mD(t){return typeof t=="string"&&pD.has(t)}uo.isJSONType=mD;function fD(){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:{}}}uo.getRules=fD});var qh=M(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.shouldUseRule=bn.shouldUseGroup=bn.schemaHasRulesForType=void 0;function hD({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Lk(t,n)}bn.schemaHasRulesForType=hD;function Lk(t,e){return e.rules.some(r=>Fk(t,r))}bn.shouldUseGroup=Lk;function Fk(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))}bn.shouldUseRule=Fk});var Di=M(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.reportTypeError=lt.checkDataTypes=lt.checkDataType=lt.coerceAndCheckDataType=lt.getJSONTypes=lt.getSchemaTypes=lt.DataType=void 0;var gD=Bh(),yD=qh(),_D=Ni(),ee=re(),Uk=pe(),lo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(lo||(lt.DataType=lo={}));function bD(t){let e=Hk(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}lt.getSchemaTypes=bD;function Hk(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(gD.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}lt.getJSONTypes=Hk;function vD(t,e){let{gen:r,data:n,opts:s}=t,o=xD(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,yD.schemaHasRulesForType)(t,e[0]));if(i){let a=Wh(e,n,s.strictNumbers,lo.Wrong);r.if(a,()=>{o.length?SD(t,e,o):Gh(t)})}return i}lt.coerceAndCheckDataType=vD;var Zk=new Set(["string","number","integer","boolean","null"]);function xD(t,e){return e?t.filter(r=>Zk.has(r)||e==="array"&&r==="array"):[]}function SD(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(Wh(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,ee._)`${a} !== undefined`);for(let u of r)(Zk.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),Gh(t),n.endIf(),n.if((0,ee._)`${a} !== undefined`,()=>{n.assign(s,a),kD(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
70
  || (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,ee._)`+${s}`);return;case"integer":n.elseIf((0,ee._)`${i} === "boolean" || ${s} === null
67
71
  || (${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 gD({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${r}]`,n))}function Lh(t,e,r,n=co.Correct){let s=n===co.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===co.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)}}lt.checkDataType=Lh;function Fh(t,e,r,n){if(t.length===1)return Lh(t[0],e,r,n);let s,o=(0,Dk.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,Lh(i,e,r,n));return s}lt.checkDataTypes=Fh;var yD={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function Uh(t){let e=_D(t);(0,dD.reportError)(e,yD)}lt.reportTypeError=Uh;function _D(t){let{gen:e,data:r,schema:n}=t,s=(0,Dk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var Lk=M(du=>{"use strict";Object.defineProperty(du,"__esModule",{value:!0});du.assignDefaults=void 0;var uo=re(),bD=pe();function vD(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)zk(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>zk(t,o,s.default))}du.assignDefaults=vD;function zk(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,uo._)`${o}${(0,uo.getProperty)(e)}`;if(s){(0,bD.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,uo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,uo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,uo._)`${a} = ${(0,uo.stringify)(r)}`)}});var Jt=M(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 Re=re(),Hh=pe(),_n=Zr(),xD=pe();function SD(t,e){let{gen:r,data:n,it:s}=t;r.if(Bh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Re._)`${e}`},!0),t.error()})}ve.checkReportMissingProp=SD;function kD({gen:t,data:e,it:{opts:r}},n,s){return(0,Re.or)(...n.map(o=>(0,Re.and)(Bh(t,e,o,r.ownProperties),(0,Re._)`${s} = ${o}`)))}ve.checkMissingProp=kD;function wD(t,e){t.setParams({missingProperty:e},!0),t.error()}ve.reportMissingProp=wD;function Fk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Re._)`Object.prototype.hasOwnProperty`})}ve.hasPropFunc=Fk;function Zh(t,e,r){return(0,Re._)`${Fk(t)}.call(${e}, ${r})`}ve.isOwnProperty=Zh;function ED(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} !== undefined`;return n?(0,Re._)`${s} && ${Zh(t,e,r)}`:s}ve.propertyInData=ED;function Bh(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} === undefined`;return n?(0,Re.or)(s,(0,Re.not)(Zh(t,e,r))):s}ve.noPropertyInData=Bh;function Uk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ve.allSchemaProperties=Uk;function $D(t,e){return Uk(e).filter(r=>!(0,Hh.alwaysValidSchema)(t,e[r]))}ve.schemaProperties=$D;function TD({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let d=u?(0,Re._)`${t}, ${e}, ${n}${s}`:e,l=[[_n.default.instancePath,(0,Re.strConcat)(_n.default.instancePath,o)],[_n.default.parentData,i.parentData],[_n.default.parentDataProperty,i.parentDataProperty],[_n.default.rootData,_n.default.rootData]];i.opts.dynamicRef&&l.push([_n.default.dynamicAnchors,_n.default.dynamicAnchors]);let m=(0,Re._)`${d}, ${r.object(...l)}`;return c!==Re.nil?(0,Re._)`${a}.call(${c}, ${m})`:(0,Re._)`${a}(${m})`}ve.callValidateCode=TD;var PD=(0,Re._)`new RegExp`;function RD({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,Re._)`${s.code==="new RegExp"?PD:(0,xD.useFunc)(t,s)}(${r}, ${n})`})}ve.usePattern=RD;function CD(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,Re._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Hh.Type.Num},o),e.if((0,Re.not)(o),a)})}}ve.validateArray=CD;function OD(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,Hh.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,Re._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Re.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ve.validateUnion=OD});var Bk=M(Pr=>{"use strict";Object.defineProperty(Pr,"__esModule",{value:!0});Pr.validateKeywordUsage=Pr.validSchemaType=Pr.funcKeywordCode=Pr.macroKeywordCode=void 0;var _t=re(),ys=Zr(),ID=Jt(),AD=Ci();function ND(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=Zk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:_t.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Pr.macroKeywordCode=ND;function DD(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;jD(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,d=Zk(n,s,u),l=n.let("valid");t.block$data(l,m),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function m(){if(e.errors===!1)f(),e.modifying&&Hk(t),g(()=>t.error());else{let y=e.async?h():p();e.modifying&&Hk(t),g(()=>MD(t,y))}}function h(){let y=n.let("ruleErrs",null);return n.try(()=>f((0,_t._)`await `),b=>n.assign(l,!1).if((0,_t._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,_t._)`${b}.errors`),()=>n.throw(b))),y}function p(){let y=(0,_t._)`${d}.errors`;return n.assign(y,null),f(_t.nil),y}function f(y=e.async?(0,_t._)`await `:_t.nil){let b=c.opts.passContext?ys.default.this:ys.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,_t._)`${y}${(0,ID.callValidateCode)(t,d,b,_)}`,e.modifying)}function g(y){var b;n.if((0,_t.not)((b=e.valid)!==null&&b!==void 0?b:l),y)}}Pr.funcKeywordCode=DD;function Hk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,_t._)`${n.parentData}[${n.parentDataProperty}]`))}function MD(t,e){let{gen:r}=t;r.if((0,_t._)`Array.isArray(${e})`,()=>{r.assign(ys.default.vErrors,(0,_t._)`${ys.default.vErrors} === null ? ${e} : ${ys.default.vErrors}.concat(${e})`).assign(ys.default.errors,(0,_t._)`${ys.default.vErrors}.length`),(0,AD.extendErrors)(t)},()=>t.error())}function jD({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Zk(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,_t.stringify)(r)})}function zD(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")}Pr.validSchemaType=zD;function LD({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)}}Pr.validateKeywordUsage=LD});var Vk=M(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.extendSubschemaMode=bn.extendSubschemaData=bn.getSubschema=void 0;var Rr=re(),qk=pe();function FD(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,Rr._)`${t.schemaPath}${(0,Rr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Rr._)`${t.schemaPath}${(0,Rr.getProperty)(e)}${(0,Rr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,qk.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')}bn.getSubschema=FD;function UD(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,m=a.let("data",(0,Rr._)`${e.data}${(0,Rr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Rr.str)`${u}${(0,qk.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Rr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Rr.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]}}bn.extendSubschemaData=UD;function HD(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}bn.extendSubschemaMode=HD});var qh=M((C6,Wk)=>{"use strict";Wk.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 Kk=M((O6,Gk)=>{"use strict";var vn=Gk.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(){};pu(e,n,s,t,"",t)};vn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};vn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};vn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};vn.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 pu(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 vn.arrayKeywords)for(var m=0;m<l.length;m++)pu(t,e,r,l[m],s+"/"+d+"/"+m,o,s,d,n,m)}else if(d in vn.propsKeywords){if(l&&typeof l=="object")for(var h in l)pu(t,e,r,l[h],s+"/"+d+"/"+ZD(h),o,s,d,n,h)}else(d in vn.keywords||t.allKeys&&!(d in vn.skipKeywords))&&pu(t,e,r,l,s+"/"+d,o,s,d,n)}r(n,s,o,i,a,c,u)}}function ZD(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Ii=M(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getSchemaRefs=Tt.resolveUrl=Tt.normalizeId=Tt._getFullPath=Tt.getFullPath=Tt.inlineRef=void 0;var BD=pe(),qD=qh(),VD=Kk(),WD=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function GD(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Vh(t):e?Jk(t)<=e:!1}Tt.inlineRef=GD;var KD=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Vh(t){for(let e in t){if(KD.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Vh)||typeof r=="object"&&Vh(r))return!0}return!1}function Jk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!WD.has(r)&&(typeof t[r]=="object"&&(0,BD.eachItem)(t[r],n=>e+=Jk(n)),e===1/0))return 1/0}return e}function Yk(t,e="",r){r!==!1&&(e=lo(e));let n=t.parse(e);return Xk(t,n)}Tt.getFullPath=Yk;function Xk(t,e){return t.serialize(e).split("#")[0]+"#"}Tt._getFullPath=Xk;var JD=/#\/?$/;function lo(t){return t?t.replace(JD,""):""}Tt.normalizeId=lo;function YD(t,e,r){return r=lo(r),t.resolve(e,r)}Tt.resolveUrl=YD;var XD=/^[a-z_][-a-z0-9._]*$/i;function QD(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=lo(t[r]||e),o={"":s},i=Yk(n,s,!1),a={},c=new Set;return VD(t,{allKeys:!0},(l,m,h,p)=>{if(p===void 0)return;let f=i+m,g=o[p];typeof l[r]=="string"&&(g=y.call(this,l[r])),b.call(this,l.$anchor),b.call(this,l.$dynamicAnchor),o[m]=g;function y(_){let S=this.opts.uriResolver.resolve;if(_=lo(g?S(g,_):_),c.has(_))throw d(_);c.add(_);let v=this.refs[_];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(l,v.schema,_):_!==lo(f)&&(_[0]==="#"?(u(l,a[_],_),a[_]=l):this.refs[_]=f),_}function b(_){if(typeof _=="string"){if(!XD.test(_))throw new Error(`invalid anchor "${_}"`);y.call(this,`#${_}`)}}}),a;function u(l,m,h){if(m!==void 0&&!qD(l,m))throw d(h)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Tt.getSchemaRefs=QD});var Di=M(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.getData=xn.KeywordCxt=xn.validateFunctionCode=void 0;var n0=Ik(),Qk=Oi(),Gh=zh(),mu=Oi(),eM=Lk(),Ni=Bk(),Wh=Vk(),B=re(),Y=Zr(),tM=Ii(),Br=pe(),Ai=Ci();function rM(t){if(i0(t)&&(a0(t),o0(t))){oM(t);return}s0(t,()=>(0,n0.topBoolOrEmptySchema)(t))}xn.validateFunctionCode=rM;function s0({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"; ${e0(r,s)}`),sM(t,s),t.code(o)}):t.func(e,(0,B._)`${Y.default.data}, ${nM(s)}`,n.$async,()=>t.code(e0(r,s)).code(o))}function nM(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 sM(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 oM(t){let{schema:e,opts:r,gen:n}=t;s0(t,()=>{r.$comment&&e.$comment&&u0(t),lM(t),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&iM(t),c0(t),mM(t)})}function iM(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 e0(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 aM(t,e){if(i0(t)&&(a0(t),o0(t))){cM(t,e);return}(0,n0.boolOrEmptySchema)(t,e)}function o0({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 i0(t){return typeof t.schema!="boolean"}function cM(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&u0(t),dM(t),pM(t);let o=n.const("_errs",Y.default.errors);c0(t,o),n.var(e,(0,B._)`${o} === ${Y.default.errors}`)}function a0(t){(0,Br.checkUnknownRules)(t),uM(t)}function c0(t,e){if(t.opts.jtd)return t0(t,[],!1,e);let r=(0,Qk.getSchemaTypes)(t.schema),n=(0,Qk.coerceAndCheckDataType)(t,r);t0(t,r,!n,e)}function uM(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Br.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function lM(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Br.checkStrictMode)(t,"default is ignored in the schema root")}function dM(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,tM.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function pM(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function u0({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 mM(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&&fM(t),e.return((0,B._)`${Y.default.errors} === 0`))}function fM({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 t0(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,Br.schemaHasRulesButRef)(o,d))){s.block(()=>d0(t,"$ref",d.all.$ref.definition));return}c.jtd||hM(t,e),s.block(()=>{for(let m of d.rules)l(m);l(d.post)});function l(m){(0,Gh.shouldUseGroup)(o,m)&&(m.type?(s.if((0,mu.checkDataType)(m.type,i,c.strictNumbers)),r0(t,m),e.length===1&&e[0]===m.type&&r&&(s.else(),(0,mu.reportTypeError)(t)),s.endIf()):r0(t,m),a||s.if((0,B._)`${Y.default.errors} === ${n||0}`))}}function r0(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,eM.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,Gh.shouldUseRule)(n,o)&&d0(t,o.keyword,o.definition,e.type)})}function hM(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(gM(t,e),t.opts.allowUnionTypes||yM(t,e),_M(t,t.dataTypes))}function gM(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{l0(t.dataTypes,r)||Kh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),vM(t,e)}}function yM(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Kh(t,"use allowUnionTypes to allow union type keyword")}function _M(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,Gh.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>bM(e,i))&&Kh(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function bM(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function l0(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function vM(t,e){let r=[];for(let n of t.dataTypes)l0(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Kh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Br.checkStrictMode)(t,e,t.opts.strictTypes)}var fu=class{constructor(e,r,n){if((0,Ni.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,Br.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",p0(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Ni.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?Ai.reportExtraError:Ai.reportError)(this,this.def.error,r)}$dataError(){(0,Ai.reportError)(this,this.def.$dataError||Ai.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,Ai.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,mu.checkDataTypes)(c,r,o.opts.strictNumbers,mu.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,Wh.getSubschema)(this.it,e);(0,Wh.extendSubschemaData)(n,this.it,e),(0,Wh.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return aM(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Br.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Br.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}};xn.KeywordCxt=fu;function d0(t,e,r,n){let s=new fu(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Ni.funcKeywordCode)(s,r):"macro"in r?(0,Ni.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Ni.funcKeywordCode)(s,r)}var xM=/^\/(?:[^~]|~0|~1)*$/,SM=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function p0(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!xM.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Y.default.rootData}else{let u=SM.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,Br.unescapeJsonPointer)(u))}`,i=(0,B._)`${i} && ${o}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}xn.getData=p0});var hu=M(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});var Jh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Yh.default=Jh});var Mi=M(eg=>{"use strict";Object.defineProperty(eg,"__esModule",{value:!0});var Xh=Ii(),Qh=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Xh.resolveUrl)(e,r,n),this.missingSchema=(0,Xh.normalizeId)((0,Xh.getFullPath)(e,this.missingRef))}};eg.default=Qh});var yu=M(Yt=>{"use strict";Object.defineProperty(Yt,"__esModule",{value:!0});Yt.resolveSchema=Yt.getCompilingSchema=Yt.resolveRef=Yt.compileSchema=Yt.SchemaEnv=void 0;var pr=re(),kM=hu(),_s=Zr(),mr=Ii(),m0=pe(),wM=Di(),po=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,mr.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=po;function rg(t){let e=f0.call(this,t);if(e)return e;let r=(0,mr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new pr.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:kM.default,code:(0,pr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:_s.default.data,parentData:_s.default.parentData,parentDataProperty:_s.default.parentDataProperty,dataNames:[_s.default.data],dataPathArr:[pr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,pr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:pr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,pr._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,wM.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(_s.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let h=new Function(`${_s.default.self}`,`${_s.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:f}=u;h.evaluated={props:p instanceof pr.Name?void 0:p,items:f instanceof pr.Name?void 0:f,dynamicProps:p instanceof pr.Name,dynamicItems:f instanceof pr.Name},h.source&&(h.source.evaluated=(0,pr.stringify)(h.evaluated))}return t.validate=h,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=rg;function EM(t,e,r){var n;r=(0,mr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=PM.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 po({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=$M.call(this,o)}Yt.resolveRef=EM;function $M(t){return(0,mr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:rg.call(this,t)}function f0(t){for(let e of this._compilations)if(TM(e,t))return e}Yt.getCompilingSchema=f0;function TM(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function PM(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||gu.call(this,t,e)}function gu(t,e){let r=this.opts.uriResolver.parse(e),n=(0,mr._getFullPath)(this.opts.uriResolver,r),s=(0,mr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return tg.call(this,r,t);let o=(0,mr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=gu.call(this,t,i);return typeof a?.schema!="object"?void 0:tg.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||rg.call(this,i),o===(0,mr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,mr.resolveUrl)(this.opts.uriResolver,s,u)),new po({schema:a,schemaId:c,root:t,baseId:s})}return tg.call(this,r,i)}}Yt.resolveSchema=gu;var RM=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function tg(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,m0.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!RM.has(a)&&u&&(e=(0,mr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,m0.schemaHasRulesButRef)(r,this.RULES)){let a=(0,mr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=gu.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new po({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var h0=M((j6,CM)=>{CM.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 sg=M((z6,b0)=>{"use strict";var OM=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),y0=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 ng(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 IM=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function g0(t){return t.length=0,!0}function AM(t,e,r){if(t.length){let n=ng(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function NM(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=AM;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=g0}else{s.push(u);continue}}return s.length&&(a===g0?r.zone=s.join(""):i?n.push(s.join("")):n.push(ng(s))),r.address=n.join(""),r}function _0(t){if(DM(t,":")<2)return{host:t,isIPV6:!1};let e=NM(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 DM(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function MM(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 jM(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 zM(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!y0(r)){let n=_0(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}b0.exports={nonSimpleDomain:IM,recomposeAuthority:zM,normalizeComponentEncoding:jM,removeDotSegments:MM,isIPv4:y0,isUUID:OM,normalizeIPv6:_0,stringArrayToHexStripped:ng}});var w0=M((L6,k0)=>{"use strict";var{isUUID:LM}=sg(),FM=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,UM=["http","https","ws","wss","urn","urn:uuid"];function HM(t){return UM.indexOf(t)!==-1}function og(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 v0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function x0(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 ZM(t){return t.secure=og(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function BM(t){if((t.port===(og(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 qM(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(FM);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=ig(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function VM(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=ig(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 WM(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!LM(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function GM(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var S0={scheme:"http",domainHost:!0,parse:v0,serialize:x0},KM={scheme:"https",domainHost:S0.domainHost,parse:v0,serialize:x0},_u={scheme:"ws",domainHost:!0,parse:ZM,serialize:BM},JM={scheme:"wss",domainHost:_u.domainHost,parse:_u.parse,serialize:_u.serialize},YM={scheme:"urn",parse:qM,serialize:VM,skipNormalize:!0},XM={scheme:"urn:uuid",parse:WM,serialize:GM,skipNormalize:!0},bu={http:S0,https:KM,ws:_u,wss:JM,urn:YM,"urn:uuid":XM};Object.setPrototypeOf(bu,null);function ig(t){return t&&(bu[t]||bu[t.toLowerCase()])||void 0}k0.exports={wsIsSecure:og,SCHEMES:bu,isValidSchemeName:HM,getSchemeHandler:ig}});var T0=M((F6,xu)=>{"use strict";var{normalizeIPv6:QM,removeDotSegments:ji,recomposeAuthority:ej,normalizeComponentEncoding:vu,isIPv4:tj,nonSimpleDomain:rj}=sg(),{SCHEMES:nj,getSchemeHandler:E0}=w0();function sj(t,e){return typeof t=="string"?t=Cr(qr(t,e),e):typeof t=="object"&&(t=qr(Cr(t,e),e)),t}function oj(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=$0(qr(t,n),qr(e,n),n,!0);return n.skipEscape=!0,Cr(s,n)}function $0(t,e,r,n){let s={};return n||(t=qr(Cr(t,r),r),e=qr(Cr(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=ji(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=ji(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=ji(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=ji(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 ij(t,e,r){return typeof t=="string"?(t=unescape(t),t=Cr(vu(qr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Cr(vu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Cr(vu(qr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Cr(vu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Cr(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=E0(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=ej(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=ji(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 aj=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function qr(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(aj);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(tj(n.host)===!1){let c=QM(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=E0(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&rj(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 ag={SCHEMES:nj,normalize:sj,resolve:oj,resolveComponent:$0,equal:ij,serialize:Cr,parse:qr};xu.exports=ag;xu.exports.default=ag;xu.exports.fastUri=ag});var R0=M(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});var P0=T0();P0.code='require("ajv/dist/runtime/uri").default';cg.default=P0});var j0=M(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.CodeGen=tt.Name=tt.nil=tt.stringify=tt.str=tt._=tt.KeywordCxt=void 0;var cj=Di();Object.defineProperty(tt,"KeywordCxt",{enumerable:!0,get:function(){return cj.KeywordCxt}});var mo=re();Object.defineProperty(tt,"_",{enumerable:!0,get:function(){return mo._}});Object.defineProperty(tt,"str",{enumerable:!0,get:function(){return mo.str}});Object.defineProperty(tt,"stringify",{enumerable:!0,get:function(){return mo.stringify}});Object.defineProperty(tt,"nil",{enumerable:!0,get:function(){return mo.nil}});Object.defineProperty(tt,"Name",{enumerable:!0,get:function(){return mo.Name}});Object.defineProperty(tt,"CodeGen",{enumerable:!0,get:function(){return mo.CodeGen}});var uj=hu(),N0=Mi(),lj=jh(),zi=yu(),dj=re(),Li=Ii(),Su=Oi(),lg=pe(),C0=h0(),pj=R0(),D0=(t,e)=>new RegExp(t,e);D0.code="new RegExp";var mj=["removeAdditional","useDefaults","coerceTypes"],fj=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),hj={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."},gj={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},O0=200;function yj(t){var e,r,n,s,o,i,a,c,u,d,l,m,h,p,f,g,y,b,_,S,v,R,$,T,D;let P=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:D0,fe=(s=t.uriResolver)!==null&&s!==void 0?s:pj.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:P)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:P)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:P)!==null&&d!==void 0?d:"log",strictTuples:(m=(l=t.strictTuples)!==null&&l!==void 0?l:P)!==null&&m!==void 0?m:"log",strictRequired:(p=(h=t.strictRequired)!==null&&h!==void 0?h:P)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:L,regExp:X}:{optimize:L,regExp:X},loopRequired:(f=t.loopRequired)!==null&&f!==void 0?f:O0,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:O0,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(R=t.validateSchema)!==null&&R!==void 0?R:!0,validateFormats:($=t.validateFormats)!==null&&$!==void 0?$:!0,unicodeRegExp:(T=t.unicodeRegExp)!==null&&T!==void 0?T:!0,int32range:(D=t.int32range)!==null&&D!==void 0?D:!0,uriResolver:fe}}var Fi=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,...yj(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new dj.ValueScope({scope:{},prefixes:fj,es5:r,lines:n}),this.logger=kj(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,lj.getRules)(),I0.call(this,hj,e,"NOT SUPPORTED"),I0.call(this,gj,e,"DEPRECATED","warn"),this._metaOpts=xj.call(this),e.formats&&bj.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&vj.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),_j.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=C0;n==="id"&&(s={...C0},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 m=this._addSchema(d,l);return m.validate||i.call(this,m)}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 N0.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,Li.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=A0.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new zi.SchemaEnv({schema:{},schemaId:n});if(r=zi.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=A0.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,Li.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(Ej.call(this,n,r),!r)return(0,lg.eachItem)(n,o=>ug.call(this,o)),this;Tj.call(this,r);let s={...r,type:(0,Su.getJSONTypes)(r.type),schemaType:(0,Su.getJSONTypes)(r.schemaType)};return(0,lg.eachItem)(n,s.type.length===0?o=>ug.call(this,o,s):o=>s.type.forEach(i=>ug.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]=M0(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,Li.normalizeId)(i||n);let u=Li.getSchemaRefs.call(this,e,n);return c=new zi.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):zi.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{zi.compileSchema.call(this,e)}finally{this.opts=r}}};Fi.ValidationError=uj.default;Fi.MissingRefError=N0.default;tt.default=Fi;function I0(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 A0(t){return t=(0,Li.normalizeId)(t),this.schemas[t]||this.refs[t]}function _j(){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 bj(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function vj(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 xj(){let t={...this.opts};for(let e of mj)delete t[e];return t}var Sj={log(){},warn(){},error(){}};function kj(t){if(t===!1)return Sj;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 wj=/^[a-z_$][a-z0-9_$:-]*$/i;function Ej(t,e){let{RULES:r}=this;if((0,lg.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!wj.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 ug(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,Su.getJSONTypes)(e.type),schemaType:(0,Su.getJSONTypes)(e.schemaType)}};e.before?$j.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 $j(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 Tj(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=M0(e)),t.validateSchema=this.compile(e,!0))}var Pj={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function M0(t){return{anyOf:[t,Pj]}}});var z0=M(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var Rj={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};dg.default=Rj});var H0=M(bs=>{"use strict";Object.defineProperty(bs,"__esModule",{value:!0});bs.callRef=bs.getValidate=void 0;var Cj=Mi(),L0=Jt(),Pt=re(),fo=Zr(),F0=yu(),ku=pe(),Oj={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=F0.resolveRef.call(c,u,s,r);if(d===void 0)throw new Cj.default(n.opts.uriResolver,s,r);if(d instanceof F0.SchemaEnv)return m(d);return h(d);function l(){if(o===u)return wu(t,i,o,o.$async);let p=e.scopeValue("root",{ref:u});return wu(t,(0,Pt._)`${p}.validate`,u,u.$async)}function m(p){let f=U0(t,p);wu(t,f,p,p.$async)}function h(p){let f=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Pt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:Pt.nil,topSchemaRef:f,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function U0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Pt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}bs.getValidate=U0;function wu(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?fo.default.this:Pt.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=s.let("valid");s.try(()=>{s.code((0,Pt._)`await ${(0,L0.callValidateCode)(t,e,u)}`),h(e),i||s.assign(p,!0)},f=>{s.if((0,Pt._)`!(${f} instanceof ${o.ValidationError})`,()=>s.throw(f)),m(f),i||s.assign(p,!1)}),t.ok(p)}function l(){t.result((0,L0.callValidateCode)(t,e,u),()=>h(e),()=>m(e))}function m(p){let f=(0,Pt._)`${p}.errors`;s.assign(fo.default.vErrors,(0,Pt._)`${fo.default.vErrors} === null ? ${f} : ${fo.default.vErrors}.concat(${f})`),s.assign(fo.default.errors,(0,Pt._)`${fo.default.vErrors}.length`)}function h(p){var f;if(!o.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=ku.mergeEvaluated.props(s,g.props,o.props));else{let y=s.var("props",(0,Pt._)`${p}.evaluated.props`);o.props=ku.mergeEvaluated.props(s,y,o.props,Pt.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=ku.mergeEvaluated.items(s,g.items,o.items));else{let y=s.var("items",(0,Pt._)`${p}.evaluated.items`);o.items=ku.mergeEvaluated.items(s,y,o.items,Pt.Name)}}}bs.callRef=wu;bs.default=Oj});var Z0=M(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var Ij=z0(),Aj=H0(),Nj=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Ij.default,Aj.default];pg.default=Nj});var B0=M(mg=>{"use strict";Object.defineProperty(mg,"__esModule",{value:!0});var Eu=re(),Sn=Eu.operators,$u={maximum:{okStr:"<=",ok:Sn.LTE,fail:Sn.GT},minimum:{okStr:">=",ok:Sn.GTE,fail:Sn.LT},exclusiveMaximum:{okStr:"<",ok:Sn.LT,fail:Sn.GTE},exclusiveMinimum:{okStr:">",ok:Sn.GT,fail:Sn.LTE}},Dj={message:({keyword:t,schemaCode:e})=>(0,Eu.str)`must be ${$u[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Eu._)`{comparison: ${$u[t].okStr}, limit: ${e}}`},Mj={keyword:Object.keys($u),type:"number",schemaType:"number",$data:!0,error:Dj,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Eu._)`${r} ${$u[e].fail} ${n} || isNaN(${r})`)}};mg.default=Mj});var q0=M(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Ui=re(),jj={message:({schemaCode:t})=>(0,Ui.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ui._)`{multipleOf: ${t}}`},zj={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:jj,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Ui._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Ui._)`${i} !== parseInt(${i})`;t.fail$data((0,Ui._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};fg.default=zj});var W0=M(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});function V0(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}hg.default=V0;V0.code='require("ajv/dist/runtime/ucs2length").default'});var G0=M(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var vs=re(),Lj=pe(),Fj=W0(),Uj={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,vs.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,vs._)`{limit: ${t}}`},Hj={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Uj,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?vs.operators.GT:vs.operators.LT,i=s.opts.unicode===!1?(0,vs._)`${r}.length`:(0,vs._)`${(0,Lj.useFunc)(t.gen,Fj.default)}(${r})`;t.fail$data((0,vs._)`${i} ${o} ${n}`)}};gg.default=Hj});var K0=M(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var Zj=Jt(),Bj=pe(),ho=re(),qj={message:({schemaCode:t})=>(0,ho.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,ho._)`{pattern: ${t}}`},Vj={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:qj,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,ho._)`new RegExp`:(0,Bj.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,ho._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,ho._)`!${d}`)}else{let c=(0,Zj.usePattern)(t,s);t.fail$data((0,ho._)`!${c}.test(${r})`)}}};yg.default=Vj});var J0=M(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var Hi=re(),Wj={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Hi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Hi._)`{limit: ${t}}`},Gj={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:Wj,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Hi.operators.GT:Hi.operators.LT;t.fail$data((0,Hi._)`Object.keys(${r}).length ${s} ${n}`)}};_g.default=Gj});var Y0=M(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var Zi=Jt(),Bi=re(),Kj=pe(),Jj={message:({params:{missingProperty:t}})=>(0,Bi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Bi._)`{missingProperty: ${t}}`},Yj={keyword:"required",type:"object",schemaType:"array",$data:!0,error:Jj,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 h=t.parentSchema.properties,{definedProperties:p}=t.it;for(let f of r)if(h?.[f]===void 0&&!p.has(f)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,Kj.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Bi.nil,l);else for(let h of r)(0,Zi.checkReportMissingProp)(t,h)}function d(){let h=e.let("missing");if(c||o){let p=e.let("valid",!0);t.block$data(p,()=>m(h,p)),t.ok(p)}else e.if((0,Zi.checkMissingProp)(t,r,h)),(0,Zi.reportMissingProp)(t,h),e.else()}function l(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,Zi.noPropertyInData)(e,s,h,a.ownProperties),()=>t.error())})}function m(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,Zi.propertyInData)(e,s,h,a.ownProperties)),e.if((0,Bi.not)(p),()=>{t.error(),e.break()})},Bi.nil)}}};bg.default=Yj});var X0=M(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var qi=re(),Xj={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,qi.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,qi._)`{limit: ${t}}`},Qj={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:Xj,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?qi.operators.GT:qi.operators.LT;t.fail$data((0,qi._)`${r}.length ${s} ${n}`)}};vg.default=Qj});var Tu=M(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var Q0=qh();Q0.code='require("ajv/dist/runtime/equal").default';xg.default=Q0});var ew=M(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var Sg=Oi(),rt=re(),ez=pe(),tz=Tu(),rz={message:({params:{i:t,j:e}})=>(0,rt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,rt._)`{i: ${t}, j: ${e}}`},nz={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:rz,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,Sg.getSchemaTypes)(o.items):[];t.block$data(c,d,(0,rt._)`${i} === false`),t.ok(c);function d(){let p=e.let("i",(0,rt._)`${r}.length`),f=e.let("j");t.setParams({i:p,j:f}),e.assign(c,!0),e.if((0,rt._)`${p} > 1`,()=>(l()?m:h)(p,f))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,f){let g=e.name("item"),y=(0,Sg.checkDataTypes)(u,g,a.opts.strictNumbers,Sg.DataType.Wrong),b=e.const("indices",(0,rt._)`{}`);e.for((0,rt._)`;${p}--;`,()=>{e.let(g,(0,rt._)`${r}[${p}]`),e.if(y,(0,rt._)`continue`),u.length>1&&e.if((0,rt._)`typeof ${g} == "string"`,(0,rt._)`${g} += "_"`),e.if((0,rt._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(f,(0,rt._)`${b}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,rt._)`${b}[${g}] = ${p}`)})}function h(p,f){let g=(0,ez.useFunc)(e,tz.default),y=e.name("outer");e.label(y).for((0,rt._)`;${p}--;`,()=>e.for((0,rt._)`${f} = ${p}; ${f}--;`,()=>e.if((0,rt._)`${g}(${r}[${p}], ${r}[${f}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};kg.default=nz});var tw=M(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});var wg=re(),sz=pe(),oz=Tu(),iz={message:"must be equal to constant",params:({schemaCode:t})=>(0,wg._)`{allowedValue: ${t}}`},az={keyword:"const",$data:!0,error:iz,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,wg._)`!${(0,sz.useFunc)(e,oz.default)}(${r}, ${s})`):t.fail((0,wg._)`${o} !== ${r}`)}};Eg.default=az});var rw=M($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var Vi=re(),cz=pe(),uz=Tu(),lz={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Vi._)`{allowedValues: ${t}}`},dz={keyword:"enum",schemaType:"array",$data:!0,error:lz,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,cz.useFunc)(e,uz.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 h=e.const("vSchema",o);d=(0,Vi.or)(...s.map((p,f)=>m(h,f)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",o,h=>e.if((0,Vi._)`${u()}(${r}, ${h})`,()=>e.assign(d,!0).break()))}function m(h,p){let f=s[p];return typeof f=="object"&&f!==null?(0,Vi._)`${u()}(${r}, ${h}[${p}])`:(0,Vi._)`${r} === ${f}`}}};$g.default=dz});var nw=M(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var pz=B0(),mz=q0(),fz=G0(),hz=K0(),gz=J0(),yz=Y0(),_z=X0(),bz=ew(),vz=tw(),xz=rw(),Sz=[pz.default,mz.default,fz.default,hz.default,gz.default,yz.default,_z.default,bz.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},vz.default,xz.default];Tg.default=Sz});var Rg=M(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.validateAdditionalItems=void 0;var xs=re(),Pg=pe(),kz={message:({params:{len:t}})=>(0,xs.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,xs._)`{limit: ${t}}`},wz={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:kz,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Pg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}sw(t,n)}};function sw(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,xs._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,xs._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Pg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,xs._)`${a} <= ${e.length}`);r.if((0,xs.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:Pg.Type.Num},u),i.allErrors||r.if((0,xs.not)(u),()=>r.break())})}}Wi.validateAdditionalItems=sw;Wi.default=wz});var Cg=M(Gi=>{"use strict";Object.defineProperty(Gi,"__esModule",{value:!0});Gi.validateTuple=void 0;var ow=re(),Pu=pe(),Ez=Jt(),$z={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return iw(t,"additionalItems",e);r.items=!0,!(0,Pu.alwaysValidSchema)(r,e)&&t.ok((0,Ez.validateArray)(t))}};function iw(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=Pu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,ow._)`${o}.length`);r.forEach((l,m)=>{(0,Pu.alwaysValidSchema)(a,l)||(n.if((0,ow._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function d(l){let{opts:m,errSchemaPath:h}=a,p=r.length,f=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(m.strictTuples&&!f){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,Pu.checkStrictMode)(a,g,m.strictTuples)}}}Gi.validateTuple=iw;Gi.default=$z});var aw=M(Og=>{"use strict";Object.defineProperty(Og,"__esModule",{value:!0});var Tz=Cg(),Pz={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Tz.validateTuple)(t,"items")};Og.default=Pz});var uw=M(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var cw=re(),Rz=pe(),Cz=Jt(),Oz=Rg(),Iz={message:({params:{len:t}})=>(0,cw.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,cw._)`{limit: ${t}}`},Az={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Iz,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Rz.alwaysValidSchema)(n,e)&&(s?(0,Oz.validateAdditionalItems)(t,s):t.ok((0,Cz.validateArray)(t)))}};Ig.default=Az});var lw=M(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});var Xt=re(),Ru=pe(),Nz={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}}`},Dz={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Nz,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,Ru.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Ru.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Ru.alwaysValidSchema)(o,r)){let f=(0,Xt._)`${d} >= ${i}`;a!==void 0&&(f=(0,Xt._)`${f} && ${d} <= ${a}`),t.pass(f);return}o.items=!0;let l=e.name("valid");a===void 0&&i===1?h(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,Xt._)`${s}.length > 0`,m)):(e.let(l,!1),m()),t.result(l,()=>t.reset());function m(){let f=e.name("_valid"),g=e.let("count",0);h(f,()=>e.if(f,()=>p(g)))}function h(f,g){e.forRange("i",0,d,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Ru.Type.Num,compositeRule:!0},f),g()})}function p(f){e.code((0,Xt._)`${f}++`),a===void 0?e.if((0,Xt._)`${f} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,Xt._)`${f} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,Xt._)`${f} >= ${i}`,()=>e.assign(l,!0)))}}};Ag.default=Dz});var mw=M(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.validateSchemaDeps=Or.validatePropertyDeps=Or.error=void 0;var Ng=re(),Mz=pe(),Ki=Jt();Or.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Ng.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Ng._)`{property: ${t},
72
+ || ${i} === "boolean" || ${s} === null`).assign(a,(0,ee._)`[${s}]`)}}}function kD({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,ee._)`${e} !== undefined`,()=>t.assign((0,ee._)`${e}[${r}]`,n))}function Vh(t,e,r,n=lo.Correct){let s=n===lo.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===lo.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)}}lt.checkDataType=Vh;function Wh(t,e,r,n){if(t.length===1)return Vh(t[0],e,r,n);let s,o=(0,Uk.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,Vh(i,e,r,n));return s}lt.checkDataTypes=Wh;var wD={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,ee._)`{type: ${t}}`:(0,ee._)`{type: ${e}}`};function Gh(t){let e=ED(t);(0,_D.reportError)(e,wD)}lt.reportTypeError=Gh;function ED(t){let{gen:e,data:r,schema:n}=t,s=(0,Uk.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var qk=M(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.assignDefaults=void 0;var po=re(),$D=pe();function TD(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)Bk(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>Bk(t,o,s.default))}yu.assignDefaults=TD;function Bk(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,po._)`${o}${(0,po.getProperty)(e)}`;if(s){(0,$D.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,po._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,po._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,po._)`${a} = ${(0,po.stringify)(r)}`)}});var Yt=M(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 Re=re(),Kh=pe(),vn=Br(),PD=pe();function RD(t,e){let{gen:r,data:n,it:s}=t;r.if(Yh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Re._)`${e}`},!0),t.error()})}ve.checkReportMissingProp=RD;function CD({gen:t,data:e,it:{opts:r}},n,s){return(0,Re.or)(...n.map(o=>(0,Re.and)(Yh(t,e,o,r.ownProperties),(0,Re._)`${s} = ${o}`)))}ve.checkMissingProp=CD;function OD(t,e){t.setParams({missingProperty:e},!0),t.error()}ve.reportMissingProp=OD;function Vk(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Re._)`Object.prototype.hasOwnProperty`})}ve.hasPropFunc=Vk;function Jh(t,e,r){return(0,Re._)`${Vk(t)}.call(${e}, ${r})`}ve.isOwnProperty=Jh;function ID(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} !== undefined`;return n?(0,Re._)`${s} && ${Jh(t,e,r)}`:s}ve.propertyInData=ID;function Yh(t,e,r,n){let s=(0,Re._)`${e}${(0,Re.getProperty)(r)} === undefined`;return n?(0,Re.or)(s,(0,Re.not)(Jh(t,e,r))):s}ve.noPropertyInData=Yh;function Wk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}ve.allSchemaProperties=Wk;function AD(t,e){return Wk(e).filter(r=>!(0,Kh.alwaysValidSchema)(t,e[r]))}ve.schemaProperties=AD;function ND({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let d=u?(0,Re._)`${t}, ${e}, ${n}${s}`:e,l=[[vn.default.instancePath,(0,Re.strConcat)(vn.default.instancePath,o)],[vn.default.parentData,i.parentData],[vn.default.parentDataProperty,i.parentDataProperty],[vn.default.rootData,vn.default.rootData]];i.opts.dynamicRef&&l.push([vn.default.dynamicAnchors,vn.default.dynamicAnchors]);let m=(0,Re._)`${d}, ${r.object(...l)}`;return c!==Re.nil?(0,Re._)`${a}.call(${c}, ${m})`:(0,Re._)`${a}(${m})`}ve.callValidateCode=ND;var DD=(0,Re._)`new RegExp`;function MD({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,Re._)`${s.code==="new RegExp"?DD:(0,PD.useFunc)(t,s)}(${r}, ${n})`})}ve.usePattern=MD;function jD(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,Re._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Kh.Type.Num},o),e.if((0,Re.not)(o),a)})}}ve.validateArray=jD;function zD(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,Kh.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,Re._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Re.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}ve.validateUnion=zD});var Jk=M(Rr=>{"use strict";Object.defineProperty(Rr,"__esModule",{value:!0});Rr.validateKeywordUsage=Rr.validSchemaType=Rr.funcKeywordCode=Rr.macroKeywordCode=void 0;var _t=re(),_s=Br(),LD=Yt(),FD=Ni();function UD(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=Kk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:_t.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Rr.macroKeywordCode=UD;function HD(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;BD(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,d=Kk(n,s,u),l=n.let("valid");t.block$data(l,m),t.ok((r=e.valid)!==null&&r!==void 0?r:l);function m(){if(e.errors===!1)f(),e.modifying&&Gk(t),g(()=>t.error());else{let y=e.async?h():p();e.modifying&&Gk(t),g(()=>ZD(t,y))}}function h(){let y=n.let("ruleErrs",null);return n.try(()=>f((0,_t._)`await `),b=>n.assign(l,!1).if((0,_t._)`${b} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,_t._)`${b}.errors`),()=>n.throw(b))),y}function p(){let y=(0,_t._)`${d}.errors`;return n.assign(y,null),f(_t.nil),y}function f(y=e.async?(0,_t._)`await `:_t.nil){let b=c.opts.passContext?_s.default.this:_s.default.self,_=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,_t._)`${y}${(0,LD.callValidateCode)(t,d,b,_)}`,e.modifying)}function g(y){var b;n.if((0,_t.not)((b=e.valid)!==null&&b!==void 0?b:l),y)}}Rr.funcKeywordCode=HD;function Gk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,_t._)`${n.parentData}[${n.parentDataProperty}]`))}function ZD(t,e){let{gen:r}=t;r.if((0,_t._)`Array.isArray(${e})`,()=>{r.assign(_s.default.vErrors,(0,_t._)`${_s.default.vErrors} === null ? ${e} : ${_s.default.vErrors}.concat(${e})`).assign(_s.default.errors,(0,_t._)`${_s.default.vErrors}.length`),(0,FD.extendErrors)(t)},()=>t.error())}function BD({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Kk(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,_t.stringify)(r)})}function qD(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")}Rr.validSchemaType=qD;function VD({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)}}Rr.validateKeywordUsage=VD});var Xk=M(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.extendSubschemaMode=xn.extendSubschemaData=xn.getSubschema=void 0;var Cr=re(),Yk=pe();function WD(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,Cr._)`${t.schemaPath}${(0,Cr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,Cr._)`${t.schemaPath}${(0,Cr.getProperty)(e)}${(0,Cr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,Yk.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')}xn.getSubschema=WD;function GD(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,m=a.let("data",(0,Cr._)`${e.data}${(0,Cr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,Cr.str)`${u}${(0,Yk.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,Cr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof Cr.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]}}xn.extendSubschemaData=GD;function KD(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}xn.extendSubschemaMode=KD});var Xh=M((M6,Qk)=>{"use strict";Qk.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 t0=M((j6,e0)=>{"use strict";var Sn=e0.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(){};_u(e,n,s,t,"",t)};Sn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};Sn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Sn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Sn.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 _u(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 Sn.arrayKeywords)for(var m=0;m<l.length;m++)_u(t,e,r,l[m],s+"/"+d+"/"+m,o,s,d,n,m)}else if(d in Sn.propsKeywords){if(l&&typeof l=="object")for(var h in l)_u(t,e,r,l[h],s+"/"+d+"/"+JD(h),o,s,d,n,h)}else(d in Sn.keywords||t.allKeys&&!(d in Sn.skipKeywords))&&_u(t,e,r,l,s+"/"+d,o,s,d,n)}r(n,s,o,i,a,c,u)}}function JD(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var Mi=M(Tt=>{"use strict";Object.defineProperty(Tt,"__esModule",{value:!0});Tt.getSchemaRefs=Tt.resolveUrl=Tt.normalizeId=Tt._getFullPath=Tt.getFullPath=Tt.inlineRef=void 0;var YD=pe(),XD=Xh(),QD=t0(),eM=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function tM(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Qh(t):e?r0(t)<=e:!1}Tt.inlineRef=tM;var rM=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Qh(t){for(let e in t){if(rM.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Qh)||typeof r=="object"&&Qh(r))return!0}return!1}function r0(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!eM.has(r)&&(typeof t[r]=="object"&&(0,YD.eachItem)(t[r],n=>e+=r0(n)),e===1/0))return 1/0}return e}function n0(t,e="",r){r!==!1&&(e=mo(e));let n=t.parse(e);return s0(t,n)}Tt.getFullPath=n0;function s0(t,e){return t.serialize(e).split("#")[0]+"#"}Tt._getFullPath=s0;var nM=/#\/?$/;function mo(t){return t?t.replace(nM,""):""}Tt.normalizeId=mo;function sM(t,e,r){return r=mo(r),t.resolve(e,r)}Tt.resolveUrl=sM;var oM=/^[a-z_][-a-z0-9._]*$/i;function iM(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=mo(t[r]||e),o={"":s},i=n0(n,s,!1),a={},c=new Set;return QD(t,{allKeys:!0},(l,m,h,p)=>{if(p===void 0)return;let f=i+m,g=o[p];typeof l[r]=="string"&&(g=y.call(this,l[r])),b.call(this,l.$anchor),b.call(this,l.$dynamicAnchor),o[m]=g;function y(_){let S=this.opts.uriResolver.resolve;if(_=mo(g?S(g,_):_),c.has(_))throw d(_);c.add(_);let v=this.refs[_];return typeof v=="string"&&(v=this.refs[v]),typeof v=="object"?u(l,v.schema,_):_!==mo(f)&&(_[0]==="#"?(u(l,a[_],_),a[_]=l):this.refs[_]=f),_}function b(_){if(typeof _=="string"){if(!oM.test(_))throw new Error(`invalid anchor "${_}"`);y.call(this,`#${_}`)}}}),a;function u(l,m,h){if(m!==void 0&&!XD(l,m))throw d(h)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}Tt.getSchemaRefs=iM});var Li=M(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.getData=kn.KeywordCxt=kn.validateFunctionCode=void 0;var u0=zk(),o0=Di(),tg=qh(),bu=Di(),aM=qk(),zi=Jk(),eg=Xk(),B=re(),Y=Br(),cM=Mi(),qr=pe(),ji=Ni();function uM(t){if(p0(t)&&(m0(t),d0(t))){pM(t);return}l0(t,()=>(0,u0.topBoolOrEmptySchema)(t))}kn.validateFunctionCode=uM;function l0({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"; ${i0(r,s)}`),dM(t,s),t.code(o)}):t.func(e,(0,B._)`${Y.default.data}, ${lM(s)}`,n.$async,()=>t.code(i0(r,s)).code(o))}function lM(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 dM(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 pM(t){let{schema:e,opts:r,gen:n}=t;l0(t,()=>{r.$comment&&e.$comment&&h0(t),yM(t),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&mM(t),f0(t),vM(t)})}function mM(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 i0(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 fM(t,e){if(p0(t)&&(m0(t),d0(t))){hM(t,e);return}(0,u0.boolOrEmptySchema)(t,e)}function d0({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 p0(t){return typeof t.schema!="boolean"}function hM(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&h0(t),_M(t),bM(t);let o=n.const("_errs",Y.default.errors);f0(t,o),n.var(e,(0,B._)`${o} === ${Y.default.errors}`)}function m0(t){(0,qr.checkUnknownRules)(t),gM(t)}function f0(t,e){if(t.opts.jtd)return a0(t,[],!1,e);let r=(0,o0.getSchemaTypes)(t.schema),n=(0,o0.coerceAndCheckDataType)(t,r);a0(t,r,!n,e)}function gM(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,qr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function yM(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,qr.checkStrictMode)(t,"default is ignored in the schema root")}function _M(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,cM.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function bM(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function h0({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 vM(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&&xM(t),e.return((0,B._)`${Y.default.errors} === 0`))}function xM({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 a0(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,qr.schemaHasRulesButRef)(o,d))){s.block(()=>y0(t,"$ref",d.all.$ref.definition));return}c.jtd||SM(t,e),s.block(()=>{for(let m of d.rules)l(m);l(d.post)});function l(m){(0,tg.shouldUseGroup)(o,m)&&(m.type?(s.if((0,bu.checkDataType)(m.type,i,c.strictNumbers)),c0(t,m),e.length===1&&e[0]===m.type&&r&&(s.else(),(0,bu.reportTypeError)(t)),s.endIf()):c0(t,m),a||s.if((0,B._)`${Y.default.errors} === ${n||0}`))}}function c0(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,aM.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,tg.shouldUseRule)(n,o)&&y0(t,o.keyword,o.definition,e.type)})}function SM(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(kM(t,e),t.opts.allowUnionTypes||wM(t,e),EM(t,t.dataTypes))}function kM(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{g0(t.dataTypes,r)||rg(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),TM(t,e)}}function wM(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&rg(t,"use allowUnionTypes to allow union type keyword")}function EM(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,tg.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>$M(e,i))&&rg(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function $M(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function g0(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function TM(t,e){let r=[];for(let n of t.dataTypes)g0(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function rg(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,qr.checkStrictMode)(t,e,t.opts.strictTypes)}var vu=class{constructor(e,r,n){if((0,zi.validateKeywordUsage)(e,r,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=r.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,qr.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=r.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=r,this.$data)this.schemaCode=e.gen.const("vSchema",_0(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,zi.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?ji.reportExtraError:ji.reportError)(this,this.def.error,r)}$dataError(){(0,ji.reportError)(this,this.def.$dataError||ji.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,ji.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,bu.checkDataTypes)(c,r,o.opts.strictNumbers,bu.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,eg.getSubschema)(this.it,e);(0,eg.extendSubschemaData)(n,this.it,e),(0,eg.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return fM(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=qr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=qr.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}};kn.KeywordCxt=vu;function y0(t,e,r,n){let s=new vu(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,zi.funcKeywordCode)(s,r):"macro"in r?(0,zi.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,zi.funcKeywordCode)(s,r)}var PM=/^\/(?:[^~]|~0|~1)*$/,RM=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function _0(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!PM.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Y.default.rootData}else{let u=RM.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,qr.unescapeJsonPointer)(u))}`,i=(0,B._)`${i} && ${o}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}kn.getData=_0});var xu=M(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});var ng=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};sg.default=ng});var Fi=M(ag=>{"use strict";Object.defineProperty(ag,"__esModule",{value:!0});var og=Mi(),ig=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,og.resolveUrl)(e,r,n),this.missingSchema=(0,og.normalizeId)((0,og.getFullPath)(e,this.missingRef))}};ag.default=ig});var ku=M(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.resolveSchema=Xt.getCompilingSchema=Xt.resolveRef=Xt.compileSchema=Xt.SchemaEnv=void 0;var pr=re(),CM=xu(),bs=Br(),mr=Mi(),b0=pe(),OM=Li(),fo=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,mr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Xt.SchemaEnv=fo;function ug(t){let e=v0.call(this,t);if(e)return e;let r=(0,mr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new pr.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:CM.default,code:(0,pr._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:bs.default.data,parentData:bs.default.parentData,parentDataProperty:bs.default.parentDataProperty,dataNames:[bs.default.data],dataPathArr:[pr.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,pr.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:pr.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,pr._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,OM.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(bs.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let h=new Function(`${bs.default.self}`,`${bs.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:h}),h.errors=null,h.schema=t.schema,h.schemaEnv=t,t.$async&&(h.$async=!0),this.opts.code.source===!0&&(h.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:f}=u;h.evaluated={props:p instanceof pr.Name?void 0:p,items:f instanceof pr.Name?void 0:f,dynamicProps:p instanceof pr.Name,dynamicItems:f instanceof pr.Name},h.source&&(h.source.evaluated=(0,pr.stringify)(h.evaluated))}return t.validate=h,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)}}Xt.compileSchema=ug;function IM(t,e,r){var n;r=(0,mr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=DM.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 fo({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=AM.call(this,o)}Xt.resolveRef=IM;function AM(t){return(0,mr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:ug.call(this,t)}function v0(t){for(let e of this._compilations)if(NM(e,t))return e}Xt.getCompilingSchema=v0;function NM(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function DM(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Su.call(this,t,e)}function Su(t,e){let r=this.opts.uriResolver.parse(e),n=(0,mr._getFullPath)(this.opts.uriResolver,r),s=(0,mr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return cg.call(this,r,t);let o=(0,mr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Su.call(this,t,i);return typeof a?.schema!="object"?void 0:cg.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||ug.call(this,i),o===(0,mr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,mr.resolveUrl)(this.opts.uriResolver,s,u)),new fo({schema:a,schemaId:c,root:t,baseId:s})}return cg.call(this,r,i)}}Xt.resolveSchema=Su;var MM=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function cg(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,b0.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!MM.has(a)&&u&&(e=(0,mr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,b0.schemaHasRulesButRef)(r,this.RULES)){let a=(0,mr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Su.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new fo({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var x0=M((Z6,jM)=>{jM.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 dg=M((B6,E0)=>{"use strict";var zM=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),k0=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 lg(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 LM=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function S0(t){return t.length=0,!0}function FM(t,e,r){if(t.length){let n=lg(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function UM(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=FM;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=S0}else{s.push(u);continue}}return s.length&&(a===S0?r.zone=s.join(""):i?n.push(s.join("")):n.push(lg(s))),r.address=n.join(""),r}function w0(t){if(HM(t,":")<2)return{host:t,isIPV6:!1};let e=UM(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 HM(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function ZM(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 BM(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 qM(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!k0(r)){let n=w0(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:LM,recomposeAuthority:qM,normalizeComponentEncoding:BM,removeDotSegments:ZM,isIPv4:k0,isUUID:zM,normalizeIPv6:w0,stringArrayToHexStripped:lg}});var C0=M((q6,R0)=>{"use strict";var{isUUID:VM}=dg(),WM=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,GM=["http","https","ws","wss","urn","urn:uuid"];function KM(t){return GM.indexOf(t)!==-1}function pg(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 $0(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function T0(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 JM(t){return t.secure=pg(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function YM(t){if((t.port===(pg(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 XM(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(WM);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=mg(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function QM(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=mg(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 ej(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!VM(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function tj(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var P0={scheme:"http",domainHost:!0,parse:$0,serialize:T0},rj={scheme:"https",domainHost:P0.domainHost,parse:$0,serialize:T0},wu={scheme:"ws",domainHost:!0,parse:JM,serialize:YM},nj={scheme:"wss",domainHost:wu.domainHost,parse:wu.parse,serialize:wu.serialize},sj={scheme:"urn",parse:XM,serialize:QM,skipNormalize:!0},oj={scheme:"urn:uuid",parse:ej,serialize:tj,skipNormalize:!0},Eu={http:P0,https:rj,ws:wu,wss:nj,urn:sj,"urn:uuid":oj};Object.setPrototypeOf(Eu,null);function mg(t){return t&&(Eu[t]||Eu[t.toLowerCase()])||void 0}R0.exports={wsIsSecure:pg,SCHEMES:Eu,isValidSchemeName:KM,getSchemeHandler:mg}});var A0=M((V6,Tu)=>{"use strict";var{normalizeIPv6:ij,removeDotSegments:Ui,recomposeAuthority:aj,normalizeComponentEncoding:$u,isIPv4:cj,nonSimpleDomain:uj}=dg(),{SCHEMES:lj,getSchemeHandler:O0}=C0();function dj(t,e){return typeof t=="string"?t=Or(Vr(t,e),e):typeof t=="object"&&(t=Vr(Or(t,e),e)),t}function pj(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=I0(Vr(t,n),Vr(e,n),n,!0);return n.skipEscape=!0,Or(s,n)}function I0(t,e,r,n){let s={};return n||(t=Vr(Or(t,r),r),e=Vr(Or(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=Ui(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=Ui(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ui(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=Ui(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 mj(t,e,r){return typeof t=="string"?(t=unescape(t),t=Or($u(Vr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=Or($u(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=Or($u(Vr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=Or($u(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function Or(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=O0(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=aj(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=Ui(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 fj=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Vr(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(fj);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(cj(n.host)===!1){let c=ij(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=O0(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&uj(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 fg={SCHEMES:lj,normalize:dj,resolve:pj,resolveComponent:I0,equal:mj,serialize:Or,parse:Vr};Tu.exports=fg;Tu.exports.default=fg;Tu.exports.fastUri=fg});var D0=M(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});var N0=A0();N0.code='require("ajv/dist/runtime/uri").default';hg.default=N0});var Z0=M(tt=>{"use strict";Object.defineProperty(tt,"__esModule",{value:!0});tt.CodeGen=tt.Name=tt.nil=tt.stringify=tt.str=tt._=tt.KeywordCxt=void 0;var hj=Li();Object.defineProperty(tt,"KeywordCxt",{enumerable:!0,get:function(){return hj.KeywordCxt}});var ho=re();Object.defineProperty(tt,"_",{enumerable:!0,get:function(){return ho._}});Object.defineProperty(tt,"str",{enumerable:!0,get:function(){return ho.str}});Object.defineProperty(tt,"stringify",{enumerable:!0,get:function(){return ho.stringify}});Object.defineProperty(tt,"nil",{enumerable:!0,get:function(){return ho.nil}});Object.defineProperty(tt,"Name",{enumerable:!0,get:function(){return ho.Name}});Object.defineProperty(tt,"CodeGen",{enumerable:!0,get:function(){return ho.CodeGen}});var gj=xu(),F0=Fi(),yj=Bh(),Hi=ku(),_j=re(),Zi=Mi(),Pu=Di(),yg=pe(),M0=x0(),bj=D0(),U0=(t,e)=>new RegExp(t,e);U0.code="new RegExp";var vj=["removeAdditional","useDefaults","coerceTypes"],xj=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),Sj={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."},kj={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},j0=200;function wj(t){var e,r,n,s,o,i,a,c,u,d,l,m,h,p,f,g,y,b,_,S,v,P,T,$,D;let R=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:U0,fe=(s=t.uriResolver)!==null&&s!==void 0?s:bj.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:R)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:R)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:R)!==null&&d!==void 0?d:"log",strictTuples:(m=(l=t.strictTuples)!==null&&l!==void 0?l:R)!==null&&m!==void 0?m:"log",strictRequired:(p=(h=t.strictRequired)!==null&&h!==void 0?h:R)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:L,regExp:X}:{optimize:L,regExp:X},loopRequired:(f=t.loopRequired)!==null&&f!==void 0?f:j0,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:j0,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(b=t.messages)!==null&&b!==void 0?b:!0,inlineRefs:(_=t.inlineRefs)!==null&&_!==void 0?_:!0,schemaId:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(v=t.addUsedSchema)!==null&&v!==void 0?v:!0,validateSchema:(P=t.validateSchema)!==null&&P!==void 0?P:!0,validateFormats:(T=t.validateFormats)!==null&&T!==void 0?T:!0,unicodeRegExp:($=t.unicodeRegExp)!==null&&$!==void 0?$:!0,int32range:(D=t.int32range)!==null&&D!==void 0?D:!0,uriResolver:fe}}var Bi=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...wj(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new _j.ValueScope({scope:{},prefixes:xj,es5:r,lines:n}),this.logger=Cj(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,yj.getRules)(),z0.call(this,Sj,e,"NOT SUPPORTED"),z0.call(this,kj,e,"DEPRECATED","warn"),this._metaOpts=Pj.call(this),e.formats&&$j.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&Tj.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),Ej.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=M0;n==="id"&&(s={...M0},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 m=this._addSchema(d,l);return m.validate||i.call(this,m)}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 F0.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,Zi.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=L0.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new Hi.SchemaEnv({schema:{},schemaId:n});if(r=Hi.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=L0.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,Zi.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(Ij.call(this,n,r),!r)return(0,yg.eachItem)(n,o=>gg.call(this,o)),this;Nj.call(this,r);let s={...r,type:(0,Pu.getJSONTypes)(r.type),schemaType:(0,Pu.getJSONTypes)(r.schemaType)};return(0,yg.eachItem)(n,s.type.length===0?o=>gg.call(this,o,s):o=>s.type.forEach(i=>gg.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]=H0(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,Zi.normalizeId)(i||n);let u=Zi.getSchemaRefs.call(this,e,n);return c=new Hi.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):Hi.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{Hi.compileSchema.call(this,e)}finally{this.opts=r}}};Bi.ValidationError=gj.default;Bi.MissingRefError=F0.default;tt.default=Bi;function z0(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 L0(t){return t=(0,Zi.normalizeId)(t),this.schemas[t]||this.refs[t]}function Ej(){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 $j(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function Tj(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 Pj(){let t={...this.opts};for(let e of vj)delete t[e];return t}var Rj={log(){},warn(){},error(){}};function Cj(t){if(t===!1)return Rj;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 Oj=/^[a-z_$][a-z0-9_$:-]*$/i;function Ij(t,e){let{RULES:r}=this;if((0,yg.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!Oj.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 gg(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?Aj.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 Aj(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 Nj(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=H0(e)),t.validateSchema=this.compile(e,!0))}var Dj={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function H0(t){return{anyOf:[t,Dj]}}});var B0=M(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var Mj={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};_g.default=Mj});var G0=M(vs=>{"use strict";Object.defineProperty(vs,"__esModule",{value:!0});vs.callRef=vs.getValidate=void 0;var jj=Fi(),q0=Yt(),Pt=re(),go=Br(),V0=ku(),Ru=pe(),zj={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=V0.resolveRef.call(c,u,s,r);if(d===void 0)throw new jj.default(n.opts.uriResolver,s,r);if(d instanceof V0.SchemaEnv)return m(d);return h(d);function l(){if(o===u)return Cu(t,i,o,o.$async);let p=e.scopeValue("root",{ref:u});return Cu(t,(0,Pt._)`${p}.validate`,u,u.$async)}function m(p){let f=W0(t,p);Cu(t,f,p,p.$async)}function h(p){let f=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Pt.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:Pt.nil,topSchemaRef:f,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function W0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Pt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}vs.getValidate=W0;function Cu(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?go.default.this:Pt.nil;n?d():l();function d(){if(!a.$async)throw new Error("async schema referenced by sync schema");let p=s.let("valid");s.try(()=>{s.code((0,Pt._)`await ${(0,q0.callValidateCode)(t,e,u)}`),h(e),i||s.assign(p,!0)},f=>{s.if((0,Pt._)`!(${f} instanceof ${o.ValidationError})`,()=>s.throw(f)),m(f),i||s.assign(p,!1)}),t.ok(p)}function l(){t.result((0,q0.callValidateCode)(t,e,u),()=>h(e),()=>m(e))}function m(p){let f=(0,Pt._)`${p}.errors`;s.assign(go.default.vErrors,(0,Pt._)`${go.default.vErrors} === null ? ${f} : ${go.default.vErrors}.concat(${f})`),s.assign(go.default.errors,(0,Pt._)`${go.default.vErrors}.length`)}function h(p){var f;if(!o.opts.unevaluated)return;let g=(f=r?.validate)===null||f===void 0?void 0:f.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=Ru.mergeEvaluated.props(s,g.props,o.props));else{let y=s.var("props",(0,Pt._)`${p}.evaluated.props`);o.props=Ru.mergeEvaluated.props(s,y,o.props,Pt.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=Ru.mergeEvaluated.items(s,g.items,o.items));else{let y=s.var("items",(0,Pt._)`${p}.evaluated.items`);o.items=Ru.mergeEvaluated.items(s,y,o.items,Pt.Name)}}}vs.callRef=Cu;vs.default=zj});var K0=M(bg=>{"use strict";Object.defineProperty(bg,"__esModule",{value:!0});var Lj=B0(),Fj=G0(),Uj=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",Lj.default,Fj.default];bg.default=Uj});var J0=M(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var Ou=re(),wn=Ou.operators,Iu={maximum:{okStr:"<=",ok:wn.LTE,fail:wn.GT},minimum:{okStr:">=",ok:wn.GTE,fail:wn.LT},exclusiveMaximum:{okStr:"<",ok:wn.LT,fail:wn.GTE},exclusiveMinimum:{okStr:">",ok:wn.GT,fail:wn.LTE}},Hj={message:({keyword:t,schemaCode:e})=>(0,Ou.str)`must be ${Iu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Ou._)`{comparison: ${Iu[t].okStr}, limit: ${e}}`},Zj={keyword:Object.keys(Iu),type:"number",schemaType:"number",$data:!0,error:Hj,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Ou._)`${r} ${Iu[e].fail} ${n} || isNaN(${r})`)}};vg.default=Zj});var Y0=M(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var qi=re(),Bj={message:({schemaCode:t})=>(0,qi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,qi._)`{multipleOf: ${t}}`},qj={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:Bj,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,qi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,qi._)`${i} !== parseInt(${i})`;t.fail$data((0,qi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};xg.default=qj});var Q0=M(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});function X0(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}Sg.default=X0;X0.code='require("ajv/dist/runtime/ucs2length").default'});var ew=M(kg=>{"use strict";Object.defineProperty(kg,"__esModule",{value:!0});var xs=re(),Vj=pe(),Wj=Q0(),Gj={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,xs.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,xs._)`{limit: ${t}}`},Kj={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:Gj,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?xs.operators.GT:xs.operators.LT,i=s.opts.unicode===!1?(0,xs._)`${r}.length`:(0,xs._)`${(0,Vj.useFunc)(t.gen,Wj.default)}(${r})`;t.fail$data((0,xs._)`${i} ${o} ${n}`)}};kg.default=Kj});var tw=M(wg=>{"use strict";Object.defineProperty(wg,"__esModule",{value:!0});var Jj=Yt(),Yj=pe(),yo=re(),Xj={message:({schemaCode:t})=>(0,yo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,yo._)`{pattern: ${t}}`},Qj={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:Xj,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,yo._)`new RegExp`:(0,Yj.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,yo._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,yo._)`!${d}`)}else{let c=(0,Jj.usePattern)(t,s);t.fail$data((0,yo._)`!${c}.test(${r})`)}}};wg.default=Qj});var rw=M(Eg=>{"use strict";Object.defineProperty(Eg,"__esModule",{value:!0});var Vi=re(),ez={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Vi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Vi._)`{limit: ${t}}`},tz={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:ez,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Vi.operators.GT:Vi.operators.LT;t.fail$data((0,Vi._)`Object.keys(${r}).length ${s} ${n}`)}};Eg.default=tz});var nw=M($g=>{"use strict";Object.defineProperty($g,"__esModule",{value:!0});var Wi=Yt(),Gi=re(),rz=pe(),nz={message:({params:{missingProperty:t}})=>(0,Gi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Gi._)`{missingProperty: ${t}}`},sz={keyword:"required",type:"object",schemaType:"array",$data:!0,error:nz,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 h=t.parentSchema.properties,{definedProperties:p}=t.it;for(let f of r)if(h?.[f]===void 0&&!p.has(f)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${f}" is not defined at "${g}" (strictRequired)`;(0,rz.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Gi.nil,l);else for(let h of r)(0,Wi.checkReportMissingProp)(t,h)}function d(){let h=e.let("missing");if(c||o){let p=e.let("valid",!0);t.block$data(p,()=>m(h,p)),t.ok(p)}else e.if((0,Wi.checkMissingProp)(t,r,h)),(0,Wi.reportMissingProp)(t,h),e.else()}function l(){e.forOf("prop",n,h=>{t.setParams({missingProperty:h}),e.if((0,Wi.noPropertyInData)(e,s,h,a.ownProperties),()=>t.error())})}function m(h,p){t.setParams({missingProperty:h}),e.forOf(h,n,()=>{e.assign(p,(0,Wi.propertyInData)(e,s,h,a.ownProperties)),e.if((0,Gi.not)(p),()=>{t.error(),e.break()})},Gi.nil)}}};$g.default=sz});var sw=M(Tg=>{"use strict";Object.defineProperty(Tg,"__esModule",{value:!0});var Ki=re(),oz={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ki.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ki._)`{limit: ${t}}`},iz={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:oz,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Ki.operators.GT:Ki.operators.LT;t.fail$data((0,Ki._)`${r}.length ${s} ${n}`)}};Tg.default=iz});var Au=M(Pg=>{"use strict";Object.defineProperty(Pg,"__esModule",{value:!0});var ow=Xh();ow.code='require("ajv/dist/runtime/equal").default';Pg.default=ow});var iw=M(Cg=>{"use strict";Object.defineProperty(Cg,"__esModule",{value:!0});var Rg=Di(),rt=re(),az=pe(),cz=Au(),uz={message:({params:{i:t,j:e}})=>(0,rt.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,rt._)`{i: ${t}, j: ${e}}`},lz={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:uz,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,Rg.getSchemaTypes)(o.items):[];t.block$data(c,d,(0,rt._)`${i} === false`),t.ok(c);function d(){let p=e.let("i",(0,rt._)`${r}.length`),f=e.let("j");t.setParams({i:p,j:f}),e.assign(c,!0),e.if((0,rt._)`${p} > 1`,()=>(l()?m:h)(p,f))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,f){let g=e.name("item"),y=(0,Rg.checkDataTypes)(u,g,a.opts.strictNumbers,Rg.DataType.Wrong),b=e.const("indices",(0,rt._)`{}`);e.for((0,rt._)`;${p}--;`,()=>{e.let(g,(0,rt._)`${r}[${p}]`),e.if(y,(0,rt._)`continue`),u.length>1&&e.if((0,rt._)`typeof ${g} == "string"`,(0,rt._)`${g} += "_"`),e.if((0,rt._)`typeof ${b}[${g}] == "number"`,()=>{e.assign(f,(0,rt._)`${b}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,rt._)`${b}[${g}] = ${p}`)})}function h(p,f){let g=(0,az.useFunc)(e,cz.default),y=e.name("outer");e.label(y).for((0,rt._)`;${p}--;`,()=>e.for((0,rt._)`${f} = ${p}; ${f}--;`,()=>e.if((0,rt._)`${g}(${r}[${p}], ${r}[${f}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Cg.default=lz});var aw=M(Ig=>{"use strict";Object.defineProperty(Ig,"__esModule",{value:!0});var Og=re(),dz=pe(),pz=Au(),mz={message:"must be equal to constant",params:({schemaCode:t})=>(0,Og._)`{allowedValue: ${t}}`},fz={keyword:"const",$data:!0,error:mz,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Og._)`!${(0,dz.useFunc)(e,pz.default)}(${r}, ${s})`):t.fail((0,Og._)`${o} !== ${r}`)}};Ig.default=fz});var cw=M(Ag=>{"use strict";Object.defineProperty(Ag,"__esModule",{value:!0});var Ji=re(),hz=pe(),gz=Au(),yz={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ji._)`{allowedValues: ${t}}`},_z={keyword:"enum",schemaType:"array",$data:!0,error:yz,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,hz.useFunc)(e,gz.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 h=e.const("vSchema",o);d=(0,Ji.or)(...s.map((p,f)=>m(h,f)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",o,h=>e.if((0,Ji._)`${u()}(${r}, ${h})`,()=>e.assign(d,!0).break()))}function m(h,p){let f=s[p];return typeof f=="object"&&f!==null?(0,Ji._)`${u()}(${r}, ${h}[${p}])`:(0,Ji._)`${r} === ${f}`}}};Ag.default=_z});var uw=M(Ng=>{"use strict";Object.defineProperty(Ng,"__esModule",{value:!0});var bz=J0(),vz=Y0(),xz=ew(),Sz=tw(),kz=rw(),wz=nw(),Ez=sw(),$z=iw(),Tz=aw(),Pz=cw(),Rz=[bz.default,vz.default,xz.default,Sz.default,kz.default,wz.default,Ez.default,$z.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},Tz.default,Pz.default];Ng.default=Rz});var Mg=M(Yi=>{"use strict";Object.defineProperty(Yi,"__esModule",{value:!0});Yi.validateAdditionalItems=void 0;var Ss=re(),Dg=pe(),Cz={message:({params:{len:t}})=>(0,Ss.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Ss._)`{limit: ${t}}`},Oz={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:Cz,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Dg.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}lw(t,n)}};function lw(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,Ss._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Ss._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Dg.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Ss._)`${a} <= ${e.length}`);r.if((0,Ss.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:Dg.Type.Num},u),i.allErrors||r.if((0,Ss.not)(u),()=>r.break())})}}Yi.validateAdditionalItems=lw;Yi.default=Oz});var jg=M(Xi=>{"use strict";Object.defineProperty(Xi,"__esModule",{value:!0});Xi.validateTuple=void 0;var dw=re(),Nu=pe(),Iz=Yt(),Az={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return pw(t,"additionalItems",e);r.items=!0,!(0,Nu.alwaysValidSchema)(r,e)&&t.ok((0,Iz.validateArray)(t))}};function pw(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=Nu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,dw._)`${o}.length`);r.forEach((l,m)=>{(0,Nu.alwaysValidSchema)(a,l)||(n.if((0,dw._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function d(l){let{opts:m,errSchemaPath:h}=a,p=r.length,f=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(m.strictTuples&&!f){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${h}"`;(0,Nu.checkStrictMode)(a,g,m.strictTuples)}}}Xi.validateTuple=pw;Xi.default=Az});var mw=M(zg=>{"use strict";Object.defineProperty(zg,"__esModule",{value:!0});var Nz=jg(),Dz={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,Nz.validateTuple)(t,"items")};zg.default=Dz});var hw=M(Lg=>{"use strict";Object.defineProperty(Lg,"__esModule",{value:!0});var fw=re(),Mz=pe(),jz=Yt(),zz=Mg(),Lz={message:({params:{len:t}})=>(0,fw.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,fw._)`{limit: ${t}}`},Fz={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:Lz,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,Mz.alwaysValidSchema)(n,e)&&(s?(0,zz.validateAdditionalItems)(t,s):t.ok((0,jz.validateArray)(t)))}};Lg.default=Fz});var gw=M(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var Qt=re(),Du=pe(),Uz={message:({params:{min:t,max:e}})=>e===void 0?(0,Qt.str)`must contain at least ${t} valid item(s)`:(0,Qt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Qt._)`{minContains: ${t}}`:(0,Qt._)`{minContains: ${t}, maxContains: ${e}}`},Hz={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:Uz,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,Qt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,Du.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,Du.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,Du.alwaysValidSchema)(o,r)){let f=(0,Qt._)`${d} >= ${i}`;a!==void 0&&(f=(0,Qt._)`${f} && ${d} <= ${a}`),t.pass(f);return}o.items=!0;let l=e.name("valid");a===void 0&&i===1?h(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,Qt._)`${s}.length > 0`,m)):(e.let(l,!1),m()),t.result(l,()=>t.reset());function m(){let f=e.name("_valid"),g=e.let("count",0);h(f,()=>e.if(f,()=>p(g)))}function h(f,g){e.forRange("i",0,d,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:Du.Type.Num,compositeRule:!0},f),g()})}function p(f){e.code((0,Qt._)`${f}++`),a===void 0?e.if((0,Qt._)`${f} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,Qt._)`${f} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,Qt._)`${f} >= ${i}`,()=>e.assign(l,!0)))}}};Fg.default=Hz});var bw=M(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.validateSchemaDeps=Ir.validatePropertyDeps=Ir.error=void 0;var Ug=re(),Zz=pe(),Qi=Yt();Ir.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,Ug.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,Ug._)`{property: ${t},
69
73
  missingProperty: ${n},
70
74
  depsCount: ${e},
71
- deps: ${r}}`};var jz={keyword:"dependencies",type:"object",schemaType:"object",error:Or.error,code(t){let[e,r]=zz(t);dw(t,e),pw(t,r)}};function zz({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 dw(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,Ki.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,Ki.checkReportMissingProp)(t,u)}):(r.if((0,Ng._)`${c} && (${(0,Ki.checkMissingProp)(t,a,o)})`),(0,Ki.reportMissingProp)(t,o),r.else())}}Or.validatePropertyDeps=dw;function pw(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,Mz.alwaysValidSchema)(o,e[a])||(r.if((0,Ki.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))}Or.validateSchemaDeps=pw;Or.default=jz});var hw=M(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});var fw=re(),Lz=pe(),Fz={message:"property name must be valid",params:({params:t})=>(0,fw._)`{propertyName: ${t.propertyName}}`},Uz={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Fz,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Lz.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,fw.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Dg.default=Uz});var jg=M(Mg=>{"use strict";Object.defineProperty(Mg,"__esModule",{value:!0});var Cu=Jt(),fr=re(),Hz=Zr(),Ou=pe(),Zz={message:"must NOT have additional properties",params:({params:t})=>(0,fr._)`{additionalProperty: ${t.additionalProperty}}`},Bz={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Zz,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,Ou.alwaysValidSchema)(i,r))return;let u=(0,Cu.allSchemaProperties)(n.properties),d=(0,Cu.allSchemaProperties)(n.patternProperties);l(),t.ok((0,fr._)`${o} === ${Hz.default.errors}`);function l(){e.forIn("key",s,g=>{!u.length&&!d.length?p(g):e.if(m(g),()=>p(g))})}function m(g){let y;if(u.length>8){let b=(0,Ou.schemaRefOrVal)(i,n.properties,"properties");y=(0,Cu.isOwnProperty)(e,b,g)}else u.length?y=(0,fr.or)(...u.map(b=>(0,fr._)`${g} === ${b}`)):y=fr.nil;return d.length&&(y=(0,fr.or)(y,...d.map(b=>(0,fr._)`${(0,Cu.usePattern)(t,b)}.test(${g})`))),(0,fr.not)(y)}function h(g){e.code((0,fr._)`delete ${s}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Ou.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(f(g,y,!1),e.if((0,fr.not)(y),()=>{t.reset(),h(g)})):(f(g,y),a||e.if((0,fr.not)(y),()=>e.break()))}}function f(g,y,b){let _={keyword:"additionalProperties",dataProp:g,dataPropType:Ou.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,y)}}};Mg.default=Bz});var _w=M(Lg=>{"use strict";Object.defineProperty(Lg,"__esModule",{value:!0});var qz=Di(),gw=Jt(),zg=pe(),yw=jg(),Vz={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&&yw.default.code(new qz.KeywordCxt(o,yw.default,"additionalProperties"));let i=(0,gw.allSchemaProperties)(r);for(let l of i)o.definedProperties.add(l);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=zg.mergeEvaluated.props(e,(0,zg.toHash)(i),o.props));let a=i.filter(l=>!(0,zg.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,gw.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)}}};Lg.default=Vz});var Sw=M(Fg=>{"use strict";Object.defineProperty(Fg,"__esModule",{value:!0});var bw=Jt(),Iu=re(),vw=pe(),xw=pe(),Wz={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,bw.allSchemaProperties)(r),c=a.filter(f=>(0,vw.alwaysValidSchema)(o,r[f]));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 Iu.Name)&&(o.props=(0,xw.evaluatedPropsToName)(e,o.props));let{props:l}=o;m();function m(){for(let f of a)u&&h(f),o.allErrors?p(f):(e.var(d,!0),p(f),e.if(d))}function h(f){for(let g in u)new RegExp(f).test(g)&&(0,vw.checkStrictMode)(o,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function p(f){e.forIn("key",n,g=>{e.if((0,Iu._)`${(0,bw.usePattern)(t,f)}.test(${g})`,()=>{let y=c.includes(f);y||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:xw.Type.Str},d),o.opts.unevaluated&&l!==!0?e.assign((0,Iu._)`${l}[${g}]`,!0):!y&&!o.allErrors&&e.if((0,Iu.not)(d),()=>e.break())})})}}};Fg.default=Wz});var kw=M(Ug=>{"use strict";Object.defineProperty(Ug,"__esModule",{value:!0});var Gz=pe(),Kz={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Gz.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"}};Ug.default=Kz});var ww=M(Hg=>{"use strict";Object.defineProperty(Hg,"__esModule",{value:!0});var Jz=Jt(),Yz={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Jz.validateUnion,error:{message:"must match a schema in anyOf"}};Hg.default=Yz});var Ew=M(Zg=>{"use strict";Object.defineProperty(Zg,"__esModule",{value:!0});var Au=re(),Xz=pe(),Qz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Au._)`{passingSchemas: ${t.passing}}`},eL={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Qz,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 m;(0,Xz.alwaysValidSchema)(s,d)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,Au._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Au._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),m&&t.mergeEvaluated(m,Au.Name)})})}}};Zg.default=eL});var $w=M(Bg=>{"use strict";Object.defineProperty(Bg,"__esModule",{value:!0});var tL=pe(),rL={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,tL.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Bg.default=rL});var Rw=M(qg=>{"use strict";Object.defineProperty(qg,"__esModule",{value:!0});var Nu=re(),Pw=pe(),nL={message:({params:t})=>(0,Nu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Nu._)`{failingKeyword: ${t.ifClause}}`},sL={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:nL,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Pw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Tw(n,"then"),o=Tw(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,Nu.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let m=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(m,i),l?e.assign(l,(0,Nu._)`${d}`):t.setParams({ifClause:d})}}}};function Tw(t,e){let r=t.schema[e];return r!==void 0&&!(0,Pw.alwaysValidSchema)(t,r)}qg.default=sL});var Cw=M(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});var oL=pe(),iL={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,oL.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Vg.default=iL});var Ow=M(Wg=>{"use strict";Object.defineProperty(Wg,"__esModule",{value:!0});var aL=Rg(),cL=aw(),uL=Cg(),lL=uw(),dL=lw(),pL=mw(),mL=hw(),fL=jg(),hL=_w(),gL=Sw(),yL=kw(),_L=ww(),bL=Ew(),vL=$w(),xL=Rw(),SL=Cw();function kL(t=!1){let e=[yL.default,_L.default,bL.default,vL.default,xL.default,SL.default,mL.default,fL.default,pL.default,hL.default,gL.default];return t?e.push(cL.default,lL.default):e.push(aL.default,uL.default),e.push(dL.default),e}Wg.default=kL});var Iw=M(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});var Ze=re(),wL={message:({schemaCode:t})=>(0,Ze.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ze._)`{format: ${t}}`},EL={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:wL,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?m():h();function m(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),f=r.const("fDef",(0,Ze._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ze._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,Ze._)`${f}.type || "string"`).assign(y,(0,Ze._)`${f}.validate`),()=>r.assign(g,(0,Ze._)`"string"`).assign(y,f)),t.fail$data((0,Ze.or)(b(),_()));function b(){return c.strictSchema===!1?Ze.nil:(0,Ze._)`${i} && !${y}`}function _(){let S=d.$async?(0,Ze._)`(${f}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ze._)`${y}(${n})`,v=(0,Ze._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${n}))`;return(0,Ze._)`${y} && ${y} !== true && ${g} === ${e} && !${v}`}}function h(){let p=l.formats[o];if(!p){b();return}if(p===!0)return;let[f,g,y]=_(p);f===e&&t.pass(S());function b(){if(c.strictSchema===!1){l.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function _(v){let R=v instanceof RegExp?(0,Ze.regexpCode)(v):c.code.formats?(0,Ze._)`${c.code.formats}${(0,Ze.getProperty)(o)}`:void 0,$=r.scopeValue("formats",{key:o,ref:v,code:R});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Ze._)`${$}.validate`]:["string",v,$]}function S(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ze._)`await ${y}(${n})`}return typeof g=="function"?(0,Ze._)`${y}(${n})`:(0,Ze._)`${y}.test(${n})`}}}};Gg.default=EL});var Aw=M(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var $L=Iw(),TL=[$L.default];Kg.default=TL});var Nw=M(go=>{"use strict";Object.defineProperty(go,"__esModule",{value:!0});go.contentVocabulary=go.metadataVocabulary=void 0;go.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];go.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Mw=M(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});var PL=Z0(),RL=nw(),CL=Ow(),OL=Aw(),Dw=Nw(),IL=[PL.default,RL.default,(0,CL.default)(),OL.default,Dw.metadataVocabulary,Dw.contentVocabulary];Jg.default=IL});var zw=M(Du=>{"use strict";Object.defineProperty(Du,"__esModule",{value:!0});Du.DiscrError=void 0;var jw;(function(t){t.Tag="tag",t.Mapping="mapping"})(jw||(Du.DiscrError=jw={}))});var Fw=M(Xg=>{"use strict";Object.defineProperty(Xg,"__esModule",{value:!0});var yo=re(),Yg=zw(),Lw=yu(),AL=Mi(),NL=pe(),DL={message:({params:{discrError:t,tagName:e}})=>t===Yg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,yo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},ML={keyword:"discriminator",type:"object",schemaType:"object",error:DL,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,yo._)`${r}${(0,yo.getProperty)(a)}`);e.if((0,yo._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:Yg.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let h=m();e.if(!1);for(let p in h)e.elseIf((0,yo._)`${u} === ${p}`),e.assign(c,l(h[p]));e.else(),t.error(!1,{discrError:Yg.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(h){let p=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(f,yo.Name),p}function m(){var h;let p={},f=y(s),g=!0;for(let S=0;S<i.length;S++){let v=i[S];if(v?.$ref&&!(0,NL.schemaHasRulesButRef)(v,o.self.RULES)){let $=v.$ref;if(v=Lw.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,$),v instanceof Lw.SchemaEnv&&(v=v.schema),v===void 0)throw new AL.default(o.opts.uriResolver,o.baseId,$)}let R=(h=v?.properties)===null||h===void 0?void 0:h[a];if(typeof R!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(v)),b(R,S)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:S}){return Array.isArray(S)&&S.includes(a)}function b(S,v){if(S.const)_(S.const,v);else if(S.enum)for(let R of S.enum)_(R,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(S,v){if(typeof S!="string"||S in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[S]=v}}}};Xg.default=ML});var Uw=M((P5,jL)=>{jL.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 ey=M((Ce,Qg)=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.MissingRefError=Ce.ValidationError=Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=Ce.Ajv=void 0;var zL=j0(),LL=Mw(),FL=Fw(),Hw=Uw(),UL=["/properties"],Mu="http://json-schema.org/draft-07/schema",_o=class extends zL.default{_addVocabularies(){super._addVocabularies(),LL.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(FL.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Hw,UL):Hw;this.addMetaSchema(e,Mu,!1),this.refs["http://json-schema.org/schema"]=Mu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Mu)?Mu:void 0)}};Ce.Ajv=_o;Qg.exports=Ce=_o;Qg.exports.Ajv=_o;Object.defineProperty(Ce,"__esModule",{value:!0});Ce.default=_o;var HL=Di();Object.defineProperty(Ce,"KeywordCxt",{enumerable:!0,get:function(){return HL.KeywordCxt}});var bo=re();Object.defineProperty(Ce,"_",{enumerable:!0,get:function(){return bo._}});Object.defineProperty(Ce,"str",{enumerable:!0,get:function(){return bo.str}});Object.defineProperty(Ce,"stringify",{enumerable:!0,get:function(){return bo.stringify}});Object.defineProperty(Ce,"nil",{enumerable:!0,get:function(){return bo.nil}});Object.defineProperty(Ce,"Name",{enumerable:!0,get:function(){return bo.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:!0,get:function(){return bo.CodeGen}});var ZL=hu();Object.defineProperty(Ce,"ValidationError",{enumerable:!0,get:function(){return ZL.default}});var BL=Mi();Object.defineProperty(Ce,"MissingRefError",{enumerable:!0,get:function(){return BL.default}})});var Jw=M(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.formatNames=Ar.fastFormats=Ar.fullFormats=void 0;function Ir(t,e){return{validate:t,compare:e}}Ar.fullFormats={date:Ir(Vw,sy),time:Ir(ry(!0),oy),"date-time":Ir(Zw(!0),Gw),"iso-time":Ir(ry(),Ww),"iso-date-time":Ir(Zw(),Kw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:JL,"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:nF,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:YL,int32:{type:"number",validate:eF},int64:{type:"number",validate:tF},float:{type:"number",validate:qw},double:{type:"number",validate:qw},password:!0,binary:!0};Ar.fastFormats={...Ar.fullFormats,date:Ir(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,sy),time:Ir(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,oy),"date-time":Ir(/^\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,Gw),"iso-time":Ir(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Ww),"iso-date-time":Ir(/^\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,Kw),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};Ar.formatNames=Object.keys(Ar.fullFormats);function qL(t){return t%4===0&&(t%100!==0||t%400===0)}var VL=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,WL=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Vw(t){let e=VL.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&&qL(r)?29:WL[n])}function sy(t,e){if(t&&e)return t>e?1:t<e?-1:0}var ty=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function ry(t){return function(r){let n=ty.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,m=s-u*c-(l<0?1:0);return(m===23||m===-1)&&(l===59||l===-1)&&i<61}}function oy(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 Ww(t,e){if(!(t&&e))return;let r=ty.exec(t),n=ty.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 ny=/t|\s/i;function Zw(t){let e=ry(t);return function(n){let s=n.split(ny);return s.length===2&&Vw(s[0])&&e(s[1])}}function Gw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function Kw(t,e){if(!(t&&e))return;let[r,n]=t.split(ny),[s,o]=e.split(ny),i=sy(r,s);if(i!==void 0)return i||oy(n,o)}var GL=/\/|:/,KL=/^(?:[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 JL(t){return GL.test(t)&&KL.test(t)}var Bw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function YL(t){return Bw.lastIndex=0,Bw.test(t)}var XL=-(2**31),QL=2**31-1;function eF(t){return Number.isInteger(t)&&t<=QL&&t>=XL}function tF(t){return Number.isInteger(t)}function qw(){return!0}var rF=/[^\\]\\Z/;function nF(t){if(rF.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var Yw=M(vo=>{"use strict";Object.defineProperty(vo,"__esModule",{value:!0});vo.formatLimitDefinition=void 0;var sF=ey(),hr=re(),kn=hr.operators,ju={formatMaximum:{okStr:"<=",ok:kn.LTE,fail:kn.GT},formatMinimum:{okStr:">=",ok:kn.GTE,fail:kn.LT},formatExclusiveMaximum:{okStr:"<",ok:kn.LT,fail:kn.GTE},formatExclusiveMinimum:{okStr:">",ok:kn.GT,fail:kn.LTE}},oF={message:({keyword:t,schemaCode:e})=>(0,hr.str)`should be ${ju[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,hr._)`{comparison: ${ju[t].okStr}, limit: ${e}}`};vo.formatLimitDefinition={keyword:Object.keys(ju),type:"string",schemaType:"string",$data:!0,error:oF,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 sF.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,hr._)`${m}[${c.schemaCode}]`);t.fail$data((0,hr.or)((0,hr._)`typeof ${h} != "object"`,(0,hr._)`${h} instanceof RegExp`,(0,hr._)`typeof ${h}.compare != "function"`,l(h)))}function d(){let m=c.schema,h=a.formats[m];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${s}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:h,code:i.code.formats?(0,hr._)`${i.code.formats}${(0,hr.getProperty)(m)}`:void 0});t.fail$data(l(p))}function l(m){return(0,hr._)`${m}.compare(${r}, ${n}) ${ju[s].fail} 0`}},dependencies:["format"]};var iF=t=>(t.addKeyword(vo.formatLimitDefinition),t);vo.default=iF});var tE=M((Ji,eE)=>{"use strict";Object.defineProperty(Ji,"__esModule",{value:!0});var xo=Jw(),aF=Yw(),iy=re(),Xw=new iy.Name("fullFormats"),cF=new iy.Name("fastFormats"),ay=(t,e={keywords:!0})=>{if(Array.isArray(e))return Qw(t,e,xo.fullFormats,Xw),t;let[r,n]=e.mode==="fast"?[xo.fastFormats,cF]:[xo.fullFormats,Xw],s=e.formats||xo.formatNames;return Qw(t,s,r,n),e.keywords&&(0,aF.default)(t),t};ay.get=(t,e="full")=>{let n=(e==="fast"?xo.fastFormats:xo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function Qw(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,iy._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}eE.exports=Ji=ay;Object.defineProperty(Ji,"__esModule",{value:!0});Ji.default=ay});function uF(){let t=new rE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,nE.default)(t),t}var rE,nE,zu,sE=x(()=>{rE=No(ey(),1),nE=No(tE(),1);zu=class{constructor(e){this._ajv=e??uF()}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 Lu,oE=x(()=>{ds();Lu=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(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==l.size||![...d].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},vi,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},no,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 iE(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 aE(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 cE=x(()=>{});var Fu,uE=x(()=>{gk();ds();sE();ci();oE();cE();Fu=class extends ru{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(bi.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 zu,this.setRequestHandler(Sf,n=>this._oninitialize(n)),this.setNotificationHandler(kf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Cf,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=bi.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new Lu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=hk(this._capabilities,e)}setRequestHandler(e,r){let s=pn(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=dn(ro,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new H(V.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,m=await Promise.resolve(r(c,u));if(l.task){let p=dn(Ys,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new H(V.InvalidParams,`Invalid task creation result: ${f}`)}return p.data}let h=dn(Bc,m);if(!h.success){let p=h.error instanceof Error?h.error.message:String(h.error);throw new H(V.InvalidParams,`Invalid tools/call result: ${p}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){aE(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&iE(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:hS.includes(r)?r:yf,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"},Oc)}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},Of,r):this.request({method:"sampling/createMessage",params:e},vi,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},no,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},no,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},If,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 cy(t){return!!t&&typeof t=="object"&&dE in t}function pE(t){return t[dE]?.complete}var dE,lE,mE=x(()=>{dE=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(lE||(lE={}))});var fE=x(()=>{});function dF(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"),!lF.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 pF(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 uy(t){let e=dF(t);return pF(t,e.warnings),e.isValid}var lF,hE=x(()=>{lF=/^[A-Za-z0-9._-]{1,128}$/});var Uu,gE=x(()=>{Uu=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 ly=x(()=>{tc();tc()});function bE(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function vE(t){return"_def"in t||"_zod"in t||bE(t)}function dy(t){return typeof t!="object"||t===null||vE(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(bE)}function yE(t){if(t){if(dy(t))return ls(t);if(!vE(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function fF(t){let e=pn(t);return e?Object.entries(e).map(([r,n])=>{let s=Fx(n),o=Ux(n);return{name:r,description:s,required:!o}}):[]}function wn(t){let r=pn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Ec(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function _E(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Hu,mF,Yi,xE=x(()=>{uE();ci();hh();ds();mE();fE();hE();gE();ly();Hu=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 Fu(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Uu(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(wn(Zc)),this.server.assertCanSetRequestHandler(wn(ro)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Zc,()=>({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=Ks(r.inputSchema);return s?ph(s,{strictUnions:!0,pipeStrategy:"input"}):mF})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=Ks(r.outputSchema);s&&(n.outputSchema=ph(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(ro,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=Ks(e.inputSchema)??e.inputSchema,i=await kc(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=wc(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=Ks(e.outputSchema),o=await kc(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=wc(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(m=>setTimeout(m,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(wn(qc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(qc,async e=>{switch(e.params.ref.type){case"ref/prompt":return OS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return IS(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 Yi;let o=pn(n.argsSchema)?.[e.params.argument.name];if(!cy(o))return Yi;let i=pE(o);if(!i)return Yi;let a=await i(e.params.argument.value,e.params.context);return _E(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 Yi;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 Yi;let o=await s(e.params.argument.value,e.params.context);return _E(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(wn(Qs)),this.server.assertCanSetRequestHandler(wn(eo)),this.server.assertCanSetRequestHandler(wn(Uc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Qs,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(eo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Uc,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(wn(to)),this.server.assertCanSetRequestHandler(wn(Hc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(to,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?fF(r.argsSchema):void 0}))})),this.server.setRequestHandler(Hc,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=Ks(n.argsSchema),o=await kc(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=wc(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:ls(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=ls(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 St?c._def?.innerType:c;return cy(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,u){uy(e);let d={title:r,description:n,inputSchema:yE(s),outputSchema:yE(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"&&uy(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=ls(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=ls(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(dy(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!dy(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()}},mF={type:"object",properties:{}};Yi={completion:{values:[],hasMore:!1}}});function hF(t){return kS.parse(JSON.parse(t))}function SE(t){return JSON.stringify(t)+`
72
- `}var Zu,kE=x(()=>{ds();Zu=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),hF(r)}clear(){this._buffer=void 0}}});import wE from"node:process";var Bu,EE=x(()=>{kE();Bu=class{constructor(e=wE.stdin,r=wE.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Zu,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 DE={};ze(DE,{PolyglotExecutor:()=>So,buildScriptFilename:()=>IE,buildShellScriptContent:()=>NE,buildSpawnOptions:()=>AE});import{spawn as $E,execSync as gF,execFileSync as CE}from"node:child_process";import{mkdtempSync as yF,writeFileSync as TE,rmSync as PE,existsSync as RE}from"node:fs";import{join as qu,resolve as OE}from"node:path";import{tmpdir as _F}from"node:os";function IE(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${bF[t]}`}function AE(t){return{windowsHide:t==="win32"}}function vF(t){return`'${t.replace(/'/g,"'\\''")}'`}function NE(t,e,r){return r==="win32"||!e?t:`export PATH=${vF(e)}
74
- ${t}`}function py(t){if(Qt&&t.pid)try{gF(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Qt,bF,xF,So,my=x(()=>{"use strict";Ra();Qt=process.platform==="win32",bF={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};xF=(()=>{if(Qt)return process.env.TEMP??process.env.TMP??_F();try{let t=CE(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:OE(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();So=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??Ts()}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=yF(qu(xF,".ctx-mode-"));try{let a=this.#a(i,n,r),c=$_(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{PE(i,{recursive:!0,force:!0})}catch{}return d}catch(a){try{PE(i,{recursive:!0,force:!0})}catch{}throw a}}async executeFile(e){let{path:r,language:n,code:s,timeout:o}=e,i=OE(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
+ deps: ${r}}`};var Bz={keyword:"dependencies",type:"object",schemaType:"object",error:Ir.error,code(t){let[e,r]=qz(t);yw(t,e),_w(t,r)}};function qz({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 yw(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,Qi.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,Qi.checkReportMissingProp)(t,u)}):(r.if((0,Ug._)`${c} && (${(0,Qi.checkMissingProp)(t,a,o)})`),(0,Qi.reportMissingProp)(t,o),r.else())}}Ir.validatePropertyDeps=yw;function _w(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,Zz.alwaysValidSchema)(o,e[a])||(r.if((0,Qi.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))}Ir.validateSchemaDeps=_w;Ir.default=Bz});var xw=M(Hg=>{"use strict";Object.defineProperty(Hg,"__esModule",{value:!0});var vw=re(),Vz=pe(),Wz={message:"property name must be valid",params:({params:t})=>(0,vw._)`{propertyName: ${t.propertyName}}`},Gz={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:Wz,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,Vz.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,vw.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};Hg.default=Gz});var Bg=M(Zg=>{"use strict";Object.defineProperty(Zg,"__esModule",{value:!0});var Mu=Yt(),fr=re(),Kz=Br(),ju=pe(),Jz={message:"must NOT have additional properties",params:({params:t})=>(0,fr._)`{additionalProperty: ${t.additionalProperty}}`},Yz={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Jz,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,ju.alwaysValidSchema)(i,r))return;let u=(0,Mu.allSchemaProperties)(n.properties),d=(0,Mu.allSchemaProperties)(n.patternProperties);l(),t.ok((0,fr._)`${o} === ${Kz.default.errors}`);function l(){e.forIn("key",s,g=>{!u.length&&!d.length?p(g):e.if(m(g),()=>p(g))})}function m(g){let y;if(u.length>8){let b=(0,ju.schemaRefOrVal)(i,n.properties,"properties");y=(0,Mu.isOwnProperty)(e,b,g)}else u.length?y=(0,fr.or)(...u.map(b=>(0,fr._)`${g} === ${b}`)):y=fr.nil;return d.length&&(y=(0,fr.or)(y,...d.map(b=>(0,fr._)`${(0,Mu.usePattern)(t,b)}.test(${g})`))),(0,fr.not)(y)}function h(g){e.code((0,fr._)`delete ${s}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){h(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,ju.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(f(g,y,!1),e.if((0,fr.not)(y),()=>{t.reset(),h(g)})):(f(g,y),a||e.if((0,fr.not)(y),()=>e.break()))}}function f(g,y,b){let _={keyword:"additionalProperties",dataProp:g,dataPropType:ju.Type.Str};b===!1&&Object.assign(_,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(_,y)}}};Zg.default=Yz});var ww=M(Vg=>{"use strict";Object.defineProperty(Vg,"__esModule",{value:!0});var Xz=Li(),Sw=Yt(),qg=pe(),kw=Bg(),Qz={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&&kw.default.code(new Xz.KeywordCxt(o,kw.default,"additionalProperties"));let i=(0,Sw.allSchemaProperties)(r);for(let l of i)o.definedProperties.add(l);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=qg.mergeEvaluated.props(e,(0,qg.toHash)(i),o.props));let a=i.filter(l=>!(0,qg.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,Sw.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)}}};Vg.default=Qz});var Pw=M(Wg=>{"use strict";Object.defineProperty(Wg,"__esModule",{value:!0});var Ew=Yt(),zu=re(),$w=pe(),Tw=pe(),eL={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(f=>(0,$w.alwaysValidSchema)(o,r[f]));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 zu.Name)&&(o.props=(0,Tw.evaluatedPropsToName)(e,o.props));let{props:l}=o;m();function m(){for(let f of a)u&&h(f),o.allErrors?p(f):(e.var(d,!0),p(f),e.if(d))}function h(f){for(let g in u)new RegExp(f).test(g)&&(0,$w.checkStrictMode)(o,`property ${g} matches pattern ${f} (use allowMatchingProperties)`)}function p(f){e.forIn("key",n,g=>{e.if((0,zu._)`${(0,Ew.usePattern)(t,f)}.test(${g})`,()=>{let y=c.includes(f);y||t.subschema({keyword:"patternProperties",schemaProp:f,dataProp:g,dataPropType:Tw.Type.Str},d),o.opts.unevaluated&&l!==!0?e.assign((0,zu._)`${l}[${g}]`,!0):!y&&!o.allErrors&&e.if((0,zu.not)(d),()=>e.break())})})}}};Wg.default=eL});var Rw=M(Gg=>{"use strict";Object.defineProperty(Gg,"__esModule",{value:!0});var tL=pe(),rL={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,tL.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"}};Gg.default=rL});var Cw=M(Kg=>{"use strict";Object.defineProperty(Kg,"__esModule",{value:!0});var nL=Yt(),sL={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:nL.validateUnion,error:{message:"must match a schema in anyOf"}};Kg.default=sL});var Ow=M(Jg=>{"use strict";Object.defineProperty(Jg,"__esModule",{value:!0});var Lu=re(),oL=pe(),iL={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Lu._)`{passingSchemas: ${t.passing}}`},aL={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:iL,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 m;(0,oL.alwaysValidSchema)(s,d)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,Lu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Lu._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),m&&t.mergeEvaluated(m,Lu.Name)})})}}};Jg.default=aL});var Iw=M(Yg=>{"use strict";Object.defineProperty(Yg,"__esModule",{value:!0});var cL=pe(),uL={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,cL.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};Yg.default=uL});var Dw=M(Xg=>{"use strict";Object.defineProperty(Xg,"__esModule",{value:!0});var Fu=re(),Nw=pe(),lL={message:({params:t})=>(0,Fu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Fu._)`{failingKeyword: ${t.ifClause}}`},dL={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:lL,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,Nw.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=Aw(n,"then"),o=Aw(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,Fu.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let d=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(d)}function u(d,l){return()=>{let m=t.subschema({keyword:d},a);e.assign(i,a),t.mergeValidEvaluated(m,i),l?e.assign(l,(0,Fu._)`${d}`):t.setParams({ifClause:d})}}}};function Aw(t,e){let r=t.schema[e];return r!==void 0&&!(0,Nw.alwaysValidSchema)(t,r)}Xg.default=dL});var Mw=M(Qg=>{"use strict";Object.defineProperty(Qg,"__esModule",{value:!0});var pL=pe(),mL={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,pL.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Qg.default=mL});var jw=M(ey=>{"use strict";Object.defineProperty(ey,"__esModule",{value:!0});var fL=Mg(),hL=mw(),gL=jg(),yL=hw(),_L=gw(),bL=bw(),vL=xw(),xL=Bg(),SL=ww(),kL=Pw(),wL=Rw(),EL=Cw(),$L=Ow(),TL=Iw(),PL=Dw(),RL=Mw();function CL(t=!1){let e=[wL.default,EL.default,$L.default,TL.default,PL.default,RL.default,vL.default,xL.default,bL.default,SL.default,kL.default];return t?e.push(hL.default,yL.default):e.push(fL.default,gL.default),e.push(_L.default),e}ey.default=CL});var zw=M(ty=>{"use strict";Object.defineProperty(ty,"__esModule",{value:!0});var Be=re(),OL={message:({schemaCode:t})=>(0,Be.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Be._)`{format: ${t}}`},IL={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:OL,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?m():h();function m(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),f=r.const("fDef",(0,Be._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Be._)`typeof ${f} == "object" && !(${f} instanceof RegExp)`,()=>r.assign(g,(0,Be._)`${f}.type || "string"`).assign(y,(0,Be._)`${f}.validate`),()=>r.assign(g,(0,Be._)`"string"`).assign(y,f)),t.fail$data((0,Be.or)(b(),_()));function b(){return c.strictSchema===!1?Be.nil:(0,Be._)`${i} && !${y}`}function _(){let S=d.$async?(0,Be._)`(${f}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Be._)`${y}(${n})`,v=(0,Be._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${n}))`;return(0,Be._)`${y} && ${y} !== true && ${g} === ${e} && !${v}`}}function h(){let p=l.formats[o];if(!p){b();return}if(p===!0)return;let[f,g,y]=_(p);f===e&&t.pass(S());function b(){if(c.strictSchema===!1){l.logger.warn(v());return}throw new Error(v());function v(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function _(v){let P=v instanceof RegExp?(0,Be.regexpCode)(v):c.code.formats?(0,Be._)`${c.code.formats}${(0,Be.getProperty)(o)}`:void 0,T=r.scopeValue("formats",{key:o,ref:v,code:P});return typeof v=="object"&&!(v instanceof RegExp)?[v.type||"string",v.validate,(0,Be._)`${T}.validate`]:["string",v,T]}function S(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Be._)`await ${y}(${n})`}return typeof g=="function"?(0,Be._)`${y}(${n})`:(0,Be._)`${y}.test(${n})`}}}};ty.default=IL});var Lw=M(ry=>{"use strict";Object.defineProperty(ry,"__esModule",{value:!0});var AL=zw(),NL=[AL.default];ry.default=NL});var Fw=M(_o=>{"use strict";Object.defineProperty(_o,"__esModule",{value:!0});_o.contentVocabulary=_o.metadataVocabulary=void 0;_o.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];_o.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var Hw=M(ny=>{"use strict";Object.defineProperty(ny,"__esModule",{value:!0});var DL=K0(),ML=uw(),jL=jw(),zL=Lw(),Uw=Fw(),LL=[DL.default,ML.default,(0,jL.default)(),zL.default,Uw.metadataVocabulary,Uw.contentVocabulary];ny.default=LL});var Bw=M(Uu=>{"use strict";Object.defineProperty(Uu,"__esModule",{value:!0});Uu.DiscrError=void 0;var Zw;(function(t){t.Tag="tag",t.Mapping="mapping"})(Zw||(Uu.DiscrError=Zw={}))});var Vw=M(oy=>{"use strict";Object.defineProperty(oy,"__esModule",{value:!0});var bo=re(),sy=Bw(),qw=ku(),FL=Fi(),UL=pe(),HL={message:({params:{discrError:t,tagName:e}})=>t===sy.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,bo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},ZL={keyword:"discriminator",type:"object",schemaType:"object",error:HL,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,bo._)`${r}${(0,bo.getProperty)(a)}`);e.if((0,bo._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:sy.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let h=m();e.if(!1);for(let p in h)e.elseIf((0,bo._)`${u} === ${p}`),e.assign(c,l(h[p]));e.else(),t.error(!1,{discrError:sy.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(h){let p=e.name("valid"),f=t.subschema({keyword:"oneOf",schemaProp:h},p);return t.mergeEvaluated(f,bo.Name),p}function m(){var h;let p={},f=y(s),g=!0;for(let S=0;S<i.length;S++){let v=i[S];if(v?.$ref&&!(0,UL.schemaHasRulesButRef)(v,o.self.RULES)){let T=v.$ref;if(v=qw.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,T),v instanceof qw.SchemaEnv&&(v=v.schema),v===void 0)throw new FL.default(o.opts.uriResolver,o.baseId,T)}let P=(h=v?.properties)===null||h===void 0?void 0:h[a];if(typeof P!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(f||y(v)),b(P,S)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return p;function y({required:S}){return Array.isArray(S)&&S.includes(a)}function b(S,v){if(S.const)_(S.const,v);else if(S.enum)for(let P of S.enum)_(P,v);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function _(S,v){if(typeof S!="string"||S in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[S]=v}}}};oy.default=ZL});var Ww=M((N5,BL)=>{BL.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 ay=M((Ce,iy)=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.MissingRefError=Ce.ValidationError=Ce.CodeGen=Ce.Name=Ce.nil=Ce.stringify=Ce.str=Ce._=Ce.KeywordCxt=Ce.Ajv=void 0;var qL=Z0(),VL=Hw(),WL=Vw(),Gw=Ww(),GL=["/properties"],Hu="http://json-schema.org/draft-07/schema",vo=class extends qL.default{_addVocabularies(){super._addVocabularies(),VL.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(WL.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Gw,GL):Gw;this.addMetaSchema(e,Hu,!1),this.refs["http://json-schema.org/schema"]=Hu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Hu)?Hu:void 0)}};Ce.Ajv=vo;iy.exports=Ce=vo;iy.exports.Ajv=vo;Object.defineProperty(Ce,"__esModule",{value:!0});Ce.default=vo;var KL=Li();Object.defineProperty(Ce,"KeywordCxt",{enumerable:!0,get:function(){return KL.KeywordCxt}});var xo=re();Object.defineProperty(Ce,"_",{enumerable:!0,get:function(){return xo._}});Object.defineProperty(Ce,"str",{enumerable:!0,get:function(){return xo.str}});Object.defineProperty(Ce,"stringify",{enumerable:!0,get:function(){return xo.stringify}});Object.defineProperty(Ce,"nil",{enumerable:!0,get:function(){return xo.nil}});Object.defineProperty(Ce,"Name",{enumerable:!0,get:function(){return xo.Name}});Object.defineProperty(Ce,"CodeGen",{enumerable:!0,get:function(){return xo.CodeGen}});var JL=xu();Object.defineProperty(Ce,"ValidationError",{enumerable:!0,get:function(){return JL.default}});var YL=Fi();Object.defineProperty(Ce,"MissingRefError",{enumerable:!0,get:function(){return YL.default}})});var rE=M(Nr=>{"use strict";Object.defineProperty(Nr,"__esModule",{value:!0});Nr.formatNames=Nr.fastFormats=Nr.fullFormats=void 0;function Ar(t,e){return{validate:t,compare:e}}Nr.fullFormats={date:Ar(Xw,dy),time:Ar(uy(!0),py),"date-time":Ar(Kw(!0),eE),"iso-time":Ar(uy(),Qw),"iso-date-time":Ar(Kw(),tE),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:nF,"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:lF,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:sF,int32:{type:"number",validate:aF},int64:{type:"number",validate:cF},float:{type:"number",validate:Yw},double:{type:"number",validate:Yw},password:!0,binary:!0};Nr.fastFormats={...Nr.fullFormats,date:Ar(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,dy),time:Ar(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,py),"date-time":Ar(/^\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,eE),"iso-time":Ar(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,Qw),"iso-date-time":Ar(/^\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,tE),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};Nr.formatNames=Object.keys(Nr.fullFormats);function XL(t){return t%4===0&&(t%100!==0||t%400===0)}var QL=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,eF=[0,31,28,31,30,31,30,31,31,30,31,30,31];function Xw(t){let e=QL.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&&XL(r)?29:eF[n])}function dy(t,e){if(t&&e)return t>e?1:t<e?-1:0}var cy=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function uy(t){return function(r){let n=cy.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,m=s-u*c-(l<0?1:0);return(m===23||m===-1)&&(l===59||l===-1)&&i<61}}function py(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 Qw(t,e){if(!(t&&e))return;let r=cy.exec(t),n=cy.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 ly=/t|\s/i;function Kw(t){let e=uy(t);return function(n){let s=n.split(ly);return s.length===2&&Xw(s[0])&&e(s[1])}}function eE(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function tE(t,e){if(!(t&&e))return;let[r,n]=t.split(ly),[s,o]=e.split(ly),i=dy(r,s);if(i!==void 0)return i||py(n,o)}var tF=/\/|:/,rF=/^(?:[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 nF(t){return tF.test(t)&&rF.test(t)}var Jw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function sF(t){return Jw.lastIndex=0,Jw.test(t)}var oF=-(2**31),iF=2**31-1;function aF(t){return Number.isInteger(t)&&t<=iF&&t>=oF}function cF(t){return Number.isInteger(t)}function Yw(){return!0}var uF=/[^\\]\\Z/;function lF(t){if(uF.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var nE=M(So=>{"use strict";Object.defineProperty(So,"__esModule",{value:!0});So.formatLimitDefinition=void 0;var dF=ay(),hr=re(),En=hr.operators,Zu={formatMaximum:{okStr:"<=",ok:En.LTE,fail:En.GT},formatMinimum:{okStr:">=",ok:En.GTE,fail:En.LT},formatExclusiveMaximum:{okStr:"<",ok:En.LT,fail:En.GTE},formatExclusiveMinimum:{okStr:">",ok:En.GT,fail:En.LTE}},pF={message:({keyword:t,schemaCode:e})=>(0,hr.str)`should be ${Zu[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,hr._)`{comparison: ${Zu[t].okStr}, limit: ${e}}`};So.formatLimitDefinition={keyword:Object.keys(Zu),type:"string",schemaType:"string",$data:!0,error:pF,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 dF.KeywordCxt(o,a.RULES.all.format.definition,"format");c.$data?u():d();function u(){let m=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),h=e.const("fmt",(0,hr._)`${m}[${c.schemaCode}]`);t.fail$data((0,hr.or)((0,hr._)`typeof ${h} != "object"`,(0,hr._)`${h} instanceof RegExp`,(0,hr._)`typeof ${h}.compare != "function"`,l(h)))}function d(){let m=c.schema,h=a.formats[m];if(!h||h===!0)return;if(typeof h!="object"||h instanceof RegExp||typeof h.compare!="function")throw new Error(`"${s}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:h,code:i.code.formats?(0,hr._)`${i.code.formats}${(0,hr.getProperty)(m)}`:void 0});t.fail$data(l(p))}function l(m){return(0,hr._)`${m}.compare(${r}, ${n}) ${Zu[s].fail} 0`}},dependencies:["format"]};var mF=t=>(t.addKeyword(So.formatLimitDefinition),t);So.default=mF});var aE=M((ea,iE)=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});var ko=rE(),fF=nE(),my=re(),sE=new my.Name("fullFormats"),hF=new my.Name("fastFormats"),fy=(t,e={keywords:!0})=>{if(Array.isArray(e))return oE(t,e,ko.fullFormats,sE),t;let[r,n]=e.mode==="fast"?[ko.fastFormats,hF]:[ko.fullFormats,sE],s=e.formats||ko.formatNames;return oE(t,s,r,n),e.keywords&&(0,fF.default)(t),t};fy.get=(t,e="full")=>{let n=(e==="fast"?ko.fastFormats:ko.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function oE(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,my._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}iE.exports=ea=fy;Object.defineProperty(ea,"__esModule",{value:!0});ea.default=fy});function gF(){let t=new cE.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,uE.default)(t),t}var cE,uE,Bu,lE=x(()=>{cE=Mo(ay(),1),uE=Mo(aE(),1);Bu=class{constructor(e){this._ajv=e??gF()}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 qu,dE=x(()=>{ps();qu=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(m=>m.type==="tool_use").map(m=>m.id)),l=new Set(o.filter(m=>m.type==="tool_result").map(m=>m.toolUseId));if(d.size!==l.size||![...d].every(m=>l.has(m)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},wi,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},oo,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 pE(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 mE(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 fE=x(()=>{});var Vu,hE=x(()=>{Sk();ps();lE();pi();dE();fE();Vu=class extends cu{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ki.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 Bu,this.setRequestHandler(Rf,n=>this._oninitialize(n)),this.setNotificationHandler(Cf,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(jf,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ki.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new qu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=xk(this._capabilities,e)}setRequestHandler(e,r){let s=fn(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Vt(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=mn(so,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new H(V.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,m=await Promise.resolve(r(c,u));if(l.task){let p=mn(Qs,m);if(!p.success){let f=p.error instanceof Error?p.error.message:String(p.error);throw new H(V.InvalidParams,`Invalid task creation result: ${f}`)}return p.data}let h=mn(Jc,m);if(!h.success){let p=h.error instanceof Error?h.error.message:String(h.error);throw new H(V.InvalidParams,`Invalid tools/call result: ${p}`)}return h.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){mE(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&pE(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:xS.includes(r)?r:wf,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this.request({method:"ping"},jc)}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},zf,r):this.request({method:"sampling/createMessage",params:e},wi,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},oo,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},oo,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},Lf,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 hy(t){return!!t&&typeof t=="object"&&yE in t}function _E(t){return t[yE]?.complete}var yE,gE,bE=x(()=>{yE=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(gE||(gE={}))});var vE=x(()=>{});function _F(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"),!yF.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 bF(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 gy(t){let e=_F(t);return bF(t,e.warnings),e.isValid}var yF,xE=x(()=>{yF=/^[A-Za-z0-9._-]{1,128}$/});var Wu,SE=x(()=>{Wu=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 yy=x(()=>{ac();ac()});function EE(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function $E(t){return"_def"in t||"_zod"in t||EE(t)}function _y(t){return typeof t!="object"||t===null||$E(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(EE)}function kE(t){if(t){if(_y(t))return ds(t);if(!$E(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function xF(t){let e=fn(t);return e?Object.entries(e).map(([r,n])=>{let s=Vx(n),o=Wx(n);return{name:r,description:s,required:!o}}):[]}function $n(t){let r=fn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Oc(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function wE(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var Gu,vF,ta,TE=x(()=>{hE();pi();Sh();ps();bE();vE();xE();SE();yy();Gu=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 Vu(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Wu(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler($n(Kc)),this.server.assertCanSetRequestHandler($n(so)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Kc,()=>({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=Ys(r.inputSchema);return s?bh(s,{strictUnions:!0,pipeStrategy:"input"}):vF})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=Ys(r.outputSchema);s&&(n.outputSchema=bh(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(so,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=Ys(e.inputSchema)??e.inputSchema,i=await Rc(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=Cc(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=Ys(e.outputSchema),o=await Rc(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=Cc(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(m=>setTimeout(m,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($n(Yc)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(Yc,async e=>{switch(e.params.ref.type){case"ref/prompt":return jS(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return zS(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 ta;let o=fn(n.argsSchema)?.[e.params.argument.name];if(!hy(o))return ta;let i=_E(o);if(!i)return ta;let a=await i(e.params.argument.value,e.params.context);return wE(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 ta;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 ta;let o=await s(e.params.argument.value,e.params.context);return wE(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler($n(to)),this.server.assertCanSetRequestHandler($n(ro)),this.server.assertCanSetRequestHandler($n(Wc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(to,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(ro,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Wc,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($n(no)),this.server.assertCanSetRequestHandler($n(Gc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(no,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?xF(r.argsSchema):void 0}))})),this.server.setRequestHandler(Gc,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=Ys(n.argsSchema),o=await Rc(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=Cc(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:ds(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=ds(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 St?c._def?.innerType:c;return hy(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,u){gy(e);let d={title:r,description:n,inputSchema:kE(s),outputSchema:kE(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"&&gy(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=ds(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=ds(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(_y(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!_y(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()}},vF={type:"object",properties:{}};ta={completion:{values:[],hasMore:!1}}});function SF(t){return RS.parse(JSON.parse(t))}function PE(t){return JSON.stringify(t)+`
76
+ `}var Ku,RE=x(()=>{ps();Ku=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
77
+ `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),SF(r)}clear(){this._buffer=void 0}}});import CE from"node:process";var Ju,OE=x(()=>{RE();Ju=class{constructor(e=CE.stdin,r=CE.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Ku,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=PE(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var UE={};Ie(UE,{PolyglotExecutor:()=>wo,buildScriptFilename:()=>zE,buildShellScriptContent:()=>FE,buildSpawnOptions:()=>LE});import{spawn as IE,execSync as kF,execFileSync as ME}from"node:child_process";import{mkdtempSync as wF,writeFileSync as AE,rmSync as NE,existsSync as DE}from"node:fs";import{join as Yu,resolve as jE}from"node:path";import{tmpdir as EF}from"node:os";function zE(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${$F[t]}`}function LE(t){return{windowsHide:t==="win32"}}function TF(t){return`'${t.replace(/'/g,"'\\''")}'`}function FE(t,e,r){return r==="win32"||!e?t:`export PATH=${TF(e)}
78
+ ${t}`}function by(t){if(er&&t.pid)try{kF(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var er,$F,PF,wo,vy=x(()=>{"use strict";Aa();er=process.platform==="win32",$F={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs",csharp:"csx"};PF=(()=>{if(er)return process.env.TEMP??process.env.TMP??EF();try{let t=ME(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:jE(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();wo=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??Ps()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(er?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:r,code:n,timeout:s,background:o=!1}=e,i=wF(Yu(PF,".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{NE(i,{recursive:!0,force:!0})}catch{}return d}catch(a){try{NE(i,{recursive:!0,force:!0})}catch{}throw a}}async executeFile(e){let{path:r,language:n,code:s,timeout:o}=e,i=jE(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
79
 
76
80
  import "fmt"
77
81
 
@@ -79,12 +83,12 @@ func main() {
79
83
  ${r}
80
84
  }
81
85
  `),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
82
- ${r}`),n==="elixir"&&RE(qu(this.#s,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(qu(this.#s,"_build/dev/lib"))}, "*/ebin"))
86
+ ${r}`),n==="elixir"&&DE(Yu(this.#s,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(Yu(this.#s,"_build/dev/lib"))}, "*/ebin"))
83
87
  |> Enum.each(&Code.prepend_path/1)
84
88
 
85
- ${r}`);let s=qu(e,IE(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?TE(s,NE(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):TE(s,r,"utf-8"),s}async#c(e,r,n){let s=Qt?".exe":"",o=e.replace(/\.rs$/,"")+s;try{CE("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","dotnet-script"].includes(e[0]),c=e[0],u;Qt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Qt?e.slice(1).map(_=>_.replace(/\\/g,"/")):e.slice(1);let d={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!Qt,...AE(process.platform)},l;if(a){let _=[c,...u].map(S=>/\s/.test(S)?JSON.stringify(S):S).join(" ");l=$E(_,[],{...d,shell:!0})}else l=$E(c,u,{...d,shell:!1});let m=!1,h=!1,p=s===void 0?void 0:setTimeout(()=>{if(m=!0,o){h=!0,l.pid&&this.#o.add(l.pid),l.unref(),l.stdout.destroy(),l.stderr.destroy();let _=Buffer.concat(f).toString("utf-8"),S=Buffer.concat(g).toString("utf-8");i({stdout:_,stderr:S,exitCode:0,timedOut:!0,backgrounded:!0})}else py(l)},s),f=[],g=[],y=0,b=!1;l.stdout.on("data",_=>{y+=_.length,y<=this.#e?f.push(_):b||(b=!0,py(l))}),l.stderr.on("data",_=>{y+=_.length,y<=this.#e?g.push(_):b||(b=!0,py(l))}),l.on("close",_=>{if(clearTimeout(p),h)return;let S=Buffer.concat(f).toString("utf-8"),v=Buffer.concat(g).toString("utf-8");b&&(v+=`
87
- [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:S,stderr:v,exitCode:m?1:_??1,timedOut:m})}),l.on("error",_=>{clearTimeout(p),!h&&i({stdout:"",stderr:_.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),s={};for(let[o,i]of Object.entries(process.env))i!==void 0&&!n.has(o)&&!o.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(o)&&(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(RE(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};
89
+ ${r}`);let s=Yu(e,zE(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?AE(s,FE(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):AE(s,r,"utf-8"),s}async#c(e,r,n){let s=er?".exe":"",o=e.replace(/\.rs$/,"")+s;try{ME("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:
90
+ ${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=er&&["tsx","ts-node","elixir","bun","dotnet-script"].includes(e[0]),c=e[0],u;er&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=er?e.slice(1).map(_=>_.replace(/\\/g,"/")):e.slice(1);let d={cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),detached:!er,...LE(process.platform)},l;if(a){let _=[c,...u].map(S=>/\s/.test(S)?JSON.stringify(S):S).join(" ");l=IE(_,[],{...d,shell:!0})}else l=IE(c,u,{...d,shell:!1});let m=!1,h=!1,p=s===void 0?void 0:setTimeout(()=>{if(m=!0,o){h=!0,l.pid&&this.#o.add(l.pid),l.unref(),l.stdout.destroy(),l.stderr.destroy();let _=Buffer.concat(f).toString("utf-8"),S=Buffer.concat(g).toString("utf-8");i({stdout:_,stderr:S,exitCode:0,timedOut:!0,backgrounded:!0})}else by(l)},s),f=[],g=[],y=0,b=!1;l.stdout.on("data",_=>{y+=_.length,y<=this.#e?f.push(_):b||(b=!0,by(l))}),l.stderr.on("data",_=>{y+=_.length,y<=this.#e?g.push(_):b||(b=!0,by(l))}),l.on("close",_=>{if(clearTimeout(p),h)return;let S=Buffer.concat(f).toString("utf-8"),v=Buffer.concat(g).toString("utf-8");b&&(v+=`
91
+ [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:S,stderr:v,exitCode:m?1:_??1,timedOut:m})}),l.on("error",_=>{clearTimeout(p),!h&&i({stdout:"",stderr:_.message,exitCode:1,timedOut:!1})})})}#u(e){let r=process.env.HOME??process.env.USERPROFILE??e,n=new Set(["BASH_ENV","ENV","PROMPT_COMMAND","PS4","SHELLOPTS","BASHOPTS","CDPATH","INPUTRC","BASH_XTRACEFD","NODE_OPTIONS","NODE_PATH","PYTHONSTARTUP","PYTHONHOME","PYTHONWARNINGS","PYTHONBREAKPOINT","PYTHONINSPECT","RUBYOPT","RUBYLIB","PERL5OPT","PERL5LIB","PERLLIB","PERL5DB","ERL_AFLAGS","ERL_FLAGS","ELIXIR_ERL_OPTIONS","ERL_LIBS","GOFLAGS","CGO_CFLAGS","CGO_LDFLAGS","RUSTC","RUSTC_WRAPPER","RUSTC_WORKSPACE_WRAPPER","CARGO_BUILD_RUSTC","CARGO_BUILD_RUSTC_WRAPPER","RUSTFLAGS","PHPRC","PHP_INI_SCAN_DIR","R_PROFILE","R_PROFILE_USER","R_HOME","DOTNET_STARTUP_HOOKS","DOTNET_ADDITIONAL_DEPS","DOTNET_SHARED_STORE","DOTNET_ROOT","DOTNET_ROOT(x86)","DOTNET_HOST_PATH","CORECLR_PROFILER","CORECLR_PROFILER_PATH","CORECLR_PROFILER_PATH_32","CORECLR_PROFILER_PATH_64","CORECLR_PROFILER_PATH_ARM32","CORECLR_PROFILER_PATH_ARM64","CORECLR_ENABLE_PROFILING","DOTNET_PROFILER_PATH","DOTNET_PROFILER_PATH_32","DOTNET_PROFILER_PATH_64","DOTNET_PROFILER_PATH_ARM32","DOTNET_PROFILER_PATH_ARM64","DOTNET_DiagnosticPorts","DOTNET_BUNDLE_EXTRACT_BASE_DIR","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),s={};for(let[o,i]of Object.entries(process.env))i!==void 0&&!n.has(o)&&!o.startsWith("BASH_FUNC_")&&!/^COMPlus_/i.test(o)&&(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",er&&!s.PATH&&s.Path&&(s.PATH=s.Path,delete s.Path),s.PATH||(s.PATH=er?"":"/usr/local/bin:/usr/bin:/bin"),er){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=er?[]:["/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
92
  const file_path = FILE_CONTENT_PATH;
89
93
  const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
90
94
  ${n}`;case"python":return`FILE_CONTENT_PATH = ${s}
@@ -142,7 +146,7 @@ file_content = File.read!(file_content_path)
142
146
  ${n}`;case"csharp":return`var FILE_CONTENT_PATH = ${s};
143
147
  var file_path = FILE_CONTENT_PATH;
144
148
  var FILE_CONTENT = System.IO.File.ReadAllText(FILE_CONTENT_PATH);
145
- ${n}`}}}});import{cpus as SF}from"node:os";async function fy(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,SF().length):o,a=Math.min(o,i,t.length),c=a<o,u=new Array(t.length),d=0;async function l(){for(;;){let h=d++;if(h>=t.length)return;try{let p=await t[h].run();u[h]={status:"fulfilled",value:p}}catch(p){u[h]={status:"rejected",reason:p}}s?.(h,u[h])}}let m=[];for(let h=0;h<a;h++)m.push(l());return await Promise.allSettled(m),{settled:u,effectiveConcurrency:a,capped:c}}var ME=x(()=>{"use strict"});var yy={};ze(yy,{BunSQLiteAdapter:()=>Vu,NodeSQLiteAdapter:()=>Wu,SQLiteBase:()=>Qi,applyWALPragmas:()=>wo,cleanOrphanedWALFiles:()=>Eo,closeDB:()=>$o,defaultDBPath:()=>gy,deleteDBFiles:()=>Gu,hasModernSqlite:()=>LE,isSQLiteCorruptionError:()=>Ku,loadDatabase:()=>nt,nodeSqliteHasFts5:()=>zE,renameCorruptDB:()=>FE,withRetry:()=>En});import{createRequire as kF}from"node:module";import{existsSync as wF,unlinkSync as jE,renameSync as EF}from"node:fs";import{tmpdir as $F}from"node:os";import{join as TF}from"node:path";function zE(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 LE(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[s,o]=(n.node??"0.0.0").split("."),i=Number(s),a=Number(o);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function nt(){if(!ko){let t=kF(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;ko=function(n,s){let o=new e(n,{readonly:s?.readonly,create:!0}),i=new Vu(o);return s?.timeout&&i.pragma(`busy_timeout = ${s.timeout}`),i}}else if(LE()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&zE(e)?ko=function(n,s){let o=new e(n,{readOnly:s?.readonly??!1});return new Wu(o)}:ko=t("better-sqlite3")}else ko=t("better-sqlite3")}return ko}function wo(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function Eo(t){if(!wF(t))for(let e of["-wal","-shm"])try{jE(t+e)}catch{}}function Gu(t){for(let e of["","-wal","-shm"])try{jE(t+e)}catch{}}function $o(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function gy(t="context-mode"){return TF($F(),`${t}-${process.pid}.db`)}function En(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 Ku(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 FE(t){let e=Date.now();for(let r of["","-wal","-shm"])try{EF(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var Vu,Wu,ko,Xi,hy,Qi,$n=x(()=>{"use strict";Vu=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()}},Wu=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()}},ko=null;Xi=Symbol.for("__context_mode_live_dbs_v3__"),hy=(()=>{let t=globalThis;return t[Xi]||(t[Xi]=new Set,process.on("exit",()=>{for(let e of t[Xi])$o(e);t[Xi].clear()})),t[Xi]})(),Qi=class{#e;#t;constructor(e){let r=nt();this.#e=e,Eo(e);let n;try{n=new r(e,{timeout:3e4}),wo(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Ku(o)){FE(e),Eo(e);try{n=new r(e,{timeout:3e4}),wo(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,hy.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){hy.delete(this.#t),$o(this.#t)}withRetry(e){return En(e)}cleanup(){hy.delete(this.#t),$o(this.#t),Gu(this.#e)}}});import{readFileSync as UE,readdirSync as WE,unlinkSync as by,existsSync as _y,statSync as Ju,openSync as HE,fstatSync as ZE,closeSync as BE}from"node:fs";import{createHash as qE}from"node:crypto";import{tmpdir as GE}from"node:os";import{join as vy}from"node:path";function KE(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 PF(t,e="AND"){let r=KE(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=>!To.has(o.toLowerCase()));return(n.length>0?n:r).map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function RF(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=KE(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let s=n.filter(i=>!To.has(i.toLowerCase()));return(s.length>0?s:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function CF(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 OF(t){return t<=4?1:t<=12?2:3}function xy(){let t=GE(),e=0;try{let r=WE(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=vy(t,n);for(let a of["","-wal","-shm"])try{by(i+a)}catch{}e++}}}catch{}return e}function Sy(t,e){let r=0;try{if(!_y(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=WE(t).filter(o=>o.endsWith(".db"));for(let o of s)try{let i=vy(t,o),c=Ju(i).mtimeMs<n;if(!c){let u=i+"-wal";if(_y(u))try{let d=Ju(u);d.size>0&&Date.now()-d.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{by(i+u)}catch{}r++}}catch{}}catch{}return r}function IF(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function AF(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,m=l+r;for(;u<a.length&&a[u]<l;)u++;u<a.length&&a[u]<=m&&(n++,u++)}}return n}function NF(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 To,VE,Yu,JE=x(()=>{"use strict";$n();To=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"]);VE=4096;Yu=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#b;#v;#x;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=nt();this.#t=e??vy(GE(),`context-mode-${process.pid}.db`),Eo(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),wo(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Ku(o)){Gu(this.#t),Eo(this.#t);try{n=new r(this.#t,{timeout:3e4}),wo(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{by(this.#t+e)}catch{}}#H(){this.#e.exec(`
149
+ ${n}`}}}});import{cpus as RF}from"node:os";async function xy(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,RF().length):o,a=Math.min(o,i,t.length),c=a<o,u=new Array(t.length),d=0;async function l(){for(;;){let h=d++;if(h>=t.length)return;try{let p=await t[h].run();u[h]={status:"fulfilled",value:p}}catch(p){u[h]={status:"rejected",reason:p}}s?.(h,u[h])}}let m=[];for(let h=0;h<a;h++)m.push(l());return await Promise.allSettled(m),{settled:u,effectiveConcurrency:a,capped:c}}var HE=x(()=>{"use strict"});var wy={};Ie(wy,{BunSQLiteAdapter:()=>Xu,NodeSQLiteAdapter:()=>Qu,SQLiteBase:()=>na,applyWALPragmas:()=>$o,cleanOrphanedWALFiles:()=>To,closeDB:()=>Po,defaultDBPath:()=>ky,deleteDBFiles:()=>el,hasModernSqlite:()=>qE,isSQLiteCorruptionError:()=>tl,loadDatabase:()=>nt,nodeSqliteHasFts5:()=>BE,renameCorruptDB:()=>VE,withRetry:()=>Tn});import{createRequire as CF}from"node:module";import{existsSync as OF,unlinkSync as ZE,renameSync as IF}from"node:fs";import{tmpdir as AF}from"node:os";import{join as NF}from"node:path";function BE(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 qE(t,e){let r=e!==void 0?e:globalThis.Bun;if(typeof r<"u"&&r!==null)return!0;let n=t??process.versions,[s,o]=(n.node??"0.0.0").split("."),i=Number(s),a=Number(o);return!Number.isFinite(i)||!Number.isFinite(a)?!1:i>22||i===22&&a>=5}function nt(){if(!Eo){let t=CF(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Eo=function(n,s){let o=new e(n,{readonly:s?.readonly,create:!0}),i=new Xu(o);return s?.timeout&&i.pragma(`busy_timeout = ${s.timeout}`),i}}else if(qE()){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&BE(e)?Eo=function(n,s){let o=new e(n,{readOnly:s?.readonly??!1});return new Qu(o)}:Eo=t("better-sqlite3")}else Eo=t("better-sqlite3")}return Eo}function $o(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function To(t){if(!OF(t))for(let e of["-wal","-shm"])try{ZE(t+e)}catch{}}function el(t){for(let e of["","-wal","-shm"])try{ZE(t+e)}catch{}}function Po(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function ky(t="context-mode"){return NF(AF(),`${t}-${process.pid}.db`)}function Tn(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 tl(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{IF(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var Xu,Qu,Eo,ra,Sy,na,Pn=x(()=>{"use strict";Xu=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()}},Qu=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()}},Eo=null;ra=Symbol.for("__context_mode_live_dbs_v3__"),Sy=(()=>{let t=globalThis;return t[ra]||(t[ra]=new Set,process.on("exit",()=>{for(let e of t[ra])Po(e);t[ra].clear()})),t[ra]})(),na=class{#e;#t;constructor(e){let r=nt();this.#e=e,To(e);let n;try{n=new r(e,{timeout:3e4}),$o(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(tl(o)){VE(e),To(e);try{n=new r(e,{timeout:3e4}),$o(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,Sy.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){Sy.delete(this.#t),Po(this.#t)}withRetry(e){return Tn(e)}cleanup(){Sy.delete(this.#t),Po(this.#t),el(this.#e)}}});import{readFileSync as WE,readdirSync as QE,unlinkSync as $y,existsSync as Ey,statSync as rl,openSync as GE,fstatSync as KE,closeSync as JE}from"node:fs";import{createHash as YE}from"node:crypto";import{tmpdir as e$}from"node:os";import{join as Ty}from"node:path";function t$(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 DF(t,e="AND"){let r=t$(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=>!Ro.has(o.toLowerCase()));return(n.length>0?n:r).map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function MF(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=t$(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let s=n.filter(i=>!Ro.has(i.toLowerCase()));return(s.length>0?s:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function jF(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 zF(t){return t<=4?1:t<=12?2:3}function Py(){let t=e$(),e=0;try{let r=QE(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=Ty(t,n);for(let a of["","-wal","-shm"])try{$y(i+a)}catch{}e++}}}catch{}return e}function Ry(t,e){let r=0;try{if(!Ey(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=QE(t).filter(o=>o.endsWith(".db"));for(let o of s)try{let i=Ty(t,o),c=rl(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Ey(u))try{let d=rl(u);d.size>0&&Date.now()-d.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{$y(i+u)}catch{}r++}}catch{}}catch{}return r}function LF(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function FF(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,m=l+r;for(;u<a.length&&a[u]<l;)u++;u<a.length&&a[u]<=m&&(n++,u++)}}return n}function UF(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 Ro,XE,nl,r$=x(()=>{"use strict";Pn();Ro=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"]);XE=4096;nl=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#b;#v;#x;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=nt();this.#t=e??Ty(e$(),`context-mode-${process.pid}.db`),To(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),$o(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(tl(o)){el(this.#t),To(this.#t);try{n=new r(this.#t,{timeout:3e4}),$o(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{$y(this.#t+e)}catch{}}#H(){this.#e.exec(`
146
150
  CREATE TABLE IF NOT EXISTS sources (
147
151
  id INTEGER PRIMARY KEY AUTOINCREMENT,
148
152
  label TEXT NOT NULL,
@@ -382,7 +386,7 @@ ${n}`}}}});import{cpus as SF}from"node:os";async function fy(t,e){let{concurrenc
382
386
  (SELECT COUNT(*) FROM sources) AS sources,
383
387
  (SELECT COUNT(*) FROM chunks) AS chunks,
384
388
  (SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
385
- `),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,attribution:o}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let m=HE(n,"r");try{if(!ZE(m).isFile())throw new Error(`refusing to index ${n}: not a regular file`);a=UE(m,"utf-8")}finally{BE(m)}}let c=s??n??"untitled",u=this.#V(a),d=n??void 0,l=d?qE("sha256").update(a).digest("hex"):void 0;return En(()=>this.#d(u,c,a,d,l,o))}indexPlainText(e,r,n=20,s){if(!e||e.trim().length===0)return this.#d([],r,"",void 0,void 0,s);let o=this.#W(e,n);return En(()=>this.#d(o.map(i=>({...i,hasCode:!1})),r,e,void 0,void 0,s))}indexJSON(e,r,n=VE,s){if(!e||e.trim().length===0)return this.indexPlainText("",r,void 0,s);let o;try{o=JSON.parse(e)}catch{return this.indexPlainText(e,r,void 0,s)}let i=[];return this.#U(o,[],i,n),i.length===0?this.indexPlainText(e,r,void 0,s):En(()=>this.#d(i,r,e,void 0,void 0,s))}#d(e,r,n,s,o,i){let a=e.filter(m=>m.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",l=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let f=this.#o.run(r,s??null,o??null);return Number(f.lastInsertRowid)}let m=this.#s.run(r,e.length,a,s??null,o??null),h=Number(m.lastInsertRowid),p=new Date().toISOString();for(let f of e){let g=f.hasCode?"code":"prose";this.#a.run(f.title,f.content,h,g,null,c,u,p),this.#c.run(f.title,f.content,h,g,null,c,u,p)}return h})();return n&&this.#q(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:l,label:r,totalChunks:e.length,codeChunks:a}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e}%`}search(e,r=3,n,s="AND",o,i="like"){let a=PF(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.#x,u=[a,o,r]):(c=this.#f,u=[a,r]),En(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,s="AND",o,i="like"){let a=RF(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.#b:this.#_,u=[a,this.#p(n,i),r]):o?(c=this.#w,u=[a,o,r]):(c=this.#y,u=[a,r]),En(()=>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=OF(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=CF(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=m=>`${m.source}::${m.title}`;for(let[m,h]of c.entries()){let p=l(h),f=d.get(p);f?f.score+=1/(60+m+1):d.set(p,{result:h,score:1/(60+m+1)})}for(let[m,h]of u.entries()){let p=l(h),f=d.get(p);f?f.score+=1/(60+m+1):d.set(p,{result:h,score:1/(60+m+1)})}return Array.from(d.values()).sort((m,h)=>h.score-m.score).slice(0,r).map(({result:m,score:h})=>({...m,rank:-h}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),s=n.filter(i=>!To.has(i)),o=s.length>0?s:n;return e.map(i=>{let a=i.title.toLowerCase(),c=o.filter(h=>a.includes(h)).length,u=i.contentType==="code"?.6:.3,d=c>0?u*(c/o.length):0,l=0,m=0;if(o.length>=2){let h=i.content.toLowerCase(),p=o.map(f=>IF(h,f));if(!p.some(f=>f.length===0)){l=1/(1+NF(p)/Math.max(h.length,1));let g=AF(p,o);m=.5*Math.min(1,g/4)}}return{result:i,boost:d+l+m}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,s,o="like"){this.#B();let i=this.#z(e,r,n,s,o);if(i.length>0)return this.#L(i,e).map(m=>({...m,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(l=>l.length>=3&&!To.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(h=>({...h,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(!_y(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=Ju(r.file_path).mtime,s=new Date(r.indexed_at+"Z");if(n<=s)continue;let o=HE(r.file_path,"r"),i;try{if(!ZE(o).isFile())continue;i=UE(o,"utf-8")}finally{BE(o)}if(qE("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(m=>m.length>=3&&!To.has(m)));for(let m of l)a.set(m,(a.get(m)??0)+1)}return Array.from(a.entries()).filter(([,d])=>d>=o&&d<=i).map(([d,l])=>{let m=Math.log(s/l),h=Math.min(d.length/20,.5),p=/[_]/.test(d),f=d.length>=12,g=p?1.5:f?.8:0;return{word:d,score:m+h+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 Ju(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(),$o(this.#e)}#q(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(o=>o.length>=3&&!To.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=VE){let n=[],s=e.split(`
389
+ `),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,attribution:o}=e,i=typeof r=="string"&&r.length>0;if(!i&&!n)throw new Error("Either content or path must be provided");let a;if(i)a=r;else{let m=GE(n,"r");try{if(!KE(m).isFile())throw new Error(`refusing to index ${n}: not a regular file`);a=WE(m,"utf-8")}finally{JE(m)}}let c=s??n??"untitled",u=this.#V(a),d=n??void 0,l=d?YE("sha256").update(a).digest("hex"):void 0;return Tn(()=>this.#d(u,c,a,d,l,o))}indexPlainText(e,r,n=20,s){if(!e||e.trim().length===0)return this.#d([],r,"",void 0,void 0,s);let o=this.#W(e,n);return Tn(()=>this.#d(o.map(i=>({...i,hasCode:!1})),r,e,void 0,void 0,s))}indexJSON(e,r,n=XE,s){if(!e||e.trim().length===0)return this.indexPlainText("",r,void 0,s);let o;try{o=JSON.parse(e)}catch{return this.indexPlainText(e,r,void 0,s)}let i=[];return this.#U(o,[],i,n),i.length===0?this.indexPlainText(e,r,void 0,s):Tn(()=>this.#d(i,r,e,void 0,void 0,s))}#d(e,r,n,s,o,i){let a=e.filter(m=>m.hasCode).length,c=i?.sessionId??"",u=i?.eventId??"",l=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let f=this.#o.run(r,s??null,o??null);return Number(f.lastInsertRowid)}let m=this.#s.run(r,e.length,a,s??null,o??null),h=Number(m.lastInsertRowid),p=new Date().toISOString();for(let f of e){let g=f.hasCode?"code":"prose";this.#a.run(f.title,f.content,h,g,null,c,u,p),this.#c.run(f.title,f.content,h,g,null,c,u,p)}return h})();return n&&this.#q(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:l,label:r,totalChunks:e.length,codeChunks:a}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e}%`}search(e,r=3,n,s="AND",o,i="like"){let a=DF(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.#x,u=[a,o,r]):(c=this.#f,u=[a,r]),Tn(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,s="AND",o,i="like"){let a=MF(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.#b:this.#_,u=[a,this.#p(n,i),r]):o?(c=this.#w,u=[a,o,r]):(c=this.#y,u=[a,r]),Tn(()=>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=zF(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=jF(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=m=>`${m.source}::${m.title}`;for(let[m,h]of c.entries()){let p=l(h),f=d.get(p);f?f.score+=1/(60+m+1):d.set(p,{result:h,score:1/(60+m+1)})}for(let[m,h]of u.entries()){let p=l(h),f=d.get(p);f?f.score+=1/(60+m+1):d.set(p,{result:h,score:1/(60+m+1)})}return Array.from(d.values()).sort((m,h)=>h.score-m.score).slice(0,r).map(({result:m,score:h})=>({...m,rank:-h}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),s=n.filter(i=>!Ro.has(i)),o=s.length>0?s:n;return e.map(i=>{let a=i.title.toLowerCase(),c=o.filter(h=>a.includes(h)).length,u=i.contentType==="code"?.6:.3,d=c>0?u*(c/o.length):0,l=0,m=0;if(o.length>=2){let h=i.content.toLowerCase(),p=o.map(f=>LF(h,f));if(!p.some(f=>f.length===0)){l=1/(1+UF(p)/Math.max(h.length,1));let g=FF(p,o);m=.5*Math.min(1,g/4)}}return{result:i,boost:d+l+m}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,s,o="like"){this.#B();let i=this.#z(e,r,n,s,o);if(i.length>0)return this.#L(i,e).map(m=>({...m,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(l=>l.length>=3&&!Ro.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(h=>({...h,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(!Ey(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=rl(r.file_path).mtime,s=new Date(r.indexed_at+"Z");if(n<=s)continue;let o=GE(r.file_path,"r"),i;try{if(!KE(o).isFile())continue;i=WE(o,"utf-8")}finally{JE(o)}if(YE("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(m=>m.length>=3&&!Ro.has(m)));for(let m of l)a.set(m,(a.get(m)??0)+1)}return Array.from(a.entries()).filter(([,d])=>d>=o&&d<=i).map(([d,l])=>{let m=Math.log(s/l),h=Math.min(d.length/20,.5),p=/[_]/.test(d),f=d.length>=12,g=p?1.5:f?.8:0;return{word:d,score:m+h+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 rl(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(),Po(this.#e)}#q(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(o=>o.length>=3&&!Ro.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=XE){let n=[],s=e.split(`
386
390
  `),o=[],i=[],a="",c=()=>{let d=i.join(`
387
391
  `).trim();if(d.length===0)return;let l=this.#Y(o,a),m=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(d)<=r){n.push({title:l,content:d,hasCode:m}),i=[];return}let h=d.split(/\n\n+/),p=[],f=1,g=()=>{if(p.length===0)return;let y=p.join(`
388
392
 
@@ -391,13 +395,13 @@ ${n}`}}}});import{cpus as SF}from"node:os";async function fy(t,e){let{concurrenc
391
395
  `);Buffer.byteLength(b)>r&&p.length>1&&(p.pop(),g(),p=[y])}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 h=l[1].length,p=l[2].trim();for(;o.length>0&&o[o.length-1].level>=h;)o.pop();o.push({level:h,text:p}),a=p,i.push(d),u++;continue}let m=d.match(/^(`{3,})(.*)?$/);if(m){let h=m[1],p=[d];for(u++;u<s.length;){if(p.push(s[u]),s[u].startsWith(h)&&s[u].trim()===h){u++;break}u++}i.push(...p);continue}i.push(d),u++}return c(),n}#W(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let d=c.trim();return{title:d.split(`
392
396
  `)[0].slice(0,80)||`Section ${u+1}`,content:d}}).filter(c=>c.content.length>0);let s=e.split(`
393
397
  `);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),m=u[0]?.trim().slice(0,80);o.push({title:m||`Lines ${d}-${l}`,content:u.join(`
394
- `)})}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 ky(t,e){return t===void 0?e:`${t}::${e}`}var YE=x(()=>{"use strict"});import{readFileSync as QE,realpathSync as DF}from"node:fs";import{resolve as ea}from"node:path";function e$(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function MF(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function jF(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function XE(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function zF(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let s=t.slice(0,n),o=t.slice(n+1),i=jF(s),a=XE(o);r=`^${i}(\\s${a})?$`}else r=`^${XE(t)}$`;return new RegExp(r,e?"i":"")}function LF(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 FF(t,e,r=!1){for(let n of e){let s=e$(n);if(s&&zF(s,r).test(t))return n}return null}function UF(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 wy(t){let e;try{e=QE(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"&&e$(i)!==null):[];return{allow:s(n.allow),deny:s(n.deny),ask:s(n.ask)}}function Ey(t,e){let r=[];if(t){let s=ea(t,".claude","settings.local.json"),o=wy(s);o&&r.push(o);let i=ea(t,".claude","settings.json"),a=wy(i);a&&r.push(a)}let n=e!==void 0?[e]:ql();for(let s of n){let o=wy(s);o&&r.push(o)}return r}function $y(t,e,r){let n=[],s=i=>{let a;try{a=QE(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let d=[];for(let l of u){if(typeof l!="string")continue;let m=MF(l);m&&m.tool===t&&d.push(m.glob)}return d};if(e){let i=s(ea(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=s(ea(e,".claude","settings.json"));a!==null&&n.push(a)}let o=r!==void 0?[r]:ql();for(let i of o){let a=s(i);a!==null&&n.push(a)}return n}function Ty(t,e,r=process.platform==="win32"){let n=UF(t);for(let s of n)for(let o of e){let i=FF(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=ea(n,t);o.add(s(i));try{o.add(s(DF(i)))}catch{}}for(let i of e)for(let a of i){let c=LF(s(a),r);for(let u of o)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function ZF(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 t$(t,e){let r=HF[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(...ZF(t)),n}var HF,r$=x(()=>{"use strict";tn();HF={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 Ry(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}
398
+ `)})}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 Cy(t,e){return t===void 0?e:`${t}::${e}`}var n$=x(()=>{"use strict"});import{readFileSync as o$,realpathSync as HF}from"node:fs";import{resolve as sa}from"node:path";function i$(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function ZF(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function BF(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function s$(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function qF(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let s=t.slice(0,n),o=t.slice(n+1),i=BF(s),a=s$(o);r=`^${i}(\\s${a})?$`}else r=`^${s$(t)}$`;return new RegExp(r,e?"i":"")}function VF(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 WF(t,e,r=!1){for(let n of e){let s=i$(n);if(s&&qF(s,r).test(t))return n}return null}function GF(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 Oy(t){let e;try{e=o$(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"&&i$(i)!==null):[];return{allow:s(n.allow),deny:s(n.deny),ask:s(n.ask)}}function Iy(t,e){let r=[];if(t){let s=sa(t,".claude","settings.local.json"),o=Oy(s);o&&r.push(o);let i=sa(t,".claude","settings.json"),a=Oy(i);a&&r.push(a)}let n=e!==void 0?[e]:Vd();for(let s of n){let o=Oy(s);o&&r.push(o)}return r}function Ay(t,e,r){let n=[],s=i=>{let a;try{a=o$(i,"utf-8")}catch{return null}let c;try{c=JSON.parse(a)}catch{return null}let u=c?.permissions?.deny;if(!Array.isArray(u))return[];let d=[];for(let l of u){if(typeof l!="string")continue;let m=ZF(l);m&&m.tool===t&&d.push(m.glob)}return d};if(e){let i=s(sa(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=s(sa(e,".claude","settings.json"));a!==null&&n.push(a)}let o=r!==void 0?[r]:Vd();for(let i of o){let a=s(i);a!==null&&n.push(a)}return n}function Ny(t,e,r=process.platform==="win32"){let n=GF(t);for(let s of n)for(let o of e){let i=WF(s,o.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Dy(t,e,r=process.platform==="win32",n){let s=i=>i.replace(/\\/g,"/"),o=new Set;if(o.add(s(t)),n){let i=sa(n,t);o.add(s(i));try{o.add(s(HF(i)))}catch{}}for(let i of e)for(let a of i){let c=VF(s(a),r);for(let u of o)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function JF(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 a$(t,e){let r=KF[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(...JF(t)),n}var KF,c$=x(()=>{"use strict";rn();KF={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}
395
399
 
396
400
  stdout:
397
401
  ${n}
398
402
 
399
403
  stderr:
400
- ${s}`}}var n$=x(()=>{"use strict"});import{execFileSync as BF}from"node:child_process";function qF(t=process.env){let e=t.CONTEXT_MODE_IDLE_TIMEOUT_MS;if(e===void 0)return 900*1e3;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<0?900*1e3:r}function VF(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=BF("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 WF(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??VF,n=e(),s=r();return()=>{let o=e();return!(o!==n||o===0||o===1||!Number.isNaN(s)&&s>1&&r()===1)}}function KF(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 s$(t){let e=t.checkIntervalMs??KF(),r=t.isParentAlive??GF,n=t.idleTimeoutMs??qF(),s=t.now??Date.now,o=!1,i=s(),a=()=>{o||(o=!0,t.onShutdown())},c=()=>{i=s()},u=setInterval(()=>{r()||a()},e);u.unref();let d=null;if(n>0&&!process.stdin.isTTY){let f=Math.max(50,Math.min(Math.floor(n/6),3e4));d=setInterval(()=>{s()-i>n&&a()},f),d.unref()}let l=["SIGTERM","SIGINT"];process.platform!=="win32"&&l.push("SIGHUP");for(let f of l)process.on(f,a);let m=()=>{r()||a()};process.stdin.isTTY||process.stdin.on("end",m);let h=()=>{o=!0,clearInterval(u),d&&clearInterval(d);for(let f of l)process.removeListener(f,a);process.stdin.removeListener("end",m)},p=h;return p.recordActivity=c,p.stop=h,p}var GF,o$=x(()=>{"use strict";GF=WF()});import{createHash as ra}from"node:crypto";import{execFileSync as JF}from"node:child_process";import{existsSync as Qu,realpathSync as YF,renameSync as Cy}from"node:fs";import{join as el}from"node:path";function na(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function i$(t){let e=t;try{e=YF.native(t)}catch{}let r=na(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function u$(t,e){return JF("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function XF(t){let e=u$(t,["rev-parse","--show-toplevel"]);return e.length>0?na(e):null}function QF(t){let e=u$(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?na(e):null}function tl(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(ta&&ta.projectDir===t&&ta.envSuffix===e)return ta.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=XF(t),s=QF(t);if(n&&s){let o=i$(n),i=i$(s);o!==i&&(r=`__${ra("sha256").update(o).digest("hex").slice(0,8)}`)}}catch{}return ta={projectDir:t,envSuffix:e,suffix:r},r}function Vr(t){return ra("sha256").update(na(t)).digest("hex").slice(0,16)}function Wr(t){let e=na(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return ra("sha256").update(r).digest("hex").slice(0,16)}function l$(t){let{projectDir:e,contentDir:r}=t,n=Wr(e),s=el(r,`${n}.db`);if(Qu(s))return s;let o=Vr(e);if(o===n)return s;let i=el(r,`${o}.db`);if(Qu(i))try{Cy(i,s);for(let a of["-wal","-shm"])try{Cy(i+a,s+a)}catch{}}catch{}return s}function sa(t){return e2({...t,ext:".db"})}function e2(t){let{projectDir:e,sessionsDir:r,ext:n}=t,s=t.suffix??tl(e),o=Wr(e),i=el(r,`${o}${s}${n}`);if(Qu(i))return i;let a=Vr(e);if(a===o)return i;let c=el(r,`${a}${s}${n}`);if(Qu(c))try{Cy(c,i)}catch{}return i}function Xu(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}var ta,a$,c$,q,gr,oa=x(()=>{"use strict";$n();a$=1e3,c$=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"},gr=class extends Qi{constructor(e){super(e?.dbPath??gy("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(`
404
+ ${s}`}}var u$=x(()=>{"use strict"});import{execFileSync as YF}from"node:child_process";function XF(t=process.env){let e=t.CONTEXT_MODE_IDLE_TIMEOUT_MS;if(e===void 0)return 0;let r=Number.parseInt(e,10);return!Number.isFinite(r)||r<0?0:r}function QF(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=YF("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 e2(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??QF,n=e(),s=r();return()=>{let o=e();return!(o!==n||o===0||o===1||!Number.isNaN(s)&&s>1&&r()===1)}}function r2(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 l$(t){let e=t.checkIntervalMs??r2(),r=t.isParentAlive??t2,n=t.idleTimeoutMs??XF(),s=t.now??Date.now,o=!1,i=s(),a=()=>{o||(o=!0,t.onShutdown())},c=()=>{i=s()},u=setInterval(()=>{r()||a()},e);u.unref();let d=null;if(n>0&&!process.stdin.isTTY){let f=Math.max(50,Math.min(Math.floor(n/6),3e4));d=setInterval(()=>{s()-i>n&&a()},f),d.unref()}let l=["SIGTERM","SIGINT"];process.platform!=="win32"&&l.push("SIGHUP");for(let f of l)process.on(f,a);let m=()=>{r()||a()};process.stdin.isTTY||process.stdin.on("end",m);let h=()=>{o=!0,clearInterval(u),d&&clearInterval(d);for(let f of l)process.removeListener(f,a);process.stdin.removeListener("end",m)},p=h;return p.recordActivity=c,p.stop=h,p}var t2,d$=x(()=>{"use strict";t2=e2()});import{createHash as ia}from"node:crypto";import{execFileSync as n2}from"node:child_process";import{existsSync as ol,realpathSync as s2,renameSync as jy}from"node:fs";import{join as il}from"node:path";function aa(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function p$(t){let e=t;try{e=s2.native(t)}catch{}let r=aa(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function h$(t,e){return n2("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function o2(t){let e=h$(t,["rev-parse","--show-toplevel"]);return e.length>0?aa(e):null}function i2(t){let e=h$(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?aa(e):null}function al(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(oa&&oa.projectDir===t&&oa.envSuffix===e)return oa.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=o2(t),s=i2(t);if(n&&s){let o=p$(n),i=p$(s);o!==i&&(r=`__${ia("sha256").update(o).digest("hex").slice(0,8)}`)}}catch{}return oa={projectDir:t,envSuffix:e,suffix:r},r}function Wr(t){return ia("sha256").update(aa(t)).digest("hex").slice(0,16)}function Gr(t){let e=aa(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return ia("sha256").update(r).digest("hex").slice(0,16)}function g$(t){let{projectDir:e,contentDir:r}=t,n=Gr(e),s=il(r,`${n}.db`);if(ol(s))return s;let o=Wr(e);if(o===n)return s;let i=il(r,`${o}.db`);if(ol(i))try{jy(i,s);for(let a of["-wal","-shm"])try{jy(i+a,s+a)}catch{}}catch{}return s}function ca(t){return a2({...t,ext:".db"})}function a2(t){let{projectDir:e,sessionsDir:r,ext:n}=t,s=t.suffix??al(e),o=Gr(e),i=il(r,`${o}${s}${n}`);if(ol(i))return i;let a=Wr(e);if(a===o)return i;let c=il(r,`${a}${s}${n}`);if(ol(c))try{jy(c,i)}catch{}return i}function sl(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}var oa,m$,f$,q,gr,ua=x(()=>{"use strict";Pn();m$=1e3,f$=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"},gr=class extends na{constructor(e){super(e?.dbPath??ky("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(`
401
405
  CREATE TABLE IF NOT EXISTS session_events (
402
406
  id INTEGER PRIMARY KEY AUTOINCREMENT,
403
407
  session_id TEXT NOT NULL,
@@ -515,19 +519,19 @@ ${s}`}}var n$=x(()=>{"use strict"});import{execFileSync as BF}from"node:child_pr
515
519
  FROM tool_calls WHERE session_id = ?`),e(q.getToolCallByTool,`SELECT tool, calls, bytes_returned
516
520
  FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(q.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
517
521
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
518
- FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",s,o){let i=ra("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=Xu(o?.bytesAvoided),m=Xu(o?.bytesReturned),h=this.db.transaction(()=>{if(this.stmt(q.checkDuplicate).get(e,c$,r.type,i))return;this.stmt(q.getEventCount).get(e).cnt>=a$&&this.stmt(q.evictLowestPriority).run(e),this.stmt(q.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,d,l,m,n,i),this.stmt(q.updateMetaLastEvent).run(e)});this.withRetry(()=>h())}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=ra("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),l=s?.[u],m=String(l?.projectDir??c.project_dir??"").trim(),h=String(l?.source??c.attribution_source??"unknown"),p=Number(l?.confidence??c.attribution_confidence??0),f=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=o?.[u],y=Xu(g?.bytesAvoided),b=Xu(g?.bytesReturned);return{event:c,dataHash:d,projectDir:m,attributionSource:h,attributionConfidence:f,bytesAvoided:y,bytesReturned:b}}),a=this.db.transaction(()=>{let c=this.stmt(q.getEventCount).get(e).cnt;for(let u of i)this.stmt(q.checkDuplicate).get(e,c$,u.event.type,u.dataHash)||(c>=a$?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 Oy,unlinkSync as t2}from"node:fs";import{join as ia}from"node:path";function Iy(t,e){try{return t2(t),e.push(t),!0}catch{return!1}}function rl(t,e){let r=!1;for(let n of r2)Iy(`${t}${n}`,e)&&n===""&&(r=!0);return r}function d$(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 _=tl(e),S=Wr(e),v=Vr(e),R=S===v?[S]:[S,v],$=!1;for(let P of R){let C=ia(r,`${P}${_}.db`);if(!Oy(C))continue;let L=null;try{L=new gr({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 T=[];if(n&&Oy(n)&&T.push(n),s){let P=Wr(e),C=Vr(e),L=P===C?[P]:[P,C];for(let X of L){let fe=ia(s,`${X}.db`);Oy(fe)&&!T.includes(fe)&&T.push(fe)}}let D=!1;for(let P of T)try{let C=nt(),L=new C(P,{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&&(D=!0)}finally{try{L.close()}catch{}}}catch{}return D&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:d}}let m=!1;if(n&&rl(n,d)&&(m=!0),s){let _=Wr(e),S=Vr(e),v=_===S?[_]:[_,S];for(let R of v){let $=ia(s,`${R}.db`);rl($,d)&&(m=!0)}}if(m&&u.push("knowledge base (FTS5)"),o){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let _=ia(o,`${i}.db`);rl(_,d)}let h=tl(e),p=Wr(e),f=Vr(e),g=p===f?[p]:[p,f],y=!1,b=!1;for(let _ of g){let S=ia(r,`${_}${h}`);rl(`${S}.db`,d)&&(y=!0),Iy(`${S}-events.md`,d)&&(b=!0),Iy(`${S}.cleanup`,d)}return y&&u.push("session events DB"),b&&u.push("session events markdown"),{deleted:u,wipedPaths:d}}var r2,p$=x(()=>{"use strict";$n();oa();r2=["","-wal","-shm"]});import{existsSync as n2}from"node:fs";function Ay(t,e){try{if(!n2(t))return;let r=new gr({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function m$(t){Ay(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 f$(t){Ay(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 h$(t){Ay(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 g$=x(()=>{"use strict";oa()});import{existsSync as y$}from"node:fs";function _$(t,e,r){try{if(!y$(t))return;let n=new gr({dbPath:t});try{let s=n.getLatestSessionId();if(!s)return;n.incrementToolCall(s,e,r)}finally{n.close()}}catch{}}function b$(t){try{if(!y$(t))return null;let e=new gr({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 v$=x(()=>{"use strict";oa()});import{existsSync as Ny,readFileSync as s2,readdirSync as o2,statSync as i2}from"node:fs";import{join as aa,isAbsolute as a2}from"node:path";function k$(t,e=5,r,n,s){let o=[],i=s?.getInstructionFiles()??["CLAUDE.md"],a=s?.getConfigDir(),u=(a?S$(r,a):null)??n??Be(),d=s?.getMemoryDir(),l=d?S$(r,d):aa(u,"memory"),m=[];if(r)for(let h of i){let p=aa(r,h);Ny(p)&&m.push({path:p,label:`project/${h}`})}if(u&&u!==r)for(let h of i){let p=aa(u,h);Ny(p)&&m.push({path:p,label:`user/${h}`})}if(l&&Ny(l))try{let h=o2(l).filter(p=>p.endsWith(".md"));for(let p of h)m.push({path:aa(l,p),label:`memory/${p}`})}catch(h){x$&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
519
- `)}for(let h of m){if(o.length>=e)break;try{let p;try{if(p=i2(h.path),p.size>1e6)continue}catch{continue}let f=s2(h.path,"utf-8"),g=f.toLowerCase();for(let y of t){if(o.length>=e)break;let _=y.toLowerCase().split(/\s+/).filter(v=>v.length>=3);if(_.some(v=>{try{return new RegExp(`\\b${v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(f)}catch{return g.includes(v)}})){let v=_.reduce((C,L)=>{let X=g.indexOf(L);return X>=0&&(C<0||X<C)?X:C},-1),R=Math.max(0,v-200),$=Math.min(f.length,v+500),T=f.lastIndexOf(`
520
-
521
- `,R),D=f.indexOf(`
522
-
523
- `,$);T>=0&&(R=T+2),D>=0&&($=D);let P=f.slice(R,$).trim();o.push({title:`[auto-memory] ${h.label}`,content:P,source:h.label,origin:"auto-memory",timestamp:p.mtime.toISOString()});break}}}catch(p){x$&&process.stderr.write(`[ctx] auto-memory file read failed: ${p}
524
- `)}}return o.slice(0,e)}function S$(t,e){return e?a2(e)||!t?e:aa(t,e):t??""}var x$,w$=x(()=>{"use strict";tn();x$=process.env.DEBUG?.includes("context-mode")});function E$(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=[],m=new Date().toISOString();try{let h=n.searchWithFallback(e,r,o,i);l.push(...h.map(p=>({title:p.title,content:p.content,source:p.source,origin:"current-session",timestamp:p.timestamp||m,rank:p.rank,matchLayer:p.matchLayer,highlighted:p.highlighted,contentType:p.contentType})))}catch(h){Dy&&process.stderr.write(`[ctx] ContentStore search failed: ${h}
525
- `)}if(s==="timeline"){try{if(a){let h=a.searchEvents(e,r,c||"",o);l.push(...h.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(h){Dy&&process.stderr.write(`[ctx] SessionDB search failed: ${h}
526
- `)}try{let h=k$([e],r,c,u,d);l.push(...h)}catch(h){Dy&&process.stderr.write(`[ctx] auto-memory search failed: ${h}
527
- `)}}for(let h of l)h.timestamp&&!h.timestamp.includes("T")&&(h.timestamp=h.timestamp.replace(" ","T")+"Z");return s==="timeline"&&l.sort((h,p)=>(h.timestamp||"").localeCompare(p.timestamp||"")),l.slice(0,r)}var Dy,$$=x(()=>{"use strict";w$();Dy=process.env.DEBUG?.includes("context-mode")});import*as Rt from"node:fs";import*as jy from"node:path";function My(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function l2(t){if(!Rt.existsSync(t.projectsRoot))return;let e,r=0;try{for(let n of Rt.readdirSync(t.projectsRoot)){let s=jy.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=jy.join(s,a);try{let u=Rt.statSync(c).mtimeMs;u>r&&(r=u,e=c)}catch{}}}}catch{return}if(e&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))try{let n=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(`
528
- `).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 T$(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:s,transcriptMaxAgeMs:o,nowMs:i,strictPlatform:a}=t,c=a?[...Zd(a),...c2]:u2;for(let u of c){let d=e[u];if(d&&!My(d))return d}if(s){let u=l2({projectsRoot:s,maxAgeMs:o,nowMs:i});if(u&&!My(u))return u}return n&&!My(n)?n:r}var c2,u2,P$=x(()=>{"use strict";Un();c2=["CONTEXT_MODE_PROJECT_DIR"],u2=["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 d2}from"node:child_process";import{existsSync as Gr,readdirSync as Po,statSync as p2}from"node:fs";import{homedir as il}from"node:os";import{join as Dt,sep as m2}from"node:path";function M$(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 h2(t){let e=t?.home??il();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 g2(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function ca(t){let e=Be(),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(Gr(r)){let h=[];try{h=Po(r).filter(p=>p.endsWith(".db"))}catch{}if(h.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():nt()}catch{}if(p)for(let f of h){let g=Dt(r,f);try{let y=new p(g,{readonly:!0});try{let b=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),_=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();s+=b?.cnt??0,o+=_?.cnt??0;try{let S=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let v of S)v.category&&(u[v.category]=(u[v.category]??0)+(v.cnt??0))}catch{}try{let S=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();S?.bytes&&(i+=S.bytes)}catch{}try{let S=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(S?.t){let v=S.t.endsWith("Z")?S.t:S.t+"Z",R=Date.parse(v);Number.isFinite(R)&&R<a&&(a=R)}}catch{}try{let S=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let v of S)v.p&&c.add(v.p)}catch{}}finally{y.close()}}catch{}}}}let d=0,l=0,m={};if(Gr(n)){let h=[];try{h=Po(n).filter(p=>{try{return p2(Dt(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of h){let f=Dt(n,p,"memory");if(!Gr(f))continue;let g=[];try{g=Po(f).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){l++,d+=g.length;for(let y of g){let b=g2(y);m[b]=(m[b]??0)+1}}}}return{totalEvents:s,totalSessions:o,autoMemoryCount:d,autoMemoryProjects:l,autoMemoryByPrefix:m,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function j$(t){let e=t.sessionsDir??Dt(il(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!Gr(e))return n;let s=[];try{s=Po(e).filter(_=>!(!_.endsWith(".db")||t.worktreeHash&&!_.startsWith(t.worktreeHash)))}catch{return n}if(s.length===0)return n;let o=null;try{o=t.loadDatabase?t.loadDatabase():nt()}catch{return n}if(!o)return n;let i={},a=0,c=0,u=0,d=0,l=Number.POSITIVE_INFINITY,m=0,h=0,p=new Map,f=_=>Math.floor(_/864e5)*864e5;for(let _ of s){let S=Dt(e,_),v=!1;try{let R=new o(S,{readonly:!0});try{let $=R.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let D of $)D.category&&(i[D.category]=(i[D.category]??0)+(D.cnt??0),a+=D.cnt??0,v=!0);let T=R.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(T?.mn){let D=Date.parse(T.mn+(T.mn.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D<l&&(l=D)}if(T?.mx){let D=Date.parse(T.mx+(T.mx.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D>m&&(m=D)}try{let D=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 P of D){if(!P.sec)continue;let C=parseInt(P.sec,10)*1e3;if(!Number.isFinite(C))continue;let L=f(C),X=p.get(L)??{count:0,rescueBytes:0};X.count+=P.cnt??0,p.set(L,X)}}catch{}try{let D=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(D?.bytes&&(u+=D.bytes),D?.n&&(d+=D.n),D?.lastSec){let P=parseInt(D.lastSec,10)*1e3;if(Number.isFinite(P)&&P>h&&(h=P),Number.isFinite(P)&&(D?.bytes??0)>0){let C=f(P),L=p.get(C)??{count:0,rescueBytes:0};L.rescueBytes=Math.max(L.rescueBytes,D.bytes),p.set(C,L)}}}catch{}}finally{R.close()}}catch{}v&&c++}let g=l<m?(m-l)/864e5:0,y=Object.entries(i).filter(([,_])=>_>0).map(([_,S])=>({category:_,count:S,label:nl[_]||_})).sort((_,S)=>S.count-_.count),b=[...p.entries()].sort((_,S)=>_[0]-S[0]).map(([_,S])=>({ms:_,count:S.count,...S.rescueBytes>0?{rescueBytes:S.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:d,byCategory:y,firstEventMs:Number.isFinite(l)?l:0,lastEventMs:m>0?m:0,lastRescueMs:h>0?h:void 0,byDay:b}}function y2(t,e,r){if(!t||!e||!Gr(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():nt()}catch{return 0}if(!n)return 0;try{let s=new n(e,{readonly:!0});try{let o=s.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
529
- FROM chunks WHERE session_id = ?`).get(t);return Number(o?.bytes??0)}finally{s.close()}}catch{return 0}}function z$(t,e){if(!t||!Gr(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():nt()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let s=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
530
- FROM chunks`).get();return Number(s?.bytes??0)}finally{n.close()}}catch{return 0}}function zy(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??Dt(il(),".claude","context-mode","sessions");if(!Gr(r))return e;let n=[];try{n=Po(r).filter(l=>!(!l.endsWith(".db")||t.worktreeHash&&!l.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let s=null;try{s=t.loadDatabase?t.loadDatabase():nt()}catch{return e}if(!s)return e;let o=0,i=0,a=0,c=0;for(let l of n){let m=Dt(r,l);try{let h=new s(m,{readonly:!0});try{if(t.sessionId){let p=h.prepare(`SELECT
522
+ FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",s,o){let i=ia("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=sl(o?.bytesAvoided),m=sl(o?.bytesReturned),h=this.db.transaction(()=>{if(this.stmt(q.checkDuplicate).get(e,f$,r.type,i))return;this.stmt(q.getEventCount).get(e).cnt>=m$&&this.stmt(q.evictLowestPriority).run(e),this.stmt(q.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,d,l,m,n,i),this.stmt(q.updateMetaLastEvent).run(e)});this.withRetry(()=>h())}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=ia("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),l=s?.[u],m=String(l?.projectDir??c.project_dir??"").trim(),h=String(l?.source??c.attribution_source??"unknown"),p=Number(l?.confidence??c.attribution_confidence??0),f=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=o?.[u],y=sl(g?.bytesAvoided),b=sl(g?.bytesReturned);return{event:c,dataHash:d,projectDir:m,attributionSource:h,attributionConfidence:f,bytesAvoided:y,bytesReturned:b}}),a=this.db.transaction(()=>{let c=this.stmt(q.getEventCount).get(e).cnt;for(let u of i)this.stmt(q.checkDuplicate).get(e,f$,u.event.type,u.dataHash)||(c>=m$?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 zy,unlinkSync as c2}from"node:fs";import{join as la}from"node:path";function Ly(t,e){try{return c2(t),e.push(t),!0}catch{return!1}}function cl(t,e){let r=!1;for(let n of u2)Ly(`${t}${n}`,e)&&n===""&&(r=!0);return r}function y$(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 _=al(e),S=Gr(e),v=Wr(e),P=S===v?[S]:[S,v],T=!1;for(let R of P){let C=la(r,`${R}${_}.db`);if(!zy(C))continue;let L=null;try{L=new gr({dbPath:C});let X=L.getEvents(a).length;L.deleteSession(a),X>0&&(T=!0)}catch{}finally{try{L?.close()}catch{}}}T&&u.push(`session rows for ${a}`);let $=[];if(n&&zy(n)&&$.push(n),s){let R=Gr(e),C=Wr(e),L=R===C?[R]:[R,C];for(let X of L){let fe=la(s,`${X}.db`);zy(fe)&&!$.includes(fe)&&$.push(fe)}}let D=!1;for(let R of $)try{let C=nt(),L=new C(R,{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&&(D=!0)}finally{try{L.close()}catch{}}}catch{}return D&&u.push(`FTS5 chunks for ${a}`),{deleted:u,wipedPaths:d}}let m=!1;if(n&&cl(n,d)&&(m=!0),s){let _=Gr(e),S=Wr(e),v=_===S?[_]:[_,S];for(let P of v){let T=la(s,`${P}.db`);cl(T,d)&&(m=!0)}}if(m&&u.push("knowledge base (FTS5)"),o){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let _=la(o,`${i}.db`);cl(_,d)}let h=al(e),p=Gr(e),f=Wr(e),g=p===f?[p]:[p,f],y=!1,b=!1;for(let _ of g){let S=la(r,`${_}${h}`);cl(`${S}.db`,d)&&(y=!0),Ly(`${S}-events.md`,d)&&(b=!0),Ly(`${S}.cleanup`,d)}return y&&u.push("session events DB"),b&&u.push("session events markdown"),{deleted:u,wipedPaths:d}}var u2,_$=x(()=>{"use strict";Pn();ua();u2=["","-wal","-shm"]});import{existsSync as l2}from"node:fs";function Fy(t,e){try{if(!l2(t))return;let r=new gr({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function b$(t){Fy(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 v$(t){Fy(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 x$(t){Fy(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 S$=x(()=>{"use strict";ua()});import{existsSync as k$}from"node:fs";function w$(t,e,r){try{if(!k$(t))return;let n=new gr({dbPath:t});try{let s=n.getLatestSessionId();if(!s)return;n.incrementToolCall(s,e,r)}finally{n.close()}}catch{}}function E$(t){try{if(!k$(t))return null;let e=new gr({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 $$=x(()=>{"use strict";ua()});import{existsSync as Uy,readFileSync as d2,readdirSync as p2,statSync as m2}from"node:fs";import{join as da,isAbsolute as f2}from"node:path";function R$(t,e=5,r,n,s){let o=[],i=s?.getInstructionFiles()??["CLAUDE.md"],a=s?.getConfigDir(),u=(a?P$(r,a):null)??n??Ze(),d=s?.getMemoryDir(),l=d?P$(r,d):da(u,"memory"),m=[];if(r)for(let h of i){let p=da(r,h);Uy(p)&&m.push({path:p,label:`project/${h}`})}if(u&&u!==r)for(let h of i){let p=da(u,h);Uy(p)&&m.push({path:p,label:`user/${h}`})}if(l&&Uy(l))try{let h=p2(l).filter(p=>p.endsWith(".md"));for(let p of h)m.push({path:da(l,p),label:`memory/${p}`})}catch(h){T$&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${h}
523
+ `)}for(let h of m){if(o.length>=e)break;try{let p;try{if(p=m2(h.path),p.size>1e6)continue}catch{continue}let f=d2(h.path,"utf-8"),g=f.toLowerCase();for(let y of t){if(o.length>=e)break;let _=y.toLowerCase().split(/\s+/).filter(v=>v.length>=3);if(_.some(v=>{try{return new RegExp(`\\b${v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(f)}catch{return g.includes(v)}})){let v=_.reduce((C,L)=>{let X=g.indexOf(L);return X>=0&&(C<0||X<C)?X:C},-1),P=Math.max(0,v-200),T=Math.min(f.length,v+500),$=f.lastIndexOf(`
524
+
525
+ `,P),D=f.indexOf(`
526
+
527
+ `,T);$>=0&&(P=$+2),D>=0&&(T=D);let R=f.slice(P,T).trim();o.push({title:`[auto-memory] ${h.label}`,content:R,source:h.label,origin:"auto-memory",timestamp:p.mtime.toISOString()});break}}}catch(p){T$&&process.stderr.write(`[ctx] auto-memory file read failed: ${p}
528
+ `)}}return o.slice(0,e)}function P$(t,e){return e?f2(e)||!t?e:da(t,e):t??""}var T$,C$=x(()=>{"use strict";rn();T$=process.env.DEBUG?.includes("context-mode")});function O$(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=[],m=new Date().toISOString();try{let h=n.searchWithFallback(e,r,o,i);l.push(...h.map(p=>({title:p.title,content:p.content,source:p.source,origin:"current-session",timestamp:p.timestamp||m,rank:p.rank,matchLayer:p.matchLayer,highlighted:p.highlighted,contentType:p.contentType})))}catch(h){Hy&&process.stderr.write(`[ctx] ContentStore search failed: ${h}
529
+ `)}if(s==="timeline"){try{if(a){let h=a.searchEvents(e,r,c||"",o);l.push(...h.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(h){Hy&&process.stderr.write(`[ctx] SessionDB search failed: ${h}
530
+ `)}try{let h=R$([e],r,c,u,d);l.push(...h)}catch(h){Hy&&process.stderr.write(`[ctx] auto-memory search failed: ${h}
531
+ `)}}for(let h of l)h.timestamp&&!h.timestamp.includes("T")&&(h.timestamp=h.timestamp.replace(" ","T")+"Z");return s==="timeline"&&l.sort((h,p)=>(h.timestamp||"").localeCompare(p.timestamp||"")),l.slice(0,r)}var Hy,I$=x(()=>{"use strict";C$();Hy=process.env.DEBUG?.includes("context-mode")});import*as Rt from"node:fs";import*as By from"node:path";function Zy(t){return t?/[/\\]\.claude[/\\]plugins[/\\](cache|marketplaces)[/\\]/.test(t):!1}function y2(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&&!(typeof t.maxAgeMs=="number"&&(t.nowMs??Date.now())-r>t.maxAgeMs))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(`
532
+ `).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 A$(t){let{env:e,cwd:r,pwd:n,transcriptsRoot:s,transcriptMaxAgeMs:o,nowMs:i,strictPlatform:a}=t,c=a?[...Bd(a),...h2]:g2;for(let u of c){let d=e[u];if(d&&!Zy(d))return d}if(s){let u=y2({projectsRoot:s,maxAgeMs:o,nowMs:i});if(u&&!Zy(u))return u}return n&&!Zy(n)?n:r}var h2,g2,N$=x(()=>{"use strict";on();h2=["CONTEXT_MODE_PROJECT_DIR"],g2=["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 _2}from"node:child_process";import{existsSync as Kr,readdirSync as Co,statSync as b2}from"node:fs";import{homedir as ml}from"node:os";import{join as Mt,sep as v2}from"node:path";function H$(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 S2(t){let e=t?.home??ml();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=Mt(e,...s,"context-mode");return{name:n,sessionsDir:Mt(o,"sessions"),contentDir:Mt(o,"content")}})}function k2(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function pa(t){let e=Ze(),r=t?.sessionsDir??Mt(e,"context-mode","sessions"),n=t?.memoryRoot??Mt(e,"projects"),s=0,o=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(Kr(r)){let h=[];try{h=Co(r).filter(p=>p.endsWith(".db"))}catch{}if(h.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():nt()}catch{}if(p)for(let f of h){let g=Mt(r,f);try{let y=new p(g,{readonly:!0});try{let b=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),_=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();s+=b?.cnt??0,o+=_?.cnt??0;try{let S=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let v of S)v.category&&(u[v.category]=(u[v.category]??0)+(v.cnt??0))}catch{}try{let S=y.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();S?.bytes&&(i+=S.bytes)}catch{}try{let S=y.prepare("SELECT MIN(created_at) AS t FROM session_events").get();if(S?.t){let v=S.t.endsWith("Z")?S.t:S.t+"Z",P=Date.parse(v);Number.isFinite(P)&&P<a&&(a=P)}}catch{}try{let S=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let v of S)v.p&&c.add(v.p)}catch{}}finally{y.close()}}catch{}}}}let d=0,l=0,m={};if(Kr(n)){let h=[];try{h=Co(n).filter(p=>{try{return b2(Mt(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of h){let f=Mt(n,p,"memory");if(!Kr(f))continue;let g=[];try{g=Co(f).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){l++,d+=g.length;for(let y of g){let b=k2(y);m[b]=(m[b]??0)+1}}}}return{totalEvents:s,totalSessions:o,autoMemoryCount:d,autoMemoryProjects:l,autoMemoryByPrefix:m,categoryCounts:u,rescueBytes:i,firstEventMs:Number.isFinite(a)?a:0,distinctProjects:c.size}}function Z$(t){let e=t.sessionsDir??Mt(ml(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!Kr(e))return n;let s=[];try{s=Co(e).filter(_=>!(!_.endsWith(".db")||t.worktreeHash&&!_.startsWith(t.worktreeHash)))}catch{return n}if(s.length===0)return n;let o=null;try{o=t.loadDatabase?t.loadDatabase():nt()}catch{return n}if(!o)return n;let i={},a=0,c=0,u=0,d=0,l=Number.POSITIVE_INFINITY,m=0,h=0,p=new Map,f=_=>Math.floor(_/864e5)*864e5;for(let _ of s){let S=Mt(e,_),v=!1;try{let P=new o(S,{readonly:!0});try{let T=P.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let D of T)D.category&&(i[D.category]=(i[D.category]??0)+(D.cnt??0),a+=D.cnt??0,v=!0);let $=P.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if($?.mn){let D=Date.parse($.mn+($.mn.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D<l&&(l=D)}if($?.mx){let D=Date.parse($.mx+($.mx.endsWith("Z")?"":"Z"));Number.isFinite(D)&&D>m&&(m=D)}try{let D=P.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let R of D){if(!R.sec)continue;let C=parseInt(R.sec,10)*1e3;if(!Number.isFinite(C))continue;let L=f(C),X=p.get(L)??{count:0,rescueBytes:0};X.count+=R.cnt??0,p.set(L,X)}}catch{}try{let D=P.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes, COUNT(*) AS n, MAX(strftime('%s', created_at)) AS lastSec FROM session_resume WHERE session_id = ? AND consumed = 1").get(r);if(D?.bytes&&(u+=D.bytes),D?.n&&(d+=D.n),D?.lastSec){let R=parseInt(D.lastSec,10)*1e3;if(Number.isFinite(R)&&R>h&&(h=R),Number.isFinite(R)&&(D?.bytes??0)>0){let C=f(R),L=p.get(C)??{count:0,rescueBytes:0};L.rescueBytes=Math.max(L.rescueBytes,D.bytes),p.set(C,L)}}}catch{}}finally{P.close()}}catch{}v&&c++}let g=l<m?(m-l)/864e5:0,y=Object.entries(i).filter(([,_])=>_>0).map(([_,S])=>({category:_,count:S,label:ll[_]||_})).sort((_,S)=>S.count-_.count),b=[...p.entries()].sort((_,S)=>_[0]-S[0]).map(([_,S])=>({ms:_,count:S.count,...S.rescueBytes>0?{rescueBytes:S.rescueBytes}:{}}));return{sessionId:r,events:a,dbCount:c,daysAlive:g,snapshotBytes:u,snapshotsConsumed:d,byCategory:y,firstEventMs:Number.isFinite(l)?l:0,lastEventMs:m>0?m:0,lastRescueMs:h>0?h:void 0,byDay:b}}function w2(t,e,r){if(!t||!e||!Kr(e))return 0;let n=null;try{n=r?.loadDatabase?r.loadDatabase():nt()}catch{return 0}if(!n)return 0;try{let s=new n(e,{readonly:!0});try{let o=s.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
533
+ FROM chunks WHERE session_id = ?`).get(t);return Number(o?.bytes??0)}finally{s.close()}}catch{return 0}}function B$(t,e){if(!t||!Kr(t))return 0;let r=null;try{r=e?.loadDatabase?e.loadDatabase():nt()}catch{return 0}if(!r)return 0;try{let n=new r(t,{readonly:!0});try{let s=n.prepare(`SELECT COALESCE(SUM(LENGTH(content) + LENGTH(title)), 0) AS bytes
534
+ FROM chunks`).get();return Number(s?.bytes??0)}finally{n.close()}}catch{return 0}}function qy(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,contentBytes:0,totalSavedTokens:0},r=t.sessionsDir??Mt(ml(),".claude","context-mode","sessions");if(!Kr(r))return e;let n=[];try{n=Co(r).filter(l=>!(!l.endsWith(".db")||t.worktreeHash&&!l.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let s=null;try{s=t.loadDatabase?t.loadDatabase():nt()}catch{return e}if(!s)return e;let o=0,i=0,a=0,c=0;for(let l of n){let m=Mt(r,l);try{let h=new s(m,{readonly:!0});try{if(t.sessionId){let p=h.prepare(`SELECT
531
535
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
532
536
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
533
537
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
@@ -535,36 +539,36 @@ ${s}`}}var n$=x(()=>{"use strict"});import{execFileSync as BF}from"node:child_pr
535
539
  COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
536
540
  COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
537
541
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
538
- FROM session_events`).get();p&&(o+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();f?.bytes&&(c+=Number(f.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=y2(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let d=Math.floor((o+i+c)/4);return{eventDataBytes:o,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:d}}function b2(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(!Gr(t.sessionsDir))return n;let s=[];try{s=Po(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 m=new o(l,{readonly:!0});try{let h=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();h&&(n.eventCount+=Number(h.cnt??0),n.dataBytes+=Number(h.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let f=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f<n.firstMs&&(n.firstMs=f)}if(p?.mx){let f=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f>n.lastMs&&(n.lastMs=f)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let f of p)f.p&&i.add(f.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let f of p)f.s&&a.add(f.s)}catch{}}finally{m.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function al(t){let e=h2({home:t?.home}),r=t?.loadDatabase??nt,n={..._2,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},s=[],o=0,i=0,a=0;for(let c of e){if(!Gr(c.sessionsDir))continue;let u=b2(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 sl(t){return v2[t]??t}function st(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 x2(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 S2(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(!e){if(process.platform==="darwin")try{let n=d2("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 R$(t){let e=il();return e?t===e?"~":t.startsWith(e+m2)?"~"+t.slice(e.length):t:t}function k2(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,s=(f,g=2)=>f.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),m=(e*1.25/1e6).toFixed(2),h=(e*.8/1e6).toFixed(2),p=[];return p.push(` $${s(n)} of Opus 4 tokens your team didn't burn.`),p.push(` context-mode kept ${st(t)} out of context \u2014 that's ${o} months of Cursor Pro paid for itself.`),c>0&&u>0&&(p.push(""),p.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p.push(""),p.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),p}function w2(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:s,cwd:o,locale:i,tz:a,now:c,version:u,latestVersion:d}=t,l=[],m=e.events*N$,h=Math.round((e.snapshotBytes??0)/4),p=m+h,f=s?.conversation?.totalSavedTokens??0,g=Math.max(p,f),y=(r?.totalEvents??0)*N$,b=Math.round((r?.rescueBytes??0)/4),_=y+b,S=s?.lifetime?.totalSavedTokens??0,v=Math.max(_,S),R=s?.lifetime?.bytesReturned??0,$=s?.lifetime?.bytesAvoided??0,T=R+$>0?Math.max(1,Math.floor(R/4)):Math.max(1,Math.round(v*.02)),D=n?.totalBytes&&n.totalBytes>0?n.totalBytes:v*4,P=s?.conversation?s.conversation.eventDataBytes+s.conversation.bytesAvoided+s.conversation.snapshotBytes:g*4,C=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`,L=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,X=L>0?Math.max(1,Math.round((c-L)/864e5)):0,fe=n?.totalSessions??r?.totalSessions??1,it=n?.perAdapter.filter(Ue=>Ue.isReal).length??0,pt;if(n&&it>=2)pt=`across ${it} AI tools`;else if(n&&it===1){let Ue=n.perAdapter.find(nr=>nr.isReal);pt=`in ${Ue?sl(Ue.name):"Claude Code"}`}else pt="in Claude Code";X>0?l.push(` Across ${X} days you ran ${yr(fe)} conversations ${pt}.`):l.push(` You ran ${yr(fe)} conversations ${pt}.`);let rr=X>0?D/X:0;l.push(` context-mode kept ${st(D)} out of your context window \u2014 about ${st(rr)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let Rn=e.firstEventMs&&e.firstEventMs>0?C$(e.firstEventMs,i,a):"";if(Rn?l.push(` This conversation started ${Rn} in ${R$(o)}.`):l.push(` This conversation lives in ${R$(o)}.`),l.push(` ${C}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ue=e.lastRescueMs&&e.lastRescueMs>0?C$(e.lastRescueMs,i,a):"",nr=Math.round(e.snapshotBytes/1024);Ue?l.push(` On ${Ue}, /compact fired \u2014 ${nr} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${nr} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let Ao=s?.conversation,_a=Ao?.bytesAvoided??0,wl=Ao?.bytesReturned??0,El=Ao?.eventDataBytes??0;if(_a+wl+El>0){let Ue=_a+wl+El,nr=Math.max(1,wl+El),sr=Math.max(1,Math.floor(Ue/4)),Nr=Math.max(1,Math.floor(nr/4)),$l=Tn(sr,sr,32),RT=Tn(Nr,sr,32),CT=(1-Nr/sr)*100,OT=Math.max(1,Math.round(sr/Nr));l.push(` Without context-mode ${st(Ue).padStart(8)} ${$l} ${yr(sr).padStart(7)} tokens`),l.push(` With context-mode ${st(nr).padStart(8)} ${RT} ${yr(Nr).padStart(7)} tokens`),l.push(` ${CT.toFixed(0)}% kept out of context \xB7 your AI ran ${OT}\xD7 longer before /compact fired`),l.push("")}if(e.byDay&&e.byDay.length>0){let Ue=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;l.push(` How that ${st(P)} built up \u2014 ${Ue} days, ${e.byDay.length} active:`),l.push(""),l.push(...$2(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 ET=e.byCategory.reduce((Ue,nr)=>Ue+nr.count,0).toLocaleString(i);l.push(` ${ET} things \u2014 files, errors, decisions, agent runs:`),l.push("");let $T=e.byCategory[0]?.count??1;for(let Ue of e.byCategory)l.push(` ${Ue.label.padEnd(26)} ${String(Ue.count).padStart(5)} ${Tn(Ue.count,$T,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let e_=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",t_=L>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(L)):"",r_=r?.distinctProjects??0,TT=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${st(P)} kept out \xB7 ${e.events.toLocaleString(i)} captures${e_?` \xB7 started ${e_}`:""}.`),l.push(` All your work: ${st(D)} kept out \xB7 ${TT.toLocaleString(i)} captures across ${r_} project${r_===1?"":"s"}${t_?` \xB7 since ${t_}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...k2(D,v,X)),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 Ue=Object.entries(r.autoMemoryByPrefix).sort((sr,Nr)=>Nr[1]-sr[1]),nr=Ue.length>0?Ue[0][1]:1;for(let[sr,Nr]of Ue){let $l=L$[sr]??sr;l.push(` ${$l.padEnd(26)} ${String(Nr).padStart(2)} ${Tn(Nr,nr,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 PT=u?`v${u}`:"context-mode";return l.push(` ${PT}`),u&&d&&d!=="unknown"&&M$(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),E2(l)}function E2(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 $2(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,h)=>m.ms-h.ms),s=n[0],o=n[n.length-1],i=Math.max(1,o.ms-s.ms),a=n[0];for(let m of n)m.count>a.count&&(a=m);let c=56,u=Array.from({length:c},()=>"\u2500");for(let m of n){let h=Math.round((m.ms-s.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[h]=p}let d=m=>{let h=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(h.find(g=>g.type==="month")?.value??"").toLowerCase(),f=h.find(g=>g.type==="day")?.value??"";return`${p} ${f}`},l=[];l.push(` ${d(s.ms)} ${u.join("")} ${d(o.ms)}`),l.push("");for(let m of n){let h=d(m.ms).padEnd(7),p=`${m.count} captures`,f=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";l.push(` ${h} ${p}${f}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function C$(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(m=>m.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 yr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function ol(t){return`$${((Number.isFinite(t)&&t>0?t:0)*cl).toFixed(2)}`}function Tn(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 O$(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(f=>f.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 f=i>=2?" everywhere":"";s.push(` All your work${f} \xB7 ${yr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${yr(c)} conversations`)}else{s.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let f=c===0&&r>0?1:c,g=f===1?"1 session":`${yr(f)} sessions`,y=a*256+r;s.push(` ${yr(a)} events \xB7 ${g} \xB7 ~${ol(y)} saved lifetime`)}s.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,f])=>f>0).map(([f,g])=>({category:f,count:g,label:nl[f]||f})).sort((f,g)=>g.count-f.count):l=(t.by_category??[]).filter(f=>f&&f.count>0);let m=l.slice(0,n),h=m.length>0?m[0].count:1;for(let f of m)s.push(` ${f.label.padEnd(26)} ${String(f.count).padStart(5)} ${Tn(f.count,h,30)}`);let p=Math.max(0,l.length-n);return p>0&&s.push(` ... ${p} more categor${p===1?"y":"ies"}`),s}function I$(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=L$[s]??s;e.push(` ${i.padEnd(26)} ${String(o).padStart(2)} ${Tn(o,n,20)}`)}return e}function A$(t,e){let r=[],n=ol(t),s=(e?.totalEvents??0)*256+t,o=ol(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 D$(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?yr(u.eventCount):"\u2014",m=st(u.dataBytes),h=st(d);n.push(` ${sl(u.name).padEnd(s)}${l.padStart(o)}${m.padStart(i)}${h.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let s=r.map(o=>sl(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 ul(t,e,r,n){let s=[],o=x2(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,T=$>0?Math.max(1,Math.round((Date.now()-$)/864e5)):0,D=T>0?`Across ${T} day${T===1?"":"s"} `:"",P=R>0?`you ran ${yr(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?sl(L.name):"Claude Code"}`}s.push(`${D}${P}${C}.`),s.push("")}if(c&&c.events>0){s.length>0&&(s.length=0);let R=S2(),$=n?.cwd??process.cwd(),T=n?.now??Date.now(),D=n?.locale??R.locale,P=n?.tz??R.tz;return s.push(...w2({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:$,locale:D,tz:P,now:T,version:e,latestVersion:r})),s.join(`
539
- `)}let m=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),h=t.savings.total_bytes_returned,p=t.savings.total_calls,f=m+h,g=f>0?m/f*100:0,y=Math.round(m/4),b=h>0?Math.max(1,Math.round(f/Math.max(h,1))):0;if(m===0){s.push(`context-mode ${o} ${p} calls`),s.push(""),p===0?s.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):s.push(`${st(h)} entered context | 0 tokens saved`),s.push(...O$(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:0})),s.push(...D$(d)),s.push(...I$(i)),s.push(...A$(0,i)),s.push("");let R=e?`v${e}`:"context-mode";return s.push(R),e&&r&&r!=="unknown"&&M$(r,e)&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
540
- `)}s.push(`${yr(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${o} \xB7 ~${ol(y)} saved (Opus)`),s.push(""),s.push(`Without context-mode |${Tn(f,f)}| ${st(f)}`),s.push(`With context-mode |${Tn(h,f)}| ${st(h)}`),s.push(""),b>=2?s.push(`${st(m)} kept out of your conversation \u2014 ${b}\xD7 longer sessions before compact.`):s.push(`${st(m)} kept out of your conversation. Never entered context.`),s.push("");let _=[`${p} calls`];t.cache&&t.cache.hits>0&&_.push(`${t.cache.hits} cache hits (+${st(t.cache.bytes_saved)})`),s.push(_.join(" \xB7 "));let S=t.savings.by_tool.filter(R=>R.calls>0);if(S.length>=2){s.push("");let R=S.map($=>{let T=$.context_kb*1024,D=g<100?T/(1-g/100):T,P=Math.max(0,D-T);return{...$,returnedBytes:T,estimatedSaved:P}}).sort(($,T)=>T.estimatedSaved-$.estimatedSaved);for(let $ of R){let T=$.tool.length>22?$.tool.slice(0,19)+"...":$.tool;s.push(` ${T.padEnd(22)} ${String($.calls).padStart(4)} calls ${st($.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 T=$.tool_name.replace(/^mcp__.*?__/,"");s.push(` ${T.padEnd(22)} ${$.calls} batches \xB7 ${$.median_concurrency} typical, ${$.max_concurrency} peak`)}}}s.push(...O$(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:y})),s.push(...D$(d)),s.push(...I$(i)),s.push(...A$(y,i)),s.push("");let v=e?`v${e}`:"context-mode";return s.push(v),e&&r&&r!=="unknown"&&r!==e&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
541
- `)}var nl,f2,Ro,_2,L$,v2,cl,N$,F$=x(()=>{"use strict";$n();tn();nl={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"},f2={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"},Ro=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)})),h=((Date.now()-e.sessionStart)/6e4).toFixed(1),p;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)));p={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:X,total_with_cache:C,total_savings_ratio:L}}let f=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),b=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,_=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),S=_?!_.consumed:!1,v=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 v){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:nl[C.category]||C.category,preview:R.get(C.category)?Array.from(R.get(C.category)).join(", "):"",why:f2[C.category]||"Survives context resets"})),T=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),P=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:nl[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:p,session:{id:n,uptime_min:h},continuity:{total_events:f,by_category:$,compact_count:b,resume_ready:S},projectMemory:{total_events:T.cnt,session_count:T.sessions,by_category:P}}}};_2={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};L$={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},v2={"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"};cl=15/1e6;N$=256});var lT={};ze(lT,{browserOpenArgv:()=>uT,buildBatchNodeOptionsPrefix:()=>oT,buildFetchCode:()=>cT,classifyIp:()=>ma,currentAttribution:()=>ks,extractSnippet:()=>Jy,formatBatchQueryResults:()=>sT,killProcessOnPort:()=>Xy,openBrowserSync:()=>By,positionsFromHighlight:()=>nT,resolveSessionIdFromSessionDB:()=>Q$,runBatchCommands:()=>iT});import{createRequire as Y$}from"node:module";import{existsSync as je,unlinkSync as la,readdirSync as T2,readFileSync as qy,writeFileSync as Vy,renameSync as P2,rmSync as fl,mkdirSync as da,cpSync as R2,statSync as U$,symlinkSync as C2,lstatSync as O2}from"node:fs";import{execSync as H$,spawnSync as X$}from"node:child_process";import{join as Oe,dirname as er,resolve as dt,sep as I2,isAbsolute as A2}from"node:path";import{fileURLToPath as N2}from"node:url";import{homedir as bl,tmpdir as Wy,cpus as D2}from"node:os";import{request as M2}from"node:https";function ks(){let t=process.env.CLAUDE_SESSION_ID??Q$();if(t)return{sessionId:t}}function Q$(t){let e=Date.now();if(!t?.bypassCache&&ll&&e-ll.checkedAt<2e3)return ll.sid;try{let r=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!r)return;let n=t?.sessionsDir??ot(),s=sa({projectDir:r,sessionsDir:n});if(!je(s))return;let o=nt(),i=new o(s,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(ll={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function j2(t){try{let e=ot();if(!je(e))return;let r=T2(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let s=Oe(e,n);try{t.index({path:s,source:"session-events",attribution:ks()}),la(s)}catch{}}}catch{}}function Hy(){return Be()}async function z2(){if(Pn)return Pn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(Un(),Wa)),e=ir();return await t(e.platform)}catch{return null}}function ot(){if(Pn)return Pn.getSessionDir();try{let e=ir(),r=Bd(e.platform);if(r){let n=Oe(bl(),...r);r.length===1&&r[0]===".claude"?n=Hy():r.length===1&&r[0]===".codex"&&(n=ja());let s=Oe(n,"context-mode","sessions");return da(s,{recursive:!0}),s}}catch{}let t=Oe(Hy(),"context-mode","sessions");return da(t,{recursive:!0}),t}function vr(){let t,e;try{let r=ir().platform;e=r,r==="claude-code"&&(t=Oe(bl(),".claude","projects"))}catch{}return T$({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:t,transcriptMaxAgeMs:300*1e3,strictPlatform:e})}function L2(t){return A2(t)?t:dt(vr(),t)}function pa(){return sa({projectDir:vr(),sessionsDir:ot()})}function hl(){let t=Oe(er(ot()),"content");return da(t,{recursive:!0}),l$({projectDir:vr(),contentDir:t})}function ws(){if(!_r){let t=hl();_r=new Yu(t),_r.setDenyChecker(e=>{try{let r=vr(),n=$y("Read",r);return Py(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=er(hl());Sy(e,14),_r.cleanupStaleSources(14);let r=Oe(bl(),".context-mode","content");je(r)&&Sy(r,0)}catch{}xy()}return j2(_r),_r}async function B$(){return new Promise(t=>{let e=M2("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 H2(){let t=Pn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function Z2(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 B2(){return!Yr||Yr==="unknown"?!1:Z2(Yr,Jr)}function q2(){if(!B2())return!1;let t=Date.now();if(dl>=F2){if(t-Z$<U2)return!1;dl=0}return dl===0&&(Z$=t),dl++,!0}function V2(){if(!q$){q$=!0;try{let t=Be(),e=dt(t,"plugins","installed_plugins.json");if(!je(e))return;let r=JSON.parse(qy(e,"utf-8")),n=dt(t,"plugins","cache"),s=je(dt(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||je(c)||!dt(c).startsWith(n+I2))continue;try{O2(c).isSymbolicLink()&&la(c)}catch{}let u=er(c);je(u)||da(u,{recursive:!0}),je(s)&&C2(s,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(V2(),q2()&&e.content.length>0){let n=H2();e.content[0].text=`\u26A0\uFE0F context-mode v${Jr} outdated \u2192 v${Yr} available. Upgrade: ${n}
542
+ FROM session_events`).get();p&&(o+=Number(p.data_bytes??0),i+=Number(p.bytes_avoided??0),a+=Number(p.bytes_returned??0));try{let f=h.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();f?.bytes&&(c+=Number(f.bytes))}catch{}}}finally{h.close()}}catch{}}let u=0;t.sessionId&&t.contentDbPath&&(u=w2(t.sessionId,t.contentDbPath,{loadDatabase:t.loadDatabase}),i+=u);let d=Math.floor((o+i+c)/4);return{eventDataBytes:o,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,contentBytes:u,totalSavedTokens:d}}function $2(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(!Kr(t.sessionsDir))return n;let s=[];try{s=Co(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=Mt(t.sessionsDir,d);try{let m=new o(l,{readonly:!0});try{let h=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();h&&(n.eventCount+=Number(h.cnt??0),n.dataBytes+=Number(h.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let f=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f<n.firstMs&&(n.firstMs=f)}if(p?.mx){let f=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(f)&&f>n.lastMs&&(n.lastMs=f)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let f of p)f.p&&i.add(f.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let f of p)f.s&&a.add(f.s)}catch{}}finally{m.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function fl(t){let e=S2({home:t?.home}),r=t?.loadDatabase??nt,n={...E2,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},s=[],o=0,i=0,a=0;for(let c of e){if(!Kr(c.sessionsDir))continue;let u=$2(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 dl(t){return T2[t]??t}function st(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 P2(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 ul(t){if(!t)return!1;try{return Intl.DateTimeFormat.supportedLocalesOf(t).length===0?!1:(new Intl.DateTimeFormat(t),!0)}catch{return!1}}function R2(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(e&&!ul(e)&&(e=""),!e){if(process.platform==="darwin"){try{let n=_2("defaults",["read","-g","AppleLocale"],{encoding:"utf8",timeout:500}).trim();n&&(e=n.replace(/_/g,"-"))}catch{}e&&!ul(e)&&(e="")}if(!e&&(t.LC_TIME||t.LANG)){let n=(t.LC_TIME||t.LANG||"").split(".")[0];n&&(e=n.replace(/_/g,"-")),e&&!ul(e)&&(e="")}if(!e)try{e=new Intl.DateTimeFormat().resolvedOptions().locale}catch{e="en-US"}}let r=t.CONTEXT_MODE_TZ??"";if(!r)try{r=new Intl.DateTimeFormat().resolvedOptions().timeZone}catch{r="UTC"}return ul(e)||(e="en-US"),{locale:e,tz:r||"UTC"}}function D$(t){let e=ml();return e?t===e?"~":t.startsWith(e+v2)?"~"+t.slice(e.length):t:t}function C2(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,s=(f,g=2)=>f.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),m=(e*1.25/1e6).toFixed(2),h=(e*.8/1e6).toFixed(2),p=[];return p.push(` $${s(n)} of Opus 4 tokens your team didn't burn.`),p.push(` context-mode kept ${st(t)} out of context \u2014 that's ${o} months of Cursor Pro paid for itself.`),c>0&&u>0&&(p.push(""),p.push(` Scale across a 10-dev team and that's ~$${u.toLocaleString("en-US")}/year saved.`)),p.push(""),p.push(" (Opus rates shown for context. On cheaper models the dollar number drops; the savings ratio holds.)"),p}function O2(t){let{conversation:e,lifetime:r,multiAdapter:n,realBytes:s,cwd:o,locale:i,tz:a,now:c,version:u,latestVersion:d}=t,l=[],m=e.events*F$,h=Math.round((e.snapshotBytes??0)/4),p=m+h,f=s?.conversation?.totalSavedTokens??0,g=Math.max(p,f),y=(r?.totalEvents??0)*F$,b=Math.round((r?.rescueBytes??0)/4),_=y+b,S=s?.lifetime?.totalSavedTokens??0,v=Math.max(_,S),P=s?.lifetime?.bytesReturned??0,T=s?.lifetime?.bytesAvoided??0,$=P+T>0?Math.max(1,Math.floor(P/4)):Math.max(1,Math.round(v*.02)),D=n?.totalBytes&&n.totalBytes>0?n.totalBytes:v*4,R=s?.conversation?s.conversation.eventDataBytes+s.conversation.bytesAvoided+s.conversation.snapshotBytes:g*4,C=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`,L=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,X=L>0?Math.max(1,Math.round((c-L)/864e5)):0,fe=n?.totalSessions??r?.totalSessions??1,it=n?.perAdapter.filter(Ue=>Ue.isReal).length??0,pt;if(n&&it>=2)pt=`across ${it} AI tools`;else if(n&&it===1){let Ue=n.perAdapter.find(sr=>sr.isReal);pt=`in ${Ue?dl(Ue.name):"Claude Code"}`}else pt="in Claude Code";X>0?l.push(` Across ${X} days you ran ${yr(fe)} conversations ${pt}.`):l.push(` You ran ${yr(fe)} conversations ${pt}.`);let nr=X>0?D/X:0;l.push(` context-mode kept ${st(D)} out of your context window \u2014 about ${st(nr)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let On=e.firstEventMs&&e.firstEventMs>0?M$(e.firstEventMs,i,a):"";if(On?l.push(` This conversation started ${On} in ${D$(o)}.`):l.push(` This conversation lives in ${D$(o)}.`),l.push(` ${C}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ue=e.lastRescueMs&&e.lastRescueMs>0?M$(e.lastRescueMs,i,a):"",sr=Math.round(e.snapshotBytes/1024);Ue?l.push(` On ${Ue}, /compact fired \u2014 ${sr} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${sr} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let Do=s?.conversation,Sa=Do?.bytesAvoided??0,Ol=Do?.bytesReturned??0,Il=Do?.eventDataBytes??0;if(Sa+Ol+Il>0){let Ue=Sa+Ol+Il,sr=Math.max(1,Ol+Il),or=Math.max(1,Math.floor(Ue/4)),Dr=Math.max(1,Math.floor(sr/4)),Al=Rn(or,or,32),NT=Rn(Dr,or,32),DT=(1-Dr/or)*100,MT=Math.max(1,Math.round(or/Dr));l.push(` Without context-mode ${st(Ue).padStart(8)} ${Al} ${yr(or).padStart(7)} tokens`),l.push(` With context-mode ${st(sr).padStart(8)} ${NT} ${yr(Dr).padStart(7)} tokens`),l.push(` ${DT.toFixed(0)}% kept out of context \xB7 your AI ran ${MT}\xD7 longer before /compact fired`),l.push("")}if(e.byDay&&e.byDay.length>0){let Ue=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;l.push(` How that ${st(R)} built up \u2014 ${Ue} days, ${e.byDay.length} active:`),l.push(""),l.push(...A2(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 CT=e.byCategory.reduce((Ue,sr)=>Ue+sr.count,0).toLocaleString(i);l.push(` ${CT} things \u2014 files, errors, decisions, agent runs:`),l.push("");let OT=e.byCategory[0]?.count??1;for(let Ue of e.byCategory)l.push(` ${Ue.label.padEnd(26)} ${String(Ue.count).padStart(5)} ${Rn(Ue.count,OT,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let c_=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",u_=L>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(L)):"",l_=r?.distinctProjects??0,IT=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${st(R)} kept out \xB7 ${e.events.toLocaleString(i)} captures${c_?` \xB7 started ${c_}`:""}.`),l.push(` All your work: ${st(D)} kept out \xB7 ${IT.toLocaleString(i)} captures across ${l_} project${l_===1?"":"s"}${u_?` \xB7 since ${u_}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...C2(D,v,X)),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 Ue=Object.entries(r.autoMemoryByPrefix).sort((or,Dr)=>Dr[1]-or[1]),sr=Ue.length>0?Ue[0][1]:1;for(let[or,Dr]of Ue){let Al=q$[or]??or;l.push(` ${Al.padEnd(26)} ${String(Dr).padStart(2)} ${Rn(Dr,sr,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"&&H$(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),I2(l)}function I2(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 A2(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,h)=>m.ms-h.ms),s=n[0],o=n[n.length-1],i=Math.max(1,o.ms-s.ms),a=n[0];for(let m of n)m.count>a.count&&(a=m);let c=56,u=Array.from({length:c},()=>"\u2500");for(let m of n){let h=Math.round((m.ms-s.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[h]=p}let d=m=>{let h=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(h.find(g=>g.type==="month")?.value??"").toLowerCase(),f=h.find(g=>g.type==="day")?.value??"";return`${p} ${f}`},l=[];l.push(` ${d(s.ms)} ${u.join("")} ${d(o.ms)}`),l.push("");for(let m of n){let h=d(m.ms).padEnd(7),p=`${m.count} captures`,f=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";l.push(` ${h} ${p}${f}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function M$(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(m=>m.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 yr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function pl(t){return`$${((Number.isFinite(t)&&t>0?t:0)*hl).toFixed(2)}`}function Rn(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 j$(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(f=>f.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 f=i>=2?" everywhere":"";s.push(` All your work${f} \xB7 ${yr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${yr(c)} conversations`)}else{s.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let f=c===0&&r>0?1:c,g=f===1?"1 session":`${yr(f)} sessions`,y=a*256+r;s.push(` ${yr(a)} events \xB7 ${g} \xB7 ~${pl(y)} saved lifetime`)}s.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,f])=>f>0).map(([f,g])=>({category:f,count:g,label:ll[f]||f})).sort((f,g)=>g.count-f.count):l=(t.by_category??[]).filter(f=>f&&f.count>0);let m=l.slice(0,n),h=m.length>0?m[0].count:1;for(let f of m)s.push(` ${f.label.padEnd(26)} ${String(f.count).padStart(5)} ${Rn(f.count,h,30)}`);let p=Math.max(0,l.length-n);return p>0&&s.push(` ... ${p} more categor${p===1?"y":"ies"}`),s}function z$(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=q$[s]??s;e.push(` ${i.padEnd(26)} ${String(o).padStart(2)} ${Rn(o,n,20)}`)}return e}function L$(t,e){let r=[],n=pl(t),s=(e?.totalEvents??0)*256+t,o=pl(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 U$(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?yr(u.eventCount):"\u2014",m=st(u.dataBytes),h=st(d);n.push(` ${dl(u.name).padEnd(s)}${l.padStart(o)}${m.padStart(i)}${h.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let s=r.map(o=>dl(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 gl(t,e,r,n){let s=[],o=P2(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,d=n?.multiAdapter,l=d?.perAdapter.filter(P=>P.isReal).length??0;if(d&&l>0){let P=d.totalSessions||i?.totalSessions||0,T=i?.firstEventMs??0,$=T>0?Math.max(1,Math.round((Date.now()-T)/864e5)):0,D=$>0?`Across ${$} day${$===1?"":"s"} `:"",R=P>0?`you ran ${yr(P)} conversation${P===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?dl(L.name):"Claude Code"}`}s.push(`${D}${R}${C}.`),s.push("")}if(c&&c.events>0){s.length>0&&(s.length=0);let P=R2(),T=n?.cwd??process.cwd(),$=n?.now??Date.now(),D=n?.locale??P.locale,R=n?.tz??P.tz;return s.push(...O2({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:T,locale:D,tz:R,now:$,version:e,latestVersion:r})),s.join(`
543
+ `)}let m=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),h=t.savings.total_bytes_returned,p=t.savings.total_calls,f=m+h,g=f>0?m/f*100:0,y=Math.round(m/4),b=h>0?Math.max(1,Math.round(f/Math.max(h,1))):0;if(m===0){s.push(`context-mode ${o} ${p} calls`),s.push(""),p===0?s.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):s.push(`${st(h)} entered context | 0 tokens saved`),s.push(...j$(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:0})),s.push(...U$(d)),s.push(...z$(i)),s.push(...L$(0,i)),s.push("");let P=e?`v${e}`:"context-mode";return s.push(P),e&&r&&r!=="unknown"&&H$(r,e)&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
544
+ `)}s.push(`${yr(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${o} \xB7 ~${pl(y)} saved (Opus)`),s.push(""),s.push(`Without context-mode |${Rn(f,f)}| ${st(f)}`),s.push(`With context-mode |${Rn(h,f)}| ${st(h)}`),s.push(""),b>=2?s.push(`${st(m)} kept out of your conversation \u2014 ${b}\xD7 longer sessions before compact.`):s.push(`${st(m)} kept out of your conversation. Never entered context.`),s.push("");let _=[`${p} calls`];t.cache&&t.cache.hits>0&&_.push(`${t.cache.hits} cache hits (+${st(t.cache.bytes_saved)})`),s.push(_.join(" \xB7 "));let S=t.savings.by_tool.filter(P=>P.calls>0);if(S.length>=2){s.push("");let P=S.map(T=>{let $=T.context_kb*1024,D=g<100?$/(1-g/100):$,R=Math.max(0,D-$);return{...T,returnedBytes:$,estimatedSaved:R}}).sort((T,$)=>$.estimatedSaved-T.estimatedSaved);for(let T of P){let $=T.tool.length>22?T.tool.slice(0,19)+"...":T.tool;s.push(` ${$.padEnd(22)} ${String(T.calls).padStart(4)} calls ${st(T.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let P=a.filter(T=>T.median_concurrency!=null&&(T.max_concurrency??1)>1);if(P.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 T of P){let $=T.tool_name.replace(/^mcp__.*?__/,"");s.push(` ${$.padEnd(22)} ${T.calls} batches \xB7 ${T.median_concurrency} typical, ${T.max_concurrency} peak`)}}}s.push(...j$(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:y})),s.push(...U$(d)),s.push(...z$(i)),s.push(...L$(y,i)),s.push("");let v=e?`v${e}`:"context-mode";return s.push(v),e&&r&&r!=="unknown"&&r!==e&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
545
+ `)}var ll,x2,Oo,E2,q$,T2,hl,F$,V$=x(()=>{"use strict";Pn();rn();ll={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"},x2={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"},Oo=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)})),h=((Date.now()-e.sessionStart)/6e4).toFixed(1),p;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)));p={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:X,total_with_cache:C,total_savings_ratio:L}}let f=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),b=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,_=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),S=_?!_.consumed:!1,v=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),P=new Map;for(let C of v){P.has(C.category)||P.set(C.category,new Set);let L=P.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 T=g.map(C=>({category:C.category,count:C.cnt,label:ll[C.category]||C.category,preview:P.get(C.category)?Array.from(P.get(C.category)).join(", "):"",why:x2[C.category]||"Survives context resets"})),$=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),R=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(C=>C.cnt>0).map(C=>({category:C.category,count:C.cnt,label:ll[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:p,session:{id:n,uptime_min:h},continuity:{total_events:f,by_category:T,compact_count:b,resume_ready:S},projectMemory:{total_events:$.cnt,session_count:$.sessions,by_category:R}}}};E2={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};q$={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},T2={"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"};hl=15/1e6;F$=256});var gT={};Ie(gT,{browserOpenArgv:()=>hT,buildBatchNodeOptionsPrefix:()=>dT,buildFetchCode:()=>fT,classifyIp:()=>ya,currentAttribution:()=>ws,extractSnippet:()=>n_,formatBatchQueryResults:()=>lT,killProcessOnPort:()=>o_,openBrowserSync:()=>Yy,positionsFromHighlight:()=>uT,resolveSessionIdFromSessionDB:()=>oT,runBatchCommands:()=>pT});import{createRequire as nT}from"node:module";import{existsSync as ze,unlinkSync as fa,readdirSync as N2,readFileSync as Xy,writeFileSync as Qy,renameSync as D2,rmSync as xl,mkdirSync as ha,cpSync as M2,statSync as W$,symlinkSync as j2,lstatSync as z2}from"node:fs";import{execSync as G$,spawnSync as sT}from"node:child_process";import{join as Oe,dirname as tr,resolve as dt,sep as L2,isAbsolute as F2}from"node:path";import{fileURLToPath as U2}from"node:url";import{homedir as $l,tmpdir as e_,cpus as H2}from"node:os";import{request as Z2}from"node:https";function ws(){let t=process.env.CLAUDE_SESSION_ID??oT();if(t)return{sessionId:t}}function oT(t){let e=Date.now();if(!t?.bypassCache&&yl&&e-yl.checkedAt<2e3)return yl.sid;try{let r=t?.projectDir??process.env.CLAUDE_PROJECT_DIR??process.env.CONTEXT_MODE_PROJECT_DIR;if(!r)return;let n=t?.sessionsDir??ot(),s=ca({projectDir:r,sessionsDir:n});if(!ze(s))return;let o=nt(),i=new o(s,{readonly:!0,fileMustExist:!0});try{let c=i.prepare("SELECT session_id FROM session_events ORDER BY created_at DESC LIMIT 1").get()?.session_id;return c&&(yl={sid:c,checkedAt:e}),c}finally{try{i.close()}catch{}}}catch{return}}function B2(t){try{let e=ot();if(!ze(e))return;let r=N2(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let s=Oe(e,n);try{t.index({path:s,source:"session-events",attribution:ws()}),fa(s)}catch{}}}catch{}}function Ky(){return Ze()}async function q2(){if(Cn)return Cn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(on(),Ka)),e=It();return await t(e.platform)}catch{return null}}function ot(){if(Cn)return Cn.getSessionDir();try{let e=It(),r=qo(e.platform);if(r){let n=Oe($l(),...r);r.length===1&&r[0]===".claude"?n=Ky():r.length===1&&r[0]===".codex"&&(n=La());let s=Oe(n,"context-mode","sessions");return ha(s,{recursive:!0}),s}}catch{}let t=Oe(Ky(),"context-mode","sessions");return ha(t,{recursive:!0}),t}function vr(){let t,e;try{let r=It().platform;e=r,r==="claude-code"&&(t=Oe($l(),".claude","projects"))}catch{}return A$({env:process.env,cwd:process.cwd(),pwd:process.env.PWD,transcriptsRoot:t,transcriptMaxAgeMs:300*1e3,strictPlatform:e})}function V2(t){return F2(t)?t:dt(vr(),t)}function ga(){return ca({projectDir:vr(),sessionsDir:ot()})}function Sl(){let t=Oe(tr(ot()),"content");return ha(t,{recursive:!0}),g$({projectDir:vr(),contentDir:t})}function Es(){if(!_r){let t=Sl();_r=new nl(t),_r.setDenyChecker(e=>{try{let r=vr(),n=Ay("Read",r);return Dy(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=tr(Sl());Ry(e,14),_r.cleanupStaleSources(14);let r=Oe($l(),".context-mode","content");ze(r)&&Ry(r,0)}catch{}Py()}return B2(_r),_r}async function J$(){return new Promise(t=>{let e=Z2("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 K2(){let t=Cn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function J2(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 Y2(){return!Xr||Xr==="unknown"?!1:J2(Xr,Yr)}function X2(){if(!Y2())return!1;let t=Date.now();if(_l>=W2){if(t-K$<G2)return!1;_l=0}return _l===0&&(K$=t),_l++,!0}function Q2(){if(!Y$){Y$=!0;try{let t=Ze(),e=dt(t,"plugins","installed_plugins.json");if(!ze(e))return;let r=JSON.parse(Xy(e,"utf-8")),n=dt(t,"plugins","cache"),s=ze(dt(jt,"package.json"))?jt:tr(jt);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)||!dt(c).startsWith(n+L2))continue;try{z2(c).isSymbolicLink()&&fa(c)}catch{}let u=tr(c);ze(u)||ha(u,{recursive:!0}),ze(s)&&j2(s,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(Q2(),X2()&&e.content.length>0){let n=K2();e.content[0].text=`\u26A0\uFE0F context-mode v${Yr} outdated \u2192 v${Xr} available. Upgrade: ${n}
542
546
 
543
- `+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,gl(),setImmediate(()=>_$(pa(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>m$({sessionDbPath:pa(),toolName:t,bytesReturned:r})),e}function br(t,e="unknown"){oe.bytesIndexed+=t,gl(),t>0&&setImmediate(()=>f$({sessionDbPath:pa(),source:e,bytesAvoided:t}))}function eT(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`;return Oe(ot(),`stats-${t}.json`)}function gl(){let t=Date.now();if(!(t-Zy<W2)){Zy=t;try{let e=Object.values(oe.bytesReturned).reduce((l,m)=>l+m,0),r=Object.values(oe.calls).reduce((l,m)=>l+m,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=pl?.tokens??0;if(!pl||t-pl.computedAt>K2)try{a=(ca({sessionsDir:ot()})?.totalEvents??0)*J2,pl={tokens:a,computedAt:t}}catch{}let c={schemaVersion:G2,version:Jr,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*cl).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*cl).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=eT(),d=`${u}.tmp`;Vy(d,JSON.stringify(c)),P2(d,u)}catch{}}}function Ky(t,e){try{let r=Ey(process.env.CLAUDE_PROJECT_DIR),n=Ty(t,r);if(n.decision==="deny")return W(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function tT(t,e,r){try{let n=t$(t,e);if(n.length===0)return null;let s=Ey(process.env.CLAUDE_PROJECT_DIR);for(let o of n){let i=Ty(o,s);if(i.decision==="deny")return W(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 rT(t,e){try{let r=vr(),n=$y("Read",r),s=Py(t,n,process.platform==="win32",r);if(s.denied)return W(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${s.matchedPattern}`}],isError:!0})}catch{}return null}function nT(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===Q2){for(e.push(r),n++;n<t.length&&t[n]!==eU;)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 nT(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 m=d.indexOf(l);for(;m!==-1;)s.push(m),m=d.indexOf(l,m+1)}}if(s.length===0)return t.slice(0,r)+`
547
+ `+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,kl(),setImmediate(()=>w$(ga(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>b$({sessionDbPath:ga(),toolName:t,bytesReturned:r})),e}function br(t,e="unknown"){oe.bytesIndexed+=t,kl(),t>0&&setImmediate(()=>v$({sessionDbPath:ga(),source:e,bytesAvoided:t}))}function iT(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`;return Oe(ot(),`stats-${t}.json`)}function kl(){let t=Date.now();if(!(t-Jy<eU)){Jy=t;try{let e=Object.values(oe.bytesReturned).reduce((l,m)=>l+m,0),r=Object.values(oe.calls).reduce((l,m)=>l+m,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=bl?.tokens??0;if(!bl||t-bl.computedAt>rU)try{a=(pa({sessionsDir:ot()})?.totalEvents??0)*nU,bl={tokens:a,computedAt:t}}catch{}let c={schemaVersion:tU,version:Yr,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*hl).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*hl).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=iT(),d=`${u}.tmp`;Qy(d,JSON.stringify(c)),D2(d,u)}catch{}}}function r_(t,e){try{let r=Iy(process.env.CLAUDE_PROJECT_DIR),n=Ny(t,r);if(n.decision==="deny")return W(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function aT(t,e,r){try{let n=a$(t,e);if(n.length===0)return null;let s=Iy(process.env.CLAUDE_PROJECT_DIR);for(let o of n){let i=Ny(o,s);if(i.decision==="deny")return W(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 cT(t,e){try{let r=vr(),n=Ay("Read",r),s=Dy(t,n,process.platform==="win32",r);if(s.denied)return W(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${s.matchedPattern}`}],isError:!0})}catch{}return null}function uT(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===iU){for(e.push(r),n++;n<t.length&&t[n]!==aU;)r++,n++;n<t.length&&n++}else r++,n++;return e}function n_(t,e,r=1500,n){if(t.length<=r)return t;let s=[];if(n)for(let u of uT(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 m=d.indexOf(l);for(;m!==-1;)s.push(m),m=d.indexOf(l,m+1)}}if(s.length===0)return t.slice(0,r)+`
544
548
  \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(`
545
549
 
546
- `)}function sT(t,e,r,n=80*1024){let s=[],o=0;for(let i of e){if(o>n){s.push(`## ${i}
550
+ `)}function lT(t,e,r,n=80*1024){let s=[],o=0;for(let i of e){if(o>n){s.push(`## ${i}
547
551
  (output cap reached \u2014 use ctx_search(queries: ["${i}"]) for details)
548
- `);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 tU(t){return`'${t.replace(/'/g,"'\\''")}'`}function rU(t){return`'${t.replace(/'/g,"''")}'`}function oT(t,e){let r=`--require ${e}`,n=t.toLowerCase(),s=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${rU(r)}; `:s==="cmd"||s==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${tU(r)} `}function V$(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}
552
+ `);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=n_(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 cU(t){return`'${t.replace(/'/g,"'\\''")}'`}function uU(t){return`'${t.replace(/'/g,"''")}'`}function dT(t,e){let r=`--require ${e}`,n=t.toLowerCase(),s=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${uU(r)}; `:s==="cmd"||s==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${cU(r)} `}function X$(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}
549
553
 
550
554
  ${n}
551
- `}async function iT(t,e,r){let{timeout:n,concurrency:s,nodeOptsPrefix:o,onFsBytes:i}=e;if(s<=1){let l=[],m=Date.now(),h=!1;for(let p=0;p<t.length;p++){let f=t[p],g;if(n!==void 0){let b=Date.now()-m,_=n-b;if(_<=0){l.push(`# ${f.label}
555
+ `}async function pT(t,e,r){let{timeout:n,concurrency:s,nodeOptsPrefix:o,onFsBytes:i}=e;if(s<=1){let l=[],m=Date.now(),h=!1;for(let p=0;p<t.length;p++){let f=t[p],g;if(n!==void 0){let b=Date.now()-m,_=n-b;if(_<=0){l.push(`# ${f.label}
552
556
 
553
557
  (skipped \u2014 batch timeout exceeded)
554
- `),h=!0;continue}g=_}let y=await r.execute({language:"shell",code:`${o}${f.command} 2>&1`,timeout:g});if(l.push(V$(f.label,y.stdout,i)),y.timedOut){h=!0;for(let b=p+1;b<t.length;b++)l.push(`# ${t[b].label}
558
+ `),h=!0;continue}g=_}let y=await r.execute({language:"shell",code:`${o}${f.command} 2>&1`,timeout:g});if(l.push(X$(f.label,y.stdout,i)),y.timedOut){h=!0;for(let b=p+1;b<t.length;b++)l.push(`# ${t[b].label}
555
559
 
556
560
  (skipped \u2014 batch timeout exceeded)
557
- `);break}}return{outputs:l,timedOut:h}}let a=t.map(l=>({run:async()=>{let m=await r.execute({language:"shell",code:`${o}${l.command} 2>&1`,timeout:n}),h=V$(l.label,m.stdout,i);return{output:m.timedOut?h.replace(/\n$/,"")+`
561
+ `);break}}return{outputs:l,timedOut:h}}let a=t.map(l=>({run:async()=>{let m=await r.execute({language:"shell",code:`${o}${l.command} 2>&1`,timeout:n}),h=X$(l.label,m.stdout,i);return{output:m.timedOut?h.replace(/\n$/,"")+`
558
562
  (timed out after ${n??"?"}ms)
559
- `:h,timedOut:!!m.timedOut}}})),{settled:c}=await fy(a,{concurrency:s}),u=new Array(t.length),d=!1;for(let l=0;l<c.length;l++){let m=c[l];if(m.status==="fulfilled")u[l]=m.value.output,m.value.timedOut&&(d=!0);else{let h=m.reason instanceof Error?m.reason.message:String(m.reason);u[l]=`# ${t[l].label}
563
+ `:h,timedOut:!!m.timedOut}}})),{settled:c}=await xy(a,{concurrency:s}),u=new Array(t.length),d=!1;for(let l=0;l<c.length;l++){let m=c[l];if(m.status==="fulfilled")u[l]=m.value.output,m.value.timedOut&&(d=!0);else{let h=m.reason instanceof Error?m.reason.message:String(m.reason);u[l]=`# ${t[l].label}
560
564
 
561
565
  (executor error: ${h})
562
- `}}return{outputs:u,timedOut:d}}function aT(t,e){let r=ws();br(Buffer.byteLength(t));let n=r.index({content:t,source:e,attribution:ks()});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
563
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function Co(t,e,r,n=5){let s=t.split(`
564
- `).length,o=Buffer.byteLength(t),i=ws(),a=i.indexPlainText(t,r,void 0,ks()),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(`
566
+ `}}return{outputs:u,timedOut:d}}function mT(t,e){let r=Es();br(Buffer.byteLength(t));let n=r.index({content:t,source:e,attribution:ws()});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
567
+ Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function Io(t,e,r,n=5){let s=t.split(`
568
+ `).length,o=Buffer.byteLength(t),i=Es(),a=i.indexPlainText(t,r,void 0,ws()),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(`
565
569
  `)}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 m=l.content.split(`
566
570
  `)[0].slice(0,120);d.push(` - ${l.title}: ${m}`)}return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),d.join(`
567
- `)}function Yy(t){if(typeof t=="string")try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t}function sU(t){let e=Yy(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function oU(){return Fy||(Fy=Y$(import.meta.url).resolve("turndown")),Fy}function iU(){return Uy||(Uy=Y$(import.meta.url).resolve("turndown-plugin-gfm")),Uy}function cT(t,e){let r=JSON.stringify(oU()),n=JSON.stringify(iU()),s=JSON.stringify(e),o=ma.toString(),i=ma.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${o};`:`var ${i} = ${o};
571
+ `)}function s_(t){if(typeof t=="string")try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t}function dU(t){let e=s_(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function pU(){return Wy||(Wy=nT(import.meta.url).resolve("turndown")),Wy}function mU(){return Gy||(Gy=nT(import.meta.url).resolve("turndown-plugin-gfm")),Gy}function fT(t,e){let r=JSON.stringify(pU()),n=JSON.stringify(mU()),s=JSON.stringify(e),o=ya.toString(),i=ya.name||"classifyIp",a=i==="classifyIp"?`var classifyIp = ${o};`:`var ${i} = ${o};
568
572
  var classifyIp = ${i};`,c=process.env.CTX_FETCH_STRICT==="1";return`
569
573
  const TurndownService = require(${r});
570
574
  const { gfm } = require(${n});
@@ -790,20 +794,20 @@ async function main() {
790
794
  emit('text', text);
791
795
  }
792
796
  main();
793
- `}async function cU(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=ma(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 ma(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?ma(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 uU(t,e,r){let n=await cU(t);if(n)return n;if(!r){let o=ws(),i=ky(e,t),a=o.getSourceMeta(i);if(a){let c=new Date(a.indexedAt+"Z"),u=Date.now()-c.getTime();if(u<aU){let d=Math.floor(u/36e5),l=Math.floor(u/(60*1e3)),m=d>0?`${d}h ago`:l>0?`${l}m ago`:"just now",h=a.chunkCount*1600;return{kind:"cached",label:a.label,chunkCount:a.chunkCount,estimatedBytes:h,ageStr:m}}}}let s=Oe(Wy(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let o=cT(t,s),i=await ha.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=qy(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{fl(s)}catch{}}}function lU(t){let e=ws(),r=ky(t.source,t.url),n=ks(),s;t.header==="__CM_CT__:json"?s=e.indexJSON(t.markdown,r,void 0,n):t.header==="__CM_CT__:text"?s=e.indexPlainText(t.markdown,r,void 0,n):s=e.index({content:t.markdown,source:r,attribution:n}),br(Buffer.byteLength(t.markdown));let o=t.markdown.length>K$?t.markdown.slice(0,K$)+`
797
+ `}async function hU(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=ya(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 ya(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?ya(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 gU(t,e,r){let n=await hU(t);if(n)return n;if(!r){let o=Es(),i=Cy(e,t),a=o.getSourceMeta(i);if(a){let c=new Date(a.indexedAt+"Z"),u=Date.now()-c.getTime();if(u<fU){let d=Math.floor(u/36e5),l=Math.floor(u/(60*1e3)),m=d>0?`${d}h ago`:l>0?`${l}m ago`:"just now",h=a.chunkCount*1600;return{kind:"cached",label:a.label,chunkCount:a.chunkCount,estimatedBytes:h,ageStr:m}}}}let s=Oe(e_(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let o=fT(t,s),i=await ba.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=Xy(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{xl(s)}catch{}}}function yU(t){let e=Es(),r=Cy(t.source,t.url),n=ws(),s;t.header==="__CM_CT__:json"?s=e.indexJSON(t.markdown,r,void 0,n):t.header==="__CM_CT__:text"?s=e.indexPlainText(t.markdown,r,void 0,n):s=e.index({content:t.markdown,source:r,attribution:n}),br(Buffer.byteLength(t.markdown));let o=t.markdown.length>tT?t.markdown.slice(0,tT)+`
794
798
 
795
- \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:s.label,totalChunks:s.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:o}}function J$(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function uT(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 By(t,e=process.platform,r=X$){let n=uT(t,e),s=[];for(let{cmd:o,args:i}of n)try{let a=r(o,i,{stdio:"ignore",timeout:ua});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 Xy(t,e=process.platform,r=X$){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:ua});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],m=u[2],h=u[u.length-1];d==="TCP"&&l.endsWith(o)&&(m!=="0.0.0.0:0"&&m!=="[::]:0"||/^\d+$/.test(h)&&i.add(h))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:ua});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:ua});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:ua});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 dU(){try{let{startupSiblingSweep:a}=await Promise.resolve().then(()=>(Wl(),T_)),c=await a();c.totalKilled>0&&console.error(`Reaped ${c.totalKilled} stale sibling MCP server(s) (SIGTERM: ${c.terminatedBySigterm}, SIGKILL: ${c.terminatedBySigkill})`)}catch{}let t=xy();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Wy():"/tmp",r=Oe(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{ha.cleanupBackgrounded(),_r&&_r.close();try{la(Gy)}catch{}try{la(r)}catch{}if(Kr&&Kr.pid&&!Kr.killed)try{Kr.kill("SIGTERM")}catch{}},s=async()=>{try{Zy=0,gl()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()});let o=s$({onShutdown:()=>s()});try{let a=Ge.server,c=a._onrequest;typeof c=="function"&&(a._onrequest=function(...u){try{o.recordActivity()}catch{}return c.apply(this,u)})}catch{}let i=new Bu;await Ge.connect(i);try{Vy(r,String(process.pid))}catch{}try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(Un(),Wa)),u=Ge.server.getClientVersion(),d=a(u??void 0);Pn=await c(d.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${d.platform}`)}catch{}try{let a=b$(pa());if(a){for(let[c,u]of Object.entries(a.calls))oe.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))oe.bytesReturned[c]=u;a.sessionStart>0&&(oe.sessionStart=a.sessionStart)}}catch{}B$().then(a=>{a!=="unknown"&&(Yr=a)}),setInterval(()=>{B$().then(a=>{a!=="unknown"&&(Yr=a)})},3600*1e3).unref(),setInterval(()=>gl(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Jr} running on stdio`),console.error(`Detected runtimes:
796
- ${Ta(fa)}`),Cn()||(console.error(`
797
- Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var Mt,Jr,fa,ml,Ge,ha,Gy,_r,ll,Pn,Kr,oe,Yr,dl,Z$,F2,U2,q$,W2,G2,K2,J2,Zy,pl,Y2,X2,Q2,eU,yl,_l,Ss,Ly,nU,W$,G$,Fy,Uy,aU,K$,ua,dT=x(()=>{"use strict";xE();EE();ly();my();ME();JE();YE();r$();Ra();n$();o$();oa();p$();g$();v$();$$();Sr();Un();fd();Zl();tn();P$();$n();F$();ds();Mt=er(N2(import.meta.url)),Jr=(()=>{for(let t of["../package.json","./package.json"]){let e=dt(Mt,t);if(je(e))try{return JSON.parse(qy(e,"utf8")).version}catch{}}return"unknown"})();process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
799
+ \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:s.label,totalChunks:s.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:o}}function rT(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function hT(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 Yy(t,e=process.platform,r=sT){let n=hT(t,e),s=[];for(let{cmd:o,args:i}of n)try{let a=r(o,i,{stdio:"ignore",timeout:ma});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 o_(t,e=process.platform,r=sT){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:ma});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],m=u[2],h=u[u.length-1];d==="TCP"&&l.endsWith(o)&&(m!=="0.0.0.0:0"&&m!=="[::]:0"||/^\d+$/.test(h)&&i.add(h))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:ma});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:ma});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:ma});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 _U(){try{let{startupSiblingSweep:a}=await Promise.resolve().then(()=>(Gd(),ev)),c=await a();c.totalKilled>0&&console.error(`Reaped ${c.totalKilled} stale sibling MCP server(s) (SIGTERM: ${c.terminatedBySigterm}, SIGKILL: ${c.terminatedBySigkill})`)}catch{}let t=Py();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?e_():"/tmp",r=Oe(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{ba.cleanupBackgrounded(),_r&&_r.close();try{fa(t_)}catch{}try{fa(r)}catch{}if(Jr&&Jr.pid&&!Jr.killed)try{Jr.kill("SIGTERM")}catch{}},s=async()=>{try{Jy=0,kl()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()});let o=l$({onShutdown:()=>s()});try{let a=Ge.server,c=a._onrequest;typeof c=="function"&&(a._onrequest=function(...u){try{o.recordActivity()}catch{}return c.apply(this,u)})}catch{}let i=new Ju;await Ge.connect(i);try{Qy(r,String(process.pid))}catch{}try{let{detectPlatform:a,getAdapter:c}=await Promise.resolve().then(()=>(on(),Ka)),u=Ge.server.getClientVersion(),d=a(u??void 0);Cn=await c(d.platform),u&&console.error(`MCP client: ${u.name} v${u.version} \u2192 ${d.platform}`)}catch{}try{let a=E$(ga());if(a){for(let[c,u]of Object.entries(a.calls))oe.calls[c]=u;for(let[c,u]of Object.entries(a.bytesReturned))oe.bytesReturned[c]=u;a.sessionStart>0&&(oe.sessionStart=a.sessionStart)}}catch{}J$().then(a=>{a!=="unknown"&&(Xr=a)}),setInterval(()=>{J$().then(a=>{a!=="unknown"&&(Xr=a)})},3600*1e3).unref(),setInterval(()=>kl(),6e4).unref(),process.stdin.isTTY&&(console.error(`Context Mode MCP server v${Yr} running on stdio`),console.error(`Detected runtimes:
800
+ ${Oa(_a)}`),In()||(console.error(`
801
+ Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash")))}var jt,Yr,_a,vl,Ge,ba,t_,_r,yl,Cn,Jr,oe,Xr,_l,K$,W2,G2,Y$,eU,tU,rU,nU,Jy,bl,sU,oU,iU,aU,wl,El,ks,Vy,lU,Q$,eT,Wy,Gy,fU,tT,ma,yT=x(()=>{"use strict";TE();OE();yy();vy();HE();r$();n$();c$();Aa();u$();d$();ua();_$();S$();$$();I$();Sr();on();hd();Yl();rn();N$();Pn();V$();ps();jt=tr(U2(import.meta.url)),Yr=(()=>{for(let t of["../package.json","./package.json"]){let e=dt(jt,t);if(ze(e))try{return JSON.parse(Xy(e,"utf8")).version}catch{}}return"unknown"})();process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
798
802
  `)});process.on("uncaughtException",t=>{process.stderr.write(`[context-mode] uncaughtException: ${t?.message??t}
799
- `)});fa=Ts(),ml=Pa(fa),Ge=new Hu({name:"context-mode",version:Jr});Ge.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Ge.server.setRequestHandler(to,async()=>({prompts:[]}));Ge.server.setRequestHandler(Qs,async()=>({resources:[]}));Ge.server.setRequestHandler(eo,async()=>({resourceTemplates:[]}));ha=new So({runtimes:fa,projectRoot:()=>vr()}),Gy=Oe(Wy(),`cm-fs-preload-${process.pid}.js`);Vy(Gy,`(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){}})();
800
- `);_r=null;Pn=null,Kr=null;oe={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()},Yr=null,dl=0,Z$=0,F2=3,U2=3600*1e3;q$=!1;W2=500,G2=2,K2=3e4,J2=256,Zy=0;Y2=ml.join(", "),X2=Cn()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",Q2="",eU="";Ge.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.${X2} Available: ${Y2}.
803
+ `)});_a=Ps(),vl=Ia(_a),Ge=new Gu({name:"context-mode",version:Yr});Ge.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Ge.server.setRequestHandler(no,async()=>({prompts:[]}));Ge.server.setRequestHandler(to,async()=>({resources:[]}));Ge.server.setRequestHandler(ro,async()=>({resourceTemplates:[]}));ba=new wo({runtimes:_a,projectRoot:()=>vr()}),t_=Oe(e_(),`cm-fs-preload-${process.pid}.js`);Qy(t_,`(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){}})();
804
+ `);_r=null;Cn=null,Jr=null;oe={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()},Xr=null,_l=0,K$=0,W2=3,G2=3600*1e3;Y$=!1;eU=500,tU=2,rU=3e4,nU=256,Jy=0;sU=vl.join(", "),oU=In()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",iU="",aU="";Ge.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.${oU} Available: ${sU}.
801
805
 
802
806
  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.
803
807
 
804
808
  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","csharp"]).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), IO.puts (Elixir), or Console.WriteLine (C#) 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'.
805
809
 
806
- 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=Ky(e,"execute");if(o)return o}else{let o=tT(e,t,"execute");if(o)return o}try{let o=e;(t==="javascript"||t==="typescript")&&(o=`
810
+ 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=r_(e,"execute");if(o)return o}else{let o=aT(e,t,"execute");if(o)return o}try{let o=e;(t==="javascript"||t==="typescript")&&(o=`
807
811
  // FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
808
812
  let __cm_fs=0;
809
813
  process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
@@ -862,18 +866,18 @@ ${e}
862
866
  }
863
867
  __cm_main().catch(e=>{console.error(e);process.exitCode=1});${n?`
864
868
  setInterval(()=>{},2147483647);`:""}
865
- })(typeof require!=='undefined'?require:null);`);let i=await ha.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?W("ctx_execute",{content:[{type:"text",text:`${d}
869
+ })(typeof require!=='undefined'?require:null);`);let i=await ba.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?W("ctx_execute",{content:[{type:"text",text:`${d}
866
870
 
867
871
  _(process backgrounded after ${r}ms \u2014 still running)_`}]}):d?W("ctx_execute",{content:[{type:"text",text:`${d}
868
872
 
869
873
  _(timed out after ${r}ms \u2014 partial output shown above)_`}]}):W("ctx_execute",{content:[{type:"text",text:`Execution timed out after ${r}ms
870
874
 
871
875
  stderr:
872
- ${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:l}=Ry({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(l)>yl?(br(Buffer.byteLength(l)),W("ctx_execute",{content:[{type:"text",text:Co(l,s,d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):Buffer.byteLength(l)>_l?(br(Buffer.byteLength(l)),W("ctx_execute",{content:[{type:"text",text:Co(l,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):W("ctx_execute",{content:[{type:"text",text:l}],isError:d})}let u=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(u)>yl?(br(Buffer.byteLength(u)),W("ctx_execute",{content:[{type:"text",text:Co(u,s,`execute:${t}`)}]})):Buffer.byteLength(u)>_l?W("ctx_execute",aT(u,`execute:${t}`)):W("ctx_execute",{content:[{type:"text",text:u}]})}catch(o){let i=o instanceof Error?o.message:String(o);return W("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});yl=5e3,_l=102400;Ge.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.
876
+ ${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)>wl?(br(Buffer.byteLength(l)),W("ctx_execute",{content:[{type:"text",text:Io(l,s,d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):Buffer.byteLength(l)>El?(br(Buffer.byteLength(l)),W("ctx_execute",{content:[{type:"text",text:Io(l,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):W("ctx_execute",{content:[{type:"text",text:l}],isError:d})}let u=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(u)>wl?(br(Buffer.byteLength(u)),W("ctx_execute",{content:[{type:"text",text:Io(u,s,`execute:${t}`)}]})):Buffer.byteLength(u)>El?W("ctx_execute",mT(u,`execute:${t}`)):W("ctx_execute",{content:[{type:"text",text:u}]})}catch(o){let i=o instanceof Error?o.message:String(o);return W("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});wl=5e3,El=102400;Ge.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.
873
877
 
874
878
  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.
875
879
 
876
- 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","csharp"]).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/Console.WriteLine."),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=rT(t,"ctx_execute_file");if(o)return o;if(e==="shell"){let i=Ky(r,"execute_file");if(i)return i}else{let i=tT(r,e,"execute_file");if(i)return i}try{let i=await ha.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return W("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}=Ry({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(u)>yl?(br(Buffer.byteLength(u)),W("ctx_execute_file",{content:[{type:"text",text:Co(u,s,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>_l?(br(Buffer.byteLength(u)),W("ctx_execute_file",{content:[{type:"text",text:Co(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):W("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)>yl?(br(Buffer.byteLength(a)),W("ctx_execute_file",{content:[{type:"text",text:Co(a,s,`file:${t}`)}]})):Buffer.byteLength(a)>_l?W("ctx_execute_file",aT(a,`file:${t}`)):W("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Ge.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.
880
+ 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","csharp"]).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/Console.WriteLine."),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=cT(t,"ctx_execute_file");if(o)return o;if(e==="shell"){let i=r_(r,"execute_file");if(i)return i}else{let i=aT(r,e,"execute_file");if(i)return i}try{let i=await ba.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return W("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)>wl?(br(Buffer.byteLength(u)),W("ctx_execute_file",{content:[{type:"text",text:Io(u,s,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>El?(br(Buffer.byteLength(u)),W("ctx_execute_file",{content:[{type:"text",text:Io(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):W("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)>wl?(br(Buffer.byteLength(a)),W("ctx_execute_file",{content:[{type:"text",text:Io(a,s,`file:${t}`)}]})):Buffer.byteLength(a)>El?W("ctx_execute_file",mT(a,`file:${t}`)):W("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return W("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});Ge.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.
877
881
 
878
882
  WHEN TO USE:
879
883
  - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
@@ -885,23 +889,23 @@ WHEN TO USE:
885
889
 
886
890
  After indexing, use 'ctx_search' to retrieve specific sections on-demand.
887
891
  When \`path\` is provided, a content hash is stored for automatic stale detection in search results.
888
- 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 W("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let n=rT(e,"ctx_index");if(n)return n}try{let n=e?L2(e):void 0;if(t)br(Buffer.byteLength(t));else if(n)try{let i=await import("fs");br(i.readFileSync(n).byteLength)}catch{}let o=ws().index({content:t,path:n,source:r??n,attribution:ks()});return W("ctx_index",{content:[{type:"text",text:`Indexed ${o.totalChunks} sections (${o.codeChunks} with code) from: ${o.label}
889
- 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 W("ctx_index",{content:[{type:"text",text:`Index error: ${s}`}],isError:!0})}});Ss=0,Ly=Date.now(),nU=6e4,W$=3,G$=8;Ge.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.
892
+ 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 W("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let n=cT(e,"ctx_index");if(n)return n}try{let n=e?V2(e):void 0;if(t)br(Buffer.byteLength(t));else if(n)try{let i=await import("fs");br(i.readFileSync(n).byteLength)}catch{}let o=Es().index({content:t,path:n,source:r??n,attribution:ws()});return W("ctx_index",{content:[{type:"text",text:`Indexed ${o.totalChunks} sections (${o.codeChunks} with code) from: ${o.label}
893
+ 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 W("ctx_index",{content:[{type:"text",text:`Index error: ${s}`}],isError:!0})}});ks=0,Vy=Date.now(),lU=6e4,Q$=3,eT=8;Ge.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.
890
894
 
891
895
  TIPS: 2-4 specific terms per query. Use 'source' to scope results.
892
896
 
893
- 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(Yy,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=ws(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return W("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
897
+ 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(s_,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=Es(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return W("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
894
898
 
895
899
  ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
896
900
  \u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
897
901
  \u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
898
902
  \u2022 ctx_index(content, source) \u2014 manually index text content
899
903
 
900
- 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 W("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-Ly>nU&&(Ss=0,Ly=c),Ss++,Ss>G$)return W("ctx_search",{content:[{type:"text",text:`BLOCKED: ${Ss} search calls in ${Math.round((c-Ly)/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=Ss>W$?1:Math.min(o,2),d=40*1024,l=0,m=[],h=null;if(r==="timeline")try{let g=ot(),y=vr(),b=sa({projectDir:y,sessionsDir:g});je(b)&&(h=new gr({dbPath:b}))}catch{}let p=Pn?.getConfigDir()??Hy();try{for(let g of s){if(l>d){m.push(`## ${g}
904
+ 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 W("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-Vy>lU&&(ks=0,Vy=c),ks++,ks>eT)return W("ctx_search",{content:[{type:"text",text:`BLOCKED: ${ks} search calls in ${Math.round((c-Vy)/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=ks>Q$?1:Math.min(o,2),d=40*1024,l=0,m=[],h=null;if(r==="timeline")try{let g=ot(),y=vr(),b=ca({projectDir:y,sessionsDir:g});ze(b)&&(h=new gr({dbPath:b}))}catch{}let p=Cn?.getConfigDir()??Ky();try{for(let g of s){if(l>d){m.push(`## ${g}
901
905
  (output cap reached)
902
- `);continue}let y;if(r==="timeline"?y=E$({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:h,projectDir:vr(),configDir:p,adapter:Pn??void 0}):y=e.searchWithFallback(g,u,i,a),y.length===0){m.push(`## ${g}
903
- No results found.`);continue}let b=y.map((_,S)=>{let v=_.origin||"current-session",R=_.timestamp?_.timestamp.slice(0,16).replace("T"," "):"",$=`--- [${v}${R?" | "+R:""} | ${_.source}] ---`,T=`### ${_.title}`,D=Jy(_.content,g,1500,_.highlighted);return`${$}
904
- ${T}
906
+ `);continue}let y;if(r==="timeline"?y=O$({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:h,projectDir:vr(),configDir:p,adapter:Cn??void 0}):y=e.searchWithFallback(g,u,i,a),y.length===0){m.push(`## ${g}
907
+ No results found.`);continue}let b=y.map((_,S)=>{let v=_.origin||"current-session",P=_.timestamp?_.timestamp.slice(0,16).replace("T"," "):"",T=`--- [${v}${P?" | "+P:""} | ${_.source}] ---`,$=`### ${_.title}`,D=n_(_.content,g,1500,_.highlighted);return`${T}
908
+ ${$}
905
909
 
906
910
  ${D}`}).join(`
907
911
 
@@ -913,10 +917,10 @@ ${b}`),l+=b.length}}finally{try{h?.close()}catch{}}let f=m.join(`
913
917
 
914
918
  `);if(e.lastRefreshCount>0&&(f=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
915
919
 
916
- `+f),Ss>=W$&&(f+=`
920
+ `+f),ks>=Q$&&(f+=`
917
921
 
918
- \u26A0 search call #${Ss}/${G$} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),f.trim().length===0){let g=e.listSources(),y=g.length>0?`
919
- Indexed sources: ${g.map(b=>`"${b.label}" (${b.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${y}`}]})}return W("ctx_search",{content:[{type:"text",text:f}]})}catch(e){let r=e instanceof Error?e.message:String(e);return W("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});Fy=null,Uy=null;aU=1440*60*1e3,K$=3072;Ge.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.
922
+ \u26A0 search call #${ks}/${eT} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),f.trim().length===0){let g=e.listSources(),y=g.length>0?`
923
+ Indexed sources: ${g.map(b=>`"${b.label}" (${b.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${y}`}]})}return W("ctx_search",{content:[{type:"text",text:f}]})}catch(e){let r=e instanceof Error?e.message:String(e);return W("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});Wy=null,Gy=null;fU=1440*60*1e3,tT=3072;Ge.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.
920
924
 
921
925
  Better than WebFetch: preview is immediate, full content is searchable, raw HTML never enters context.
922
926
 
@@ -926,14 +930,14 @@ PARALLELIZE I/O: For multi-URL research (library evaluation, migration scans, do
926
930
  \u2705 Use concurrency: 4-8 for: library docs sweep, multi-changelog scan, competitive pricing pages, multi-region docs, GitHub raw file pulls.
927
931
  \u274C Single URL \u2192 use the legacy {url, source} shape (concurrency irrelevant).
928
932
  Example: requests: [{url: 'https://react.dev/...', source: 'react'}, {url: 'https://vuejs.org/...', source: 'vue'}], concurrency: 5.
929
- 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 W("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let i=!r&&o.length===1,a=n??1,c=o.map(P=>({run:()=>uU(P.url,P.source,s)})),{settled:u,effectiveConcurrency:d,capped:l}=await fy(c,{concurrency:a,capByCpuCount:!i&&a>1}),m=[];for(let P=0;P<u.length;P++){let C=u[P];if(C.status==="rejected"){let X=C.reason instanceof Error?C.reason.message:String(C.reason);m.push({kind:"job_error",url:o[P].url,error:X});continue}let L=C.value;if(L.kind==="cached"){oe.cacheHits++,oe.cacheBytesSaved+=L.estimatedBytes;let X=L.estimatedBytes,fe=L.label;setImmediate(()=>h$({sessionDbPath:pa(),source:fe,bytesAvoided:X})),m.push({kind:"cached",label:L.label,chunkCount:L.chunkCount,ageStr:L.ageStr})}else L.kind==="fetch_error"?m.push({kind:"fetch_error",url:L.url,error:L.error,reason:L.reason}):m.push({kind:"fetched",indexed:lU(L)})}if(i){let P=m[0];if(P.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${P.label}** \u2014 ${P.chunkCount} sections, indexed ${P.ageStr} (fresh, TTL: 24h).
933
+ 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 W("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let i=!r&&o.length===1,a=n??1,c=o.map(R=>({run:()=>gU(R.url,R.source,s)})),{settled:u,effectiveConcurrency:d,capped:l}=await xy(c,{concurrency:a,capByCpuCount:!i&&a>1}),m=[];for(let R=0;R<u.length;R++){let C=u[R];if(C.status==="rejected"){let X=C.reason instanceof Error?C.reason.message:String(C.reason);m.push({kind:"job_error",url:o[R].url,error:X});continue}let L=C.value;if(L.kind==="cached"){oe.cacheHits++,oe.cacheBytesSaved+=L.estimatedBytes;let X=L.estimatedBytes,fe=L.label;setImmediate(()=>x$({sessionDbPath:ga(),source:fe,bytesAvoided:X})),m.push({kind:"cached",label:L.label,chunkCount:L.chunkCount,ageStr:L.ageStr})}else L.kind==="fetch_error"?m.push({kind:"fetch_error",url:L.url,error:L.error,reason:L.reason}):m.push({kind:"fetched",indexed:yU(L)})}if(i){let R=m[0];if(R.kind==="cached")return W("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${R.label}** \u2014 ${R.chunkCount} sections, indexed ${R.ageStr} (fresh, TTL: 24h).
930
934
  To refresh: call ctx_fetch_and_index again with \`force: true\`.
931
935
 
932
936
  You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
933
- Use: ctx_search(queries: [...], source: "${P.label}")`}]});if(P.kind==="fetched"){let C=(P.indexed.totalBytes/1024).toFixed(1),L=[`Fetched and indexed **${P.indexed.totalChunks} sections** (${C}KB) from: ${P.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${P.indexed.label}") for specific lookups.`,"","---","",P.indexed.preview].join(`
934
- `);return W("ctx_fetch_and_index",{content:[{type:"text",text:L}]})}if(P.kind==="fetch_error"){let C=P.reason==="empty"?`Fetched ${P.url} but got empty content`:P.reason==="read"?`Fetched ${P.url} but could not read subprocess output`:P.reason==="exit"?`Failed to fetch ${P.url}: ${P.error}`:`Fetch error: ${P.error}`;return W("ctx_fetch_and_index",{content:[{type:"text",text:C}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${P.error}`}],isError:!0})}let h=384,p=[],f=0,g=0,y=0,b=0,_=0,S=[];for(let P of m)if(P.kind==="cached")y++,p.push(`- [cache] ${P.label} \u2014 ${P.chunkCount} sections (${P.ageStr})`);else if(P.kind==="fetched"){b++,f+=P.indexed.totalChunks,g+=P.indexed.totalBytes;let C=(P.indexed.totalBytes/1024).toFixed(1);p.push(`- [new] ${P.indexed.label} \u2014 ${P.indexed.totalChunks} sections (${C}KB)`);let L=P.indexed.preview.length>h?P.indexed.preview.slice(0,h).trimEnd()+"\u2026":P.indexed.preview;S.push(`### ${P.indexed.label}
937
+ Use: ctx_search(queries: [...], source: "${R.label}")`}]});if(R.kind==="fetched"){let C=(R.indexed.totalBytes/1024).toFixed(1),L=[`Fetched and indexed **${R.indexed.totalChunks} sections** (${C}KB) from: ${R.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${R.indexed.label}") for specific lookups.`,"","---","",R.indexed.preview].join(`
938
+ `);return W("ctx_fetch_and_index",{content:[{type:"text",text:L}]})}if(R.kind==="fetch_error"){let C=R.reason==="empty"?`Fetched ${R.url} but got empty content`:R.reason==="read"?`Fetched ${R.url} but could not read subprocess output`:R.reason==="exit"?`Failed to fetch ${R.url}: ${R.error}`:`Fetch error: ${R.error}`;return W("ctx_fetch_and_index",{content:[{type:"text",text:C}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${R.error}`}],isError:!0})}let h=384,p=[],f=0,g=0,y=0,b=0,_=0,S=[];for(let R of m)if(R.kind==="cached")y++,p.push(`- [cache] ${R.label} \u2014 ${R.chunkCount} sections (${R.ageStr})`);else if(R.kind==="fetched"){b++,f+=R.indexed.totalChunks,g+=R.indexed.totalBytes;let C=(R.indexed.totalBytes/1024).toFixed(1);p.push(`- [new] ${R.indexed.label} \u2014 ${R.indexed.totalChunks} sections (${C}KB)`);let L=R.indexed.preview.length>h?R.indexed.preview.slice(0,h).trimEnd()+"\u2026":R.indexed.preview;S.push(`### ${R.indexed.label}
935
939
 
936
- ${L}`)}else _++,p.push(`- [err] ${P.url}: ${P.error}`);let v=(g/1024).toFixed(1),R=l?` cap=${d}/${D2().length}cpu`:"",$=(P,C,L)=>`${P} ${P===1?C:L}`,D=[`fetched ${o.length} c=${d}${R}. ok=${b} cache=${y} err=${_}. ${$(f,"section","sections")} ${v}KB.`,"",...p,"",'ctx_search(queries: [...], source: "<label>") for full content.',...S.length>0?["","---","",...S]:[]].join(`
940
+ ${L}`)}else _++,p.push(`- [err] ${R.url}: ${R.error}`);let v=(g/1024).toFixed(1),P=l?` cap=${d}/${H2().length}cpu`:"",T=(R,C,L)=>`${R} ${R===1?C:L}`,D=[`fetched ${o.length} c=${d}${P}. ok=${b} cache=${y} err=${_}. ${T(f,"section","sections")} ${v}KB.`,"",...p,"",'ctx_search(queries: [...], source: "<label>") for full content.',...S.length>0?["","---","",...S]:[]].join(`
937
941
  `);return W("ctx_fetch_and_index",{content:[{type:"text",text:D}],isError:_===o.length})});Ge.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.
938
942
 
939
943
  THIS IS THE PRIMARY TOOL. Use this instead of multiple ctx_execute() calls.
@@ -947,12 +951,12 @@ PARALLELIZE I/O: For I/O-bound batches (network calls, slow API queries, multi-U
947
951
  Example: [gh issue view 1, gh issue view 2, gh issue view 3] \u2192 concurrency: 3.
948
952
  Speedup depends on workload \u2014 applies to I/O wait, not CPU work.
949
953
 
950
- 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(sU,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(Yy,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=Ky(s.command,"batch_execute");if(o)return o}try{let s=oT(fa.shell,Gy),{outputs:o,timedOut:i}=await iT(t,{timeout:r,concurrency:n,nodeOptsPrefix:s,onFsBytes:_=>{oe.bytesSandboxed+=_}},ha),a=o.join(`
954
+ 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(dU,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(s_,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=r_(s.command,"batch_execute");if(o)return o}try{let s=dT(_a.shell,t_),{outputs:o,timedOut:i}=await pT(t,{timeout:r,concurrency:n,nodeOptsPrefix:s,onFsBytes:_=>{oe.bytesSandboxed+=_}},ba),a=o.join(`
951
955
  `),c=Buffer.byteLength(a),u=a.split(`
952
- `).length;if(i&&o.length===0)return W("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});br(c);let d=ws(),l=`batch:${t.map(_=>_.label).join(",").slice(0,80)}`,m=d.index({content:a,source:l,attribution:ks()}),h=d.getChunksBySource(m.sourceId),p=["## Indexed Sections",""],f=[];for(let _ of h){let S=Buffer.byteLength(_.content);p.push(`- ${_.title} (${(S/1024).toFixed(1)}KB)`),f.push(_.title)}let g=sT(d,e,l),y=d.getDistinctiveTerms?d.getDistinctiveTerms(m.sourceId):[],b=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${m.totalChunks} sections. Searched ${e.length} queries.`,"",...p,"",...g,y.length>0?`
956
+ `).length;if(i&&o.length===0)return W("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});br(c);let d=Es(),l=`batch:${t.map(_=>_.label).join(",").slice(0,80)}`,m=d.index({content:a,source:l,attribution:ws()}),h=d.getChunksBySource(m.sourceId),p=["## Indexed Sections",""],f=[];for(let _ of h){let S=Buffer.byteLength(_.content);p.push(`- ${_.title} (${(S/1024).toFixed(1)}KB)`),f.push(_.title)}let g=lT(d,e,l),y=d.getDistinctiveTerms?d.getDistinctiveTerms(m.sourceId):[],b=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${m.totalChunks} sections. Searched ${e.length} queries.`,"",...p,"",...g,y.length>0?`
953
957
  Searchable terms for follow-up: ${y.join(", ")}`:""].join(`
954
- `);return W("ctx_batch_execute",{content:[{type:"text",text:b}]})}catch(s){let o=s instanceof Error?s.message:String(s);return W("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${o}`}],isError:!0})}});Ge.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=vr(),r=Wr(e),n=sa({projectDir:e,sessionsDir:ot()});if(je(n)){let s=nt(),o=new s(n,{readonly:!0});try{let i=new Ro(o),a=i.queryAll(oe),c=i.getMcpToolUsage(),u=ca({sessionsDir:ot()}),d;try{d=al()}catch{}let l,m;try{let h=process.env.CLAUDE_SESSION_ID;if(h||(h=o.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),h){l=j$({sessionId:h,sessionsDir:ot(),worktreeHash:r});let p=hl(),f=zy({sessionId:h,sessionsDir:ot(),worktreeHash:r,contentDbPath:p}),g=zy({sessionsDir:ot()}),y=z$(p),b={...g,contentBytes:g.contentBytes+y,bytesAvoided:g.bytesAvoided+y,totalSavedTokens:Math.floor((g.eventDataBytes+g.bytesAvoided+y+g.snapshotBytes)/4)};m={conversation:f,lifetime:b}}}catch{}t=ul(a,Jr,Yr,{lifetime:u,mcpUsage:c,multiAdapter:d,conversation:l,realBytes:m,cwd:e})}finally{o.close()}}else{let o=new Ro(J$()).queryAll(oe),i=ca({sessionsDir:ot()}),a;try{a=al()}catch{}t=ul(o,Jr,Yr,{lifetime:i,multiAdapter:a})}}catch{let r=new Ro(J$()).queryAll(oe),n;try{n=ca({sessionsDir:ot()})}catch{}let s;try{s=al()}catch{}t=ul(r,Jr,Yr,n||s?{lifetime:n,multiAdapter:s}:void 0)}return W("ctx_stats",{content:[{type:"text",text:t}]})});Ge.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=je(dt(Mt,"package.json"))?Mt:er(Mt),r=11,n=(ml.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${ml.length}/${r} (${n}%) \u2014 ${ml.join(", ")}`),Cn()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");{let o=new So({runtimes:fa});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=nt();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 z2();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=Oa(s,e);o.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let i of o){let a=dt(e,i);je(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${Jr}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
955
- `)}]})});Ge.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=je(dt(Mt,"package.json"))?Mt:er(Mt),e=dt(t,"cli.bundle.mjs"),r=dt(t,"build","cli.js");try{let i=ot(),a=Oe(er(i),"insight-cache");je(a)&&(Xy(4747),fl(a,{recursive:!0,force:!0}))}catch{}let n="";try{let{detectPlatform:i}=await Promise.resolve().then(()=>(Un(),Wa)),a=Ge.server.getClientVersion();n=` --platform ${i(a??void 0).platform}`}catch{}let s;if(je(e))s=`${xe(e)} upgrade${n}`;else if(je(r))s=`${xe(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(`
958
+ `);return W("ctx_batch_execute",{content:[{type:"text",text:b}]})}catch(s){let o=s instanceof Error?s.message:String(s);return W("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${o}`}],isError:!0})}});Ge.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=vr(),r=Gr(e),n=ca({projectDir:e,sessionsDir:ot()});if(ze(n)){let s=nt(),o=new s(n,{readonly:!0});try{let i=new Oo(o),a=i.queryAll(oe),c=i.getMcpToolUsage(),u=pa({sessionsDir:ot()}),d;try{d=fl()}catch{}let l,m;try{let h=process.env.CLAUDE_SESSION_ID;if(h||(h=o.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),h){l=Z$({sessionId:h,sessionsDir:ot(),worktreeHash:r});let p=Sl(),f=qy({sessionId:h,sessionsDir:ot(),worktreeHash:r,contentDbPath:p}),g=qy({sessionsDir:ot()}),y=B$(p),b={...g,contentBytes:g.contentBytes+y,bytesAvoided:g.bytesAvoided+y,totalSavedTokens:Math.floor((g.eventDataBytes+g.bytesAvoided+y+g.snapshotBytes)/4)};m={conversation:f,lifetime:b}}}catch{}t=gl(a,Yr,Xr,{lifetime:u,mcpUsage:c,multiAdapter:d,conversation:l,realBytes:m,cwd:e})}finally{o.close()}}else{let o=new Oo(rT()).queryAll(oe),i=pa({sessionsDir:ot()}),a;try{a=fl()}catch{}t=gl(o,Yr,Xr,{lifetime:i,multiAdapter:a})}}catch{let r=new Oo(rT()).queryAll(oe),n;try{n=pa({sessionsDir:ot()})}catch{}let s;try{s=fl()}catch{}t=gl(r,Yr,Xr,n||s?{lifetime:n,multiAdapter:s}:void 0)}return W("ctx_stats",{content:[{type:"text",text:t}]})});Ge.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(dt(jt,"package.json"))?jt:tr(jt),r=11,n=(vl.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${vl.length}/${r} (${n}%) \u2014 ${vl.join(", ")}`),In()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");{let o=new wo({runtimes:_a});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=nt();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 q2();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=Da(s,e);o.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let i of o){let a=dt(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${Yr}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
959
+ `)}]})});Ge.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(dt(jt,"package.json"))?jt:tr(jt),e=dt(t,"cli.bundle.mjs"),r=dt(t,"build","cli.js");try{let i=ot(),a=Oe(tr(i),"insight-cache");ze(a)&&(o_(4747),xl(a,{recursive:!0,force:!0}))}catch{}let n="";try{let{detectPlatform:i}=await Promise.resolve().then(()=>(on(),Ka)),a=Ge.server.getClientVersion();n=` --platform ${i(a??void 0).platform}`}catch{}let s;if(ze(e))s=`${xe(e)} upgrade${n}`;else if(ze(r))s=`${xe(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(`
956
960
  `),c=dt(t,".ctx-upgrade-inline.mjs"),{writeFileSync:u}=await import("node:fs");u(c,a),s=xe(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(`
957
961
  `);return W("ctx_upgrade",{content:[{type:"text",text:o}]})});Ge.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:`DESTRUCTIVE \u2014 permanently delete indexed content. CANNOT be undone.
958
962
 
@@ -976,50 +980,48 @@ REFUSAL RULES (tool returns an error):
976
980
 
977
981
  Use sessionId when the user asks to clear a specific conversation's data.
978
982
  Use scope:'project' ONLY when the user explicitly asks to reset everything.
979
- 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.")})},async({confirm:t,sessionId:e,scope:r})=>{if(e&&r==="project")return W("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return W("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let s;try{s=hl()}catch{}if(_r){try{_r.cleanup()}catch{}_r=null}let o=s?er(s):void 0,{deleted:i}=d$({projectDir:vr(),sessionsDir:ot(),storePath:s,contentDir:o,legacyContentDir:Oe(bl(),".context-mode","content"),contentHash:Vr(vr()),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=eT();je(c)&&la(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return W("ctx_purge",{content:[{type:"text",text:a}]})});ua=5e3;Ge.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=je(dt(Mt,"package.json"))?Mt:er(Mt),u=dt(c,"insight"),d=i?dt(i):ot(),l=a?dt(a):Oe(er(d),"content"),m=Oe(er(d),"insight-cache");if(!je(Oe(u,"server.mjs")))return W("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let h=[],p=!1;da(m,{recursive:!0});let f=U$(Oe(u,"server.mjs")).mtimeMs,g=je(Oe(m,"server.mjs"))?U$(Oe(m,"server.mjs")).mtimeMs:0;if(f>g&&(h.push("Copying source files..."),R2(u,m,{recursive:!0,force:!0}),h.push("Source files copied."),p=!0),!je(Oe(m,"node_modules"))||p){h.push("Installing dependencies (first run, ~30s)...");try{H$(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:m,stdio:"pipe",timeout:3e5})}catch{try{fl(Oe(m,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!je(Oe(m,"node_modules","vite"))||!je(Oe(m,"node_modules","better-sqlite3")))throw fl(Oe(m,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");h.push("Dependencies installed.")}h.push("Building dashboard..."),H$("npx vite build",{cwd:m,stdio:"pipe",timeout:6e4}),h.push("Build complete.");let b=!1;try{let{request:T}=await import("node:http");await new Promise((D,P)=>{let C=T(`http://127.0.0.1:${o}/api/overview`,{timeout:2e3},L=>{L.resume(),D()});C.on("error",()=>P()),C.on("timeout",()=>{C.destroy(),P()}),C.end()}),b=!0}catch{}if(b&&p){h.push("Killing stale dashboard server (source updated)...");let T=Xy(o);if(T.attemptedPids.length>0&&T.killedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Could not free port ${o} (kill failed for ${T.attemptedPids.join(", ")}: ${T.errors.join("; ")}). Try ctx_insight({ port: ${o+1} }) or stop the process manually.`}]});if(T.errors.length>0&&T.attemptedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${o}: ${T.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(D=>setTimeout(D,500)),h.push(`Stale server killed (${T.killedPids.length} pid${T.killedPids.length===1?"":"s"}).`)}else if(b){h.push("Dashboard already running.");let T=`http://localhost:${o}`,D=By(T),P=D.ok?"":` (auto-open failed: ${D.reason}; navigate manually)`;return W("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${T}${P}`}]})}if(Kr&&Kr.pid&&!Kr.killed)try{Kr.kill("SIGTERM")}catch{}let{spawn:_}=await import("node:child_process"),S=_("node",[Oe(m,"server.mjs")],{cwd:m,env:{...process.env,PORT:String(o),INSIGHT_SESSION_DIR:d,INSIGHT_CONTENT_DIR:l,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});S.on("error",()=>{}),S.unref(),Kr=S,await new Promise(T=>setTimeout(T,1500));try{let{request:T}=await import("node:http");await new Promise((D,P)=>{let C=T(`http://127.0.0.1:${o}/api/overview`,{timeout:3e3},L=>{D(),L.resume()});C.on("error",P),C.on("timeout",()=>{C.destroy(),P(new Error("timeout"))}),C.end()})}catch{return W("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.
983
+ 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.")})},async({confirm:t,sessionId:e,scope:r})=>{if(e&&r==="project")return W("ctx_purge",{content:[{type:"text",text:"Ambiguous purge: sessionId implies scope:'session', cannot combine with scope:'project'. Use scope:'project' WITHOUT sessionId for the legacy whole-project wipe."}],isError:!0});if(!t)return W("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let n=r??(e?"session":"project");!r&&!e&&console.warn("[context-mode] ctx_purge: bare {confirm:true} is deprecated. Pass scope:'project' for the whole-project wipe, or scope:'session' + sessionId for a scoped wipe. See issue #520.");let s;try{s=Sl()}catch{}if(_r){try{_r.cleanup()}catch{}_r=null}let o=s?tr(s):void 0,{deleted:i}=y$({projectDir:vr(),sessionsDir:ot(),storePath:s,contentDir:o,legacyContentDir:Oe($l(),".context-mode","content"),contentHash:Wr(vr()),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=iT();ze(c)&&fa(c)}catch{}}let a=n==="session"?`Purged session ${e}: ${i.length?i.join(", "):"no matching rows"}. Other sessions and project-wide stats preserved.`:`Purged: ${i.join(", ")}. All session data for this project has been permanently deleted.`;return W("ctx_purge",{content:[{type:"text",text:a}]})});ma=5e3;Ge.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(dt(jt,"package.json"))?jt:tr(jt),u=dt(c,"insight"),d=i?dt(i):ot(),l=a?dt(a):Oe(tr(d),"content"),m=Oe(tr(d),"insight-cache");if(!ze(Oe(u,"server.mjs")))return W("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let h=[],p=!1;ha(m,{recursive:!0});let f=W$(Oe(u,"server.mjs")).mtimeMs,g=ze(Oe(m,"server.mjs"))?W$(Oe(m,"server.mjs")).mtimeMs:0;if(f>g&&(h.push("Copying source files..."),M2(u,m,{recursive:!0,force:!0}),h.push("Source files copied."),p=!0),!ze(Oe(m,"node_modules"))||p){h.push("Installing dependencies (first run, ~30s)...");try{G$(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:m,stdio:"pipe",timeout:3e5})}catch{try{xl(Oe(m,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!ze(Oe(m,"node_modules","vite"))||!ze(Oe(m,"node_modules","better-sqlite3")))throw xl(Oe(m,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");h.push("Dependencies installed.")}h.push("Building dashboard..."),G$("npx vite build",{cwd:m,stdio:"pipe",timeout:6e4}),h.push("Build complete.");let b=!1;try{let{request:$}=await import("node:http");await new Promise((D,R)=>{let C=$(`http://127.0.0.1:${o}/api/overview`,{timeout:2e3},L=>{L.resume(),D()});C.on("error",()=>R()),C.on("timeout",()=>{C.destroy(),R()}),C.end()}),b=!0}catch{}if(b&&p){h.push("Killing stale dashboard server (source updated)...");let $=o_(o);if($.attemptedPids.length>0&&$.killedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Could not free port ${o} (kill failed for ${$.attemptedPids.join(", ")}: ${$.errors.join("; ")}). Try ctx_insight({ port: ${o+1} }) or stop the process manually.`}]});if($.errors.length>0&&$.attemptedPids.length===0)return W("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${o}: ${$.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(D=>setTimeout(D,500)),h.push(`Stale server killed (${$.killedPids.length} pid${$.killedPids.length===1?"":"s"}).`)}else if(b){h.push("Dashboard already running.");let $=`http://localhost:${o}`,D=Yy($),R=D.ok?"":` (auto-open failed: ${D.reason}; navigate manually)`;return W("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${$}${R}`}]})}if(Jr&&Jr.pid&&!Jr.killed)try{Jr.kill("SIGTERM")}catch{}let{spawn:_}=await import("node:child_process"),S=_("node",[Oe(m,"server.mjs")],{cwd:m,env:{...process.env,PORT:String(o),INSIGHT_SESSION_DIR:d,INSIGHT_CONTENT_DIR:l,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});S.on("error",()=>{}),S.unref(),Jr=S,await new Promise($=>setTimeout($,1500));try{let{request:$}=await import("node:http");await new Promise((D,R)=>{let C=$(`http://127.0.0.1:${o}/api/overview`,{timeout:3e3},L=>{D(),L.resume()});C.on("error",R),C.on("timeout",()=>{C.destroy(),R(new Error("timeout"))}),C.end()})}catch{return W("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.
980
984
 
981
985
  To fix:
982
986
  - Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${o}`:`lsof -ti:${o} | xargs kill`}
983
- - Or use a different port: ctx_insight({ port: ${o+1} })`}]})}let v=`http://localhost:${o}`,R=By(v),$=R.ok?"":` (auto-open failed: ${R.reason}; navigate manually)`;return h.push(`Dashboard running at ${v}${$}`),W("ctx_insight",{content:[{type:"text",text:h.map(T=>`- ${T}`).join(`
987
+ - Or use a different port: ctx_insight({ port: ${o+1} })`}]})}let v=`http://localhost:${o}`,P=Yy(v),T=P.ok?"":` (auto-open failed: ${P.reason}; navigate manually)`;return h.push(`Dashboard running at ${v}${T}`),W("ctx_insight",{content:[{type:"text",text:h.map($=>`- ${$}`).join(`
984
988
  `)+`
985
989
 
986
990
  Open: ${v}
987
- PID: ${S.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${S.pid} /F`:`kill ${S.pid}`}`}]})}catch(h){let p=h instanceof Error?h.message:String(h);return W("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});dU().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var _T={};ze(_T,{needsHookNormalization:()=>ya,normalizeHooksJson:()=>gT,normalizeHooksOnStartup:()=>pU,normalizePluginJson:()=>yT});import{existsSync as pT,readFileSync as mT,writeFileSync as fT}from"node:fs";import{resolve as hT}from"node:path";function vl(t){return String(t).replace(/\\/g,"/")}function ya(t){return!t||typeof t!="string"?!1:t.includes(ga)}function gT(t,e,r){if(!ya(t))return t;let n=vl(e),s=vl(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 m of l){if(typeof m?.command!="string"||!m.command.includes(ga))continue;let h=m.command.replaceAll(ga,s);h=h.replace(/^\s*node\s+/,`"${n}" `),m.command=h,a=!0}}}return a?JSON.stringify(o,null,2):t}function yT(t,e,r){if(!ya(t))return t;let n=vl(e),s=vl(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(m=>typeof m=="string"&&m.includes(ga)?m.replaceAll(ga,s):m);l.some((m,h)=>m!==d[h])&&(u.args=l,a=!0)}u.command==="node"&&a&&(u.command=n)}}return a?JSON.stringify(o,null,2):t}function pU({pluginRoot:t,nodePath:e,platform:r}){if(r==="win32"&&!(!t||!e)){try{let n=hT(t,"hooks","hooks.json");if(pT(n)){let s=mT(n,"utf-8");if(ya(s)){let o=gT(s,e,t);o!==s&&fT(n,o,"utf-8")}}}catch{}try{let n=hT(t,".claude-plugin","plugin.json");if(pT(n)){let s=mT(n,"utf-8");if(ya(s)){let o=yT(s,e,t);o!==s&&fT(n,o,"utf-8")}}}catch{}}}var ga,bT=x(()=>{"use strict";ga="${CLAUDE_PLUGIN_ROOT}"});import{stdout as KT,stdin as JT}from"node:process";import*as Qr from"node:readline";var n_=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,s_=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,o_=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 Pl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,ba=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,va=/\t{1,1000}/y,Rl=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"),xa=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,zT=new RegExp("\\p{M}+","gu"),LT={limit:1/0,ellipsis:""},i_=(t,e={},r={})=>{let n=e.limit??1/0,s=e.ellipsis??"",o=e?.ellipsisWidth??(s?i_(s,LT,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,d=r.emojiWidth??2,l=r.fullWidthWidth??2,m=r.regularWidth??1,h=r.wideWidth??2,p=0,f=0,g=t.length,y=0,b=!1,_=g,S=Math.max(0,n-o),v=0,R=0,$=0,T=0;e:for(;;){if(R>v||f>=g&&f>p){let D=t.slice(v,R)||t.slice(p,f);y=0;for(let P of D.replaceAll(zT,"")){let C=P.codePointAt(0)||0;if(s_(C)?T=l:o_(C)?T=h:u!==m&&n_(C)?T=u:T=m,$+T>S&&(_=Math.min(_,Math.max(v,p)+y)),$+T>n){b=!0;break e}y+=P.length,$+=T}v=R=0}if(f>=g)break;if(xa.lastIndex=f,xa.test(t)){if(y=xa.lastIndex-f,T=y*m,$+T>S&&(_=Math.min(_,f+Math.floor((S-$)/m))),$+T>n){b=!0;break}$+=T,v=p,R=f,f=p=xa.lastIndex;continue}if(Pl.lastIndex=f,Pl.test(t)){if($+i>S&&(_=Math.min(_,f)),$+i>n){b=!0;break}$+=i,v=p,R=f,f=p=Pl.lastIndex;continue}if(ba.lastIndex=f,ba.test(t)){if(y=ba.lastIndex-f,T=y*a,$+T>S&&(_=Math.min(_,f+Math.floor((S-$)/a))),$+T>n){b=!0;break}$+=T,v=p,R=f,f=p=ba.lastIndex;continue}if(va.lastIndex=f,va.test(t)){if(y=va.lastIndex-f,T=y*c,$+T>S&&(_=Math.min(_,f+Math.floor((S-$)/c))),$+T>n){b=!0;break}$+=T,v=p,R=f,f=p=va.lastIndex;continue}if(Rl.lastIndex=f,Rl.test(t)){if($+d>S&&(_=Math.min(_,f)),$+d>n){b=!0;break}$+=d,v=p,R=f,f=p=Rl.lastIndex;continue}f+=1}return{width:b?S:$,index:b?_:g,truncated:b,ellipsed:b&&n>=o}},a_=i_;var FT={limit:1/0,ellipsis:"",ellipsisWidth:0},UT=(t,e={})=>a_(t,FT,e).width,mt=UT;var Sa="\x1B",p_="\x9B",HT=39,Ol="\x07",m_="[",ZT="]",f_="m",Il=`${ZT}8;;`,c_=new RegExp(`(?:\\${m_}(?<code>\\d+)m|\\${Il}(?<uri>.*)${Ol})`,"y"),u_=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},l_=t=>`${Sa}${m_}${t}${f_}`,d_=t=>`${Sa}${Il}${t}${Ol}`,Cl=(t,e,r)=>{let n=e[Symbol.iterator](),s=!1,o=!1,i=t.at(-1),a=i===void 0?0:mt(i),c=n.next(),u=n.next(),d=0;for(;!c.done;){let l=c.value,m=mt(l);a+m<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===Sa||l===p_)&&(s=!0,o=e.startsWith(Il,d+1)),s?o?l===Ol&&(s=!1,o=!1):l===f_&&(s=!1):(a+=m,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),d+=l.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},BT=t=>{let e=t.split(" "),r=e.length;for(;r&&!mt(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},qT=(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 m=i[l];if(r.trim!==!1){let p=a.at(-1)??"",f=p.trimStart();p.length!==f.length&&(a[a.length-1]=f,c=mt(f))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let h=mt(m);if(r.hard&&h>e){let p=e-c,f=1+Math.floor((h-p-1)/e);Math.floor((h-1)/e)<f&&a.push(""),Cl(a,m,e),c=mt(a.at(-1)??"");continue}if(c+h>e&&c&&h){if(r.wordWrap===!1&&c<e){Cl(a,m,e),c=mt(a.at(-1)??"");continue}a.push(""),c=0}if(c+h>e&&r.wordWrap===!1){Cl(a,m,e),c=mt(a.at(-1)??"");continue}a[a.length-1]+=m,c+=h}r.trim!==!1&&(a=a.map(l=>BT(l)));let u=a.join(`
988
- `),d=!1;for(let l=0;l<u.length;l++){let m=u[l];if(n+=m,!d)d=m>="\uD800"&&m<="\uDBFF";else continue;if(m===Sa||m===p_){c_.lastIndex=l+1;let p=c_.exec(u)?.groups;if(p?.code!==void 0){let f=Number.parseFloat(p.code);s=f===HT?void 0:f}else p?.uri!==void 0&&(o=p.uri.length===0?void 0:p.uri)}if(u[l+1]===`
989
- `){o&&(n+=d_(""));let h=s?u_(s):void 0;s&&h&&(n+=l_(h))}else m===`
990
- `&&(s&&u_(s)&&(n+=l_(s)),o&&(n+=d_(o)))}return n},VT=/\r?\n/;function $s(t,e,r){return String(t).normalize().split(VT).map(n=>qT(n,e,r)).join(`
991
- `)}var Do=No(Nl(),1);import{ReadStream as g_}from"node:tty";var YT=["up","down","left","right","space","enter","cancel"],XT=["January","February","March","April","May","June","July","August","September","October","November","December"],xr={actions:new Set(YT),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:[...XT],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 y_(t,e){if(typeof t=="string")return xr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&y_(r,e))return!0;return!1}var QT=globalThis.process.platform.startsWith("win");function __({input:t=JT,output:e=KT,overwrite:r=!0,hideCursor:n=!0}={}){let s=Qr.createInterface({input:t,output:e,prompt:"",tabSize:1});Qr.emitKeypressEvents(t,s),t instanceof g_&&t.isTTY&&t.setRawMode(!0);let o=(i,{name:a,sequence:c})=>{let u=String(i);if(y_([u,a,c],"cancel")){n&&e.write(Do.cursor.show),process.exit(0);return}if(!r)return;Qr.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{Qr.clearLine(e,1,()=>{t.once("keypress",o)})})};return n&&e.write(Do.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),n&&e.write(Do.cursor.show),t instanceof g_&&t.isTTY&&!QT&&t.setRawMode(!1),s.terminal=!1,s.close()}}var Dl=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Ie,stripVTControlCharacters as uH}from"node:util";import jt from"node:process";var Mo=No(Nl(),1);function tP(){return jt.platform!=="win32"?jt.env.TERM!=="linux":!!jt.env.CI||!!jt.env.WT_SESSION||!!jt.env.TERMINUS_SUBLIME||jt.env.ConEmuTask==="{cmd::Cmder}"||jt.env.TERM_PROGRAM==="Terminus-Sublime"||jt.env.TERM_PROGRAM==="vscode"||jt.env.TERM==="xterm-256color"||jt.env.TERM==="alacritty"||jt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var Ml=tP(),rP=()=>process.env.CI==="true";var ye=(t,e)=>Ml?t:e,mH=ye("\u25C6","*"),nP=ye("\u25A0","x"),sP=ye("\u25B2","x"),jl=ye("\u25C7","o"),oP=ye("\u250C","T"),en=ye("\u2502","|"),iP=ye("\u2514","\u2014"),fH=ye("\u2510","T"),hH=ye("\u2518","\u2014"),gH=ye("\u25CF",">"),yH=ye("\u25CB"," "),_H=ye("\u25FB","[\u2022]"),bH=ye("\u25FC","[+]"),vH=ye("\u25FB","[ ]"),xH=ye("\u25AA","\u2022"),b_=ye("\u2500","-"),aP=ye("\u256E","+"),cP=ye("\u251C","+"),uP=ye("\u256F","+"),lP=ye("\u2570","+"),SH=ye("\u256D","+"),dP=ye("\u25CF","\u2022"),pP=ye("\u25C6","*"),mP=ye("\u25B2","!"),fP=ye("\u25A0","x");var A={message:(t=[],{symbol:e=Ie("gray",en),secondarySymbol:r=Ie("gray",en),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 m=0;m<s;m++)i.push(c);let l=Array.isArray(t)?t:t.split(`
991
+ PID: ${S.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${S.pid} /F`:`kill ${S.pid}`}`}]})}catch(h){let p=h instanceof Error?h.message:String(h);return W("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});_U().catch(t=>{console.error("Fatal:",t),process.exit(1)})});var wT={};Ie(wT,{needsHookNormalization:()=>xa,normalizeHooksJson:()=>ST,normalizeHooksOnStartup:()=>bU,normalizePluginJson:()=>kT});import{existsSync as _T,readFileSync as bT,writeFileSync as vT}from"node:fs";import{resolve as xT}from"node:path";function Tl(t){return String(t).replace(/\\/g,"/")}function xa(t){return!t||typeof t!="string"?!1:t.includes(va)}function ST(t,e,r){if(!xa(t))return t;let n=Tl(e),s=Tl(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 m of l){if(typeof m?.command!="string"||!m.command.includes(va))continue;let h=m.command.replaceAll(va,s);h=h.replace(/^\s*node\s+/,`"${n}" `),m.command=h,a=!0}}}return a?JSON.stringify(o,null,2):t}function kT(t,e,r){if(!xa(t))return t;let n=Tl(e),s=Tl(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(m=>typeof m=="string"&&m.includes(va)?m.replaceAll(va,s):m);l.some((m,h)=>m!==d[h])&&(u.args=l,a=!0)}u.command==="node"&&a&&(u.command=n)}}return a?JSON.stringify(o,null,2):t}function bU({pluginRoot:t,nodePath:e,platform:r}){if(!(r!=="win32"&&r!=="linux")&&!(!t||!e)){try{let n=xT(t,"hooks","hooks.json");if(_T(n)){let s=bT(n,"utf-8");if(xa(s)){let o=ST(s,e,t);o!==s&&vT(n,o,"utf-8")}}}catch{}try{let n=xT(t,".claude-plugin","plugin.json");if(_T(n)){let s=bT(n,"utf-8");if(xa(s)){let o=kT(s,e,t);o!==s&&vT(n,o,"utf-8")}}}catch{}}}var va,ET=x(()=>{"use strict";va="${CLAUDE_PLUGIN_ROOT}"});import{stdout as eP,stdin as tP}from"node:process";import*as en from"node:readline";var d_=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,p_=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,m_=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 Dl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,ka=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,wa=/\t{1,1000}/y,Ml=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"),Ea=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ZT=new RegExp("\\p{M}+","gu"),BT={limit:1/0,ellipsis:""},f_=(t,e={},r={})=>{let n=e.limit??1/0,s=e.ellipsis??"",o=e?.ellipsisWidth??(s?f_(s,BT,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,d=r.emojiWidth??2,l=r.fullWidthWidth??2,m=r.regularWidth??1,h=r.wideWidth??2,p=0,f=0,g=t.length,y=0,b=!1,_=g,S=Math.max(0,n-o),v=0,P=0,T=0,$=0;e:for(;;){if(P>v||f>=g&&f>p){let D=t.slice(v,P)||t.slice(p,f);y=0;for(let R of D.replaceAll(ZT,"")){let C=R.codePointAt(0)||0;if(p_(C)?$=l:m_(C)?$=h:u!==m&&d_(C)?$=u:$=m,T+$>S&&(_=Math.min(_,Math.max(v,p)+y)),T+$>n){b=!0;break e}y+=R.length,T+=$}v=P=0}if(f>=g)break;if(Ea.lastIndex=f,Ea.test(t)){if(y=Ea.lastIndex-f,$=y*m,T+$>S&&(_=Math.min(_,f+Math.floor((S-T)/m))),T+$>n){b=!0;break}T+=$,v=p,P=f,f=p=Ea.lastIndex;continue}if(Dl.lastIndex=f,Dl.test(t)){if(T+i>S&&(_=Math.min(_,f)),T+i>n){b=!0;break}T+=i,v=p,P=f,f=p=Dl.lastIndex;continue}if(ka.lastIndex=f,ka.test(t)){if(y=ka.lastIndex-f,$=y*a,T+$>S&&(_=Math.min(_,f+Math.floor((S-T)/a))),T+$>n){b=!0;break}T+=$,v=p,P=f,f=p=ka.lastIndex;continue}if(wa.lastIndex=f,wa.test(t)){if(y=wa.lastIndex-f,$=y*c,T+$>S&&(_=Math.min(_,f+Math.floor((S-T)/c))),T+$>n){b=!0;break}T+=$,v=p,P=f,f=p=wa.lastIndex;continue}if(Ml.lastIndex=f,Ml.test(t)){if(T+d>S&&(_=Math.min(_,f)),T+d>n){b=!0;break}T+=d,v=p,P=f,f=p=Ml.lastIndex;continue}f+=1}return{width:b?S:T,index:b?_:g,truncated:b,ellipsed:b&&n>=o}},h_=f_;var qT={limit:1/0,ellipsis:"",ellipsisWidth:0},VT=(t,e={})=>h_(t,qT,e).width,mt=VT;var $a="\x1B",v_="\x9B",WT=39,zl="\x07",x_="[",GT="]",S_="m",Ll=`${GT}8;;`,g_=new RegExp(`(?:\\${x_}(?<code>\\d+)m|\\${Ll}(?<uri>.*)${zl})`,"y"),y_=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},__=t=>`${$a}${x_}${t}${S_}`,b_=t=>`${$a}${Ll}${t}${zl}`,jl=(t,e,r)=>{let n=e[Symbol.iterator](),s=!1,o=!1,i=t.at(-1),a=i===void 0?0:mt(i),c=n.next(),u=n.next(),d=0;for(;!c.done;){let l=c.value,m=mt(l);a+m<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===$a||l===v_)&&(s=!0,o=e.startsWith(Ll,d+1)),s?o?l===zl&&(s=!1,o=!1):l===S_&&(s=!1):(a+=m,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),d+=l.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},KT=t=>{let e=t.split(" "),r=e.length;for(;r&&!mt(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},JT=(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 m=i[l];if(r.trim!==!1){let p=a.at(-1)??"",f=p.trimStart();p.length!==f.length&&(a[a.length-1]=f,c=mt(f))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let h=mt(m);if(r.hard&&h>e){let p=e-c,f=1+Math.floor((h-p-1)/e);Math.floor((h-1)/e)<f&&a.push(""),jl(a,m,e),c=mt(a.at(-1)??"");continue}if(c+h>e&&c&&h){if(r.wordWrap===!1&&c<e){jl(a,m,e),c=mt(a.at(-1)??"");continue}a.push(""),c=0}if(c+h>e&&r.wordWrap===!1){jl(a,m,e),c=mt(a.at(-1)??"");continue}a[a.length-1]+=m,c+=h}r.trim!==!1&&(a=a.map(l=>KT(l)));let u=a.join(`
992
+ `),d=!1;for(let l=0;l<u.length;l++){let m=u[l];if(n+=m,!d)d=m>="\uD800"&&m<="\uDBFF";else continue;if(m===$a||m===v_){g_.lastIndex=l+1;let p=g_.exec(u)?.groups;if(p?.code!==void 0){let f=Number.parseFloat(p.code);s=f===WT?void 0:f}else p?.uri!==void 0&&(o=p.uri.length===0?void 0:p.uri)}if(u[l+1]===`
993
+ `){o&&(n+=b_(""));let h=s?y_(s):void 0;s&&h&&(n+=__(h))}else m===`
994
+ `&&(s&&y_(s)&&(n+=__(s)),o&&(n+=b_(o)))}return n},YT=/\r?\n/;function Ts(t,e,r){return String(t).normalize().split(YT).map(n=>JT(n,e,r)).join(`
995
+ `)}var jo=Mo(Ul(),1);import{ReadStream as w_}from"node:tty";var rP=["up","down","left","right","space","enter","cancel"],nP=["January","February","March","April","May","June","July","August","September","October","November","December"],xr={actions:new Set(rP),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:[...nP],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 E_(t,e){if(typeof t=="string")return xr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&E_(r,e))return!0;return!1}var sP=globalThis.process.platform.startsWith("win");function $_({input:t=tP,output:e=eP,overwrite:r=!0,hideCursor:n=!0}={}){let s=en.createInterface({input:t,output:e,prompt:"",tabSize:1});en.emitKeypressEvents(t,s),t instanceof w_&&t.isTTY&&t.setRawMode(!0);let o=(i,{name:a,sequence:c})=>{let u=String(i);if(E_([u,a,c],"cancel")){n&&e.write(jo.cursor.show),process.exit(0);return}if(!r)return;en.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{en.clearLine(e,1,()=>{t.once("keypress",o)})})};return n&&e.write(jo.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),n&&e.write(jo.cursor.show),t instanceof w_&&t.isTTY&&!sP&&t.setRawMode(!1),s.terminal=!1,s.close()}}var Hl=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Ae,stripVTControlCharacters as gH}from"node:util";import zt from"node:process";var zo=Mo(Ul(),1);function iP(){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 Zl=iP(),aP=()=>process.env.CI==="true";var ye=(t,e)=>Zl?t:e,vH=ye("\u25C6","*"),cP=ye("\u25A0","x"),uP=ye("\u25B2","x"),Bl=ye("\u25C7","o"),lP=ye("\u250C","T"),tn=ye("\u2502","|"),dP=ye("\u2514","\u2014"),xH=ye("\u2510","T"),SH=ye("\u2518","\u2014"),kH=ye("\u25CF",">"),wH=ye("\u25CB"," "),EH=ye("\u25FB","[\u2022]"),$H=ye("\u25FC","[+]"),TH=ye("\u25FB","[ ]"),PH=ye("\u25AA","\u2022"),T_=ye("\u2500","-"),pP=ye("\u256E","+"),mP=ye("\u251C","+"),fP=ye("\u256F","+"),hP=ye("\u2570","+"),RH=ye("\u256D","+"),gP=ye("\u25CF","\u2022"),yP=ye("\u25C6","*"),_P=ye("\u25B2","!"),bP=ye("\u25A0","x");var A={message:(t=[],{symbol:e=Ae("gray",tn),secondarySymbol:r=Ae("gray",tn),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 m=0;m<s;m++)i.push(c);let l=Array.isArray(t)?t:t.split(`
992
996
  `);if(l.length>0){let[m,...h]=l;m.length>0?i.push(`${u}${m}`):i.push(a?e:"");for(let p of h)p.length>0?i.push(`${d}${p}`):i.push(a?r:"")}n.write(`${i.join(`
993
997
  `)}
994
- `)},info:(t,e)=>{A.message(t,{...e,symbol:Ie("blue",dP)})},success:(t,e)=>{A.message(t,{...e,symbol:Ie("green",pP)})},step:(t,e)=>{A.message(t,{...e,symbol:Ie("green",jl)})},warn:(t,e)=>{A.message(t,{...e,symbol:Ie("yellow",mP)})},warning:(t,e)=>{A.warn(t,e)},error:(t,e)=>{A.message(t,{...e,symbol:Ie("red",fP)})}};var zl=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??xr.withGuide?`${Ie("gray",oP)} `:"";r.write(`${n}${t}
995
- `)},ka=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??xr.withGuide?`${Ie("gray",en)}
996
- ${Ie("gray",iP)} `:"";r.write(`${n}${t}
997
-
998
- `)};var hP=t=>Ie("dim",t),gP=(t,e,r)=>{let n={hard:!0,trim:!1},s=$s(t,e,n).split(`
999
- `),o=s.reduce((c,u)=>Math.max(mt(u),c),0),i=s.map(r).reduce((c,u)=>Math.max(mt(u),c),0),a=e-(i-o);return $s(t,a,n)},Ll=(t="",e="",r)=>{let n=r?.output??jt.stdout,s=r?.withGuide??xr.withGuide,o=r?.format??hP,i=["",...gP(t,Dl(n)-6,o).split(`
1000
- `).map(o),""],a=mt(e),c=Math.max(i.reduce((m,h)=>{let p=mt(h);return p>m?p:m},0),a)+2,u=i.map(m=>`${Ie("gray",en)} ${m}${" ".repeat(c-mt(m))}${Ie("gray",en)}`).join(`
1001
- `),d=s?`${Ie("gray",en)}
1002
- `:"",l=s?cP:lP;n.write(`${d}${Ie("green",jl)} ${Ie("reset",e)} ${Ie("gray",b_.repeat(Math.max(c-a-1,1))+aP)}
998
+ `)},info:(t,e)=>{A.message(t,{...e,symbol:Ae("blue",gP)})},success:(t,e)=>{A.message(t,{...e,symbol:Ae("green",yP)})},step:(t,e)=>{A.message(t,{...e,symbol:Ae("green",Bl)})},warn:(t,e)=>{A.message(t,{...e,symbol:Ae("yellow",_P)})},warning:(t,e)=>{A.warn(t,e)},error:(t,e)=>{A.message(t,{...e,symbol:Ae("red",bP)})}};var ql=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??xr.withGuide?`${Ae("gray",lP)} `:"";r.write(`${n}${t}
999
+ `)},Ta=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??xr.withGuide?`${Ae("gray",tn)}
1000
+ ${Ae("gray",dP)} `:"";r.write(`${n}${t}
1001
+
1002
+ `)};var vP=t=>Ae("dim",t),xP=(t,e,r)=>{let n={hard:!0,trim:!1},s=Ts(t,e,n).split(`
1003
+ `),o=s.reduce((c,u)=>Math.max(mt(u),c),0),i=s.map(r).reduce((c,u)=>Math.max(mt(u),c),0),a=e-(i-o);return Ts(t,a,n)},Vl=(t="",e="",r)=>{let n=r?.output??zt.stdout,s=r?.withGuide??xr.withGuide,o=r?.format??vP,i=["",...xP(t,Hl(n)-6,o).split(`
1004
+ `).map(o),""],a=mt(e),c=Math.max(i.reduce((m,h)=>{let p=mt(h);return p>m?p:m},0),a)+2,u=i.map(m=>`${Ae("gray",tn)} ${m}${" ".repeat(c-mt(m))}${Ae("gray",tn)}`).join(`
1005
+ `),d=s?`${Ae("gray",tn)}
1006
+ `:"",l=s?mP:hP;n.write(`${d}${Ae("green",Bl)} ${Ae("reset",e)} ${Ae("gray",T_.repeat(Math.max(c-a-1,1))+pP)}
1003
1007
  ${u}
1004
- ${Ie("gray",l+b_.repeat(c+2)+uP)}
1005
- `)};var yP=t=>Ie("magenta",t),Fl=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:o=Ml?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=Ml?80:120,signal:a,...c}={})=>{let u=rP(),d,l,m=!1,h=!1,p="",f,g=performance.now(),y=Dl(r),b=c?.styleFrame??yP,_=fe=>{let it=fe>1?s??xr.messages.error:n??xr.messages.cancel;h=fe===1,m&&(X(it,fe),h&&typeof e=="function"&&e())},S=()=>_(2),v=()=>_(1),R=()=>{process.on("uncaughtExceptionMonitor",S),process.on("unhandledRejection",S),process.on("SIGINT",v),process.on("SIGTERM",v),process.on("exit",_),a&&a.addEventListener("abort",v)},$=()=>{process.removeListener("uncaughtExceptionMonitor",S),process.removeListener("unhandledRejection",S),process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),process.removeListener("exit",_),a&&a.removeEventListener("abort",v)},T=()=>{if(f===void 0)return;u&&r.write(`
1006
- `);let fe=$s(f,y,{hard:!0,trim:!1}).split(`
1007
- `);fe.length>1&&r.write(Mo.cursor.up(fe.length-1)),r.write(Mo.cursor.to(0)),r.write(Mo.erase.down())},D=fe=>fe.replace(/\.+$/,""),P=fe=>{let it=(performance.now()-fe)/1e3,pt=Math.floor(it/60),rr=Math.floor(it%60);return pt>0?`[${pt}m ${rr}s]`:`[${rr}s]`},C=c.withGuide??xr.withGuide,L=(fe="")=>{m=!0,d=__({output:r}),p=D(fe),g=performance.now(),C&&r.write(`${Ie("gray",en)}
1008
- `);let it=0,pt=0;R(),l=setInterval(()=>{if(u&&p===f)return;T(),f=p;let rr=b(o[it]),Rn;if(u)Rn=`${rr} ${p}...`;else if(t==="timer")Rn=`${rr} ${p} ${P(g)}`;else{let _a=".".repeat(Math.floor(pt)).slice(0,3);Rn=`${rr} ${p}${_a}`}let Ao=$s(Rn,y,{hard:!0,trim:!1});r.write(Ao),it=it+1<o.length?it+1:0,pt=pt<4?pt+.125:0},i)},X=(fe="",it=0,pt=!1)=>{if(!m)return;m=!1,clearInterval(l),T();let rr=it===0?Ie("green",jl):it===1?Ie("red",nP):Ie("red",sP);p=fe??p,pt||(t==="timer"?r.write(`${rr} ${p} ${P(g)}
1009
- `):r.write(`${rr} ${p}
1010
- `)),$(),d()};return{start:L,stop:(fe="")=>X(fe,0),message:(fe="")=>{p=D(fe??p)},cancel:(fe="")=>X(fe,1),error:(fe="")=>X(fe,2),clear:()=>X("",0,!0),get isCancelled(){return h}}},kH={light:ye("\u2500","-"),heavy:ye("\u2501","="),block:ye("\u2588","#")};var wH=`${Ie("gray",en)} `;var E=No(S_(),1);Ra();Zl();tn();Wl();import{execFileSync as Oo,execSync as mU,execFile as fU}from"node:child_process";import{readFileSync as Xr,writeFileSync as hU,cpSync as vT,accessSync as ST,existsSync as He,rmSync as Io,closeSync as gU,openSync as yU,chmodSync as _U,constants as kT}from"node:fs";import{request as bU}from"node:https";import{resolve as ce,dirname as Qy,join as bt}from"node:path";import{tmpdir as vU,devNull as xU,homedir as xT}from"node:os";import{fileURLToPath as SU,pathToFileURL as Sl}from"node:url";import{existsSync as P_,readFileSync as R_,writeFileSync as C_}from"node:fs";import{resolve as Ps,sep as O_}from"node:path";var I_=/[/\\]context-mode-upgrade-\d+[/\\]/,Gl="${CLAUDE_PLUGIN_ROOT}/start.mjs";function Kl({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=Ps(t),s=Ps(e)+O_;if(!n.startsWith(s))return{healed:[],skipped:"outside-cache-root"};let o=Ps(t,".claude-plugin","plugin.json");if(!P_(o))return{healed:[],skipped:"no-plugin-json"};let i;try{i=R_(o,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],m=d.args,h=m.map(f=>typeof f!="string"?f:I_.test(f)&&/[/\\]start\.mjs$/.test(f)?Gl:f);if(h.some((f,g)=>f!==m[g])){d.args=h,l.push("plugin-json-args");try{C_(o,JSON.stringify(a,null,2)+`
1011
- `,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:l}}function Jl({pluginRoot:t,pluginCacheRoot:e,pluginKey:r}){if(!t||!e||!r)return{healed:[],skipped:"missing-args"};let n=Ps(t),s=Ps(e)+O_;if(!n.startsWith(s))return{healed:[],skipped:"outside-cache-root"};let o=Ps(t,".mcp.json");if(!P_(o))return{healed:[],skipped:"no-mcp-json"};let i;try{i=R_(o,"utf-8")}catch(f){return{healed:[],error:`read-failed: ${f&&f.message||f}`}}let a;try{a=JSON.parse(i)}catch(f){return{healed:[],error:`parse-failed: ${f&&f.message||f}`}}let c=a&&a.mcpServers;if(!c||typeof c!="object")return{healed:[],skipped:"no-mcp-servers"};let u=r.split("@")[0],d=c[u];if(!d||typeof d!="object"||!Array.isArray(d.args))return{healed:[],skipped:"no-our-server"};let l=[],m=d.args,h=m.map(f=>typeof f!="string"?f:f==="./start.mjs"||f==="start.mjs"||I_.test(f)&&/[/\\]start\.mjs$/.test(f)?Gl:f);if(h.some((f,g)=>f!==m[g])){d.args=h,l.push("mcp-json-args");try{C_(o,JSON.stringify(a,null,2)+`
1012
- `,"utf-8")}catch(f){return{healed:[],error:`write-failed: ${f&&f.message||f}`}}}return{healed:l}}import{existsSync as UP}from"node:fs";import{execSync as HP,execFileSync as ZH,spawnSync as BH}from"node:child_process";function A_({platform:t=process.platform,existsSync:e=UP,exec:r=HP,now:n=()=>new Date().getFullYear()}={}){if(t!=="win32")return null;try{let s="C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";if(!e(s))return null;let i=r(`"${s}" -latest -property displayName`,{encoding:"utf-8",stdio:"pipe",timeout:15e3}).trim().match(/\b(20\d{2})\b/);if(!i)return null;let a=Number(i[1]),c=n()+5;if(a>c){try{process.stderr.write(`[context-mode] vswhere displayName reports VS year ${a} (> ${c}); ignoring as likely corrupted output. Falling back to node-gyp default detection.
1013
- `)}catch{}return null}return i[1]}catch{return null}}Un();function kU(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 wU={"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 EU(t,e){try{gU(2),yU(xU,"w")}catch{process.stderr.write=(()=>!0)}let r=wU[t]?.[e];r||process.exit(1);let n=Es();await import(Sl(bt(n,r)).href)}var tr=process.argv.slice(2);if(tr[0]==="doctor")OU().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;AU(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"?EU(tr[1],tr[2]):tr[0]==="insight"?IU(tr[1]?Number(tr[1]):4747):tr[0]==="statusline"?NU():Promise.resolve().then(()=>(dT(),lT));function cK(t){return t.replace(/\\/g,"/")}var kl=process.platform==="win32";function xl(t,e={}){Oo(kl?"npm.cmd":"npm",t,{...e,...kl?{shell:!0}:{}})}function $U(t,e={}){let r={...e,...kl?{shell:!0}:{}};mU(kl?t.replace(/^npm /,"npm.cmd "):t,r)}function TU(t,e=process.platform,r=fU){let n={stdio:"ignore"},s=()=>console.error(`
1014
- Could not auto-open browser. Open manually: ${t}`),o=kU(t,e),i=!1;for(let{cmd:a,args:c}of o)try{r(a,c,n),i=!0;break}catch{}i||s()}function PU(){let t=SU(import.meta.url),e=Qy(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?ce(e,".."):e}function RU(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?ce(r,t,...e):ce(xT(),"AppData","Local",t,...e)}return ce(xT(),".cache",t,...e)}function Es(){let t=ir().platform;return t==="opencode"||t==="kilo"?RU(t):PU()}function wT(){try{return JSON.parse(Xr(ce(Es(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function CU(){return new Promise(t=>{let e=bU("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 OU(){process.stdout.isTTY&&console.clear();let t=ir(),e=await Bo(t.platform);zl(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=Fl();n.start("Running diagnostics");let s,o;try{s=Ts(),o=Pa(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")),ka(E.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),Ll(Ta(s),"Runtimes");{let{hasModernSqlite:f}=await Promise.resolve().then(()=>($n(),yy));process.platform==="linux"&&!f()&&!Cn()&&(r++,A.error(E.default.red("Node version: FAIL")+` \u2014 Linux + Node ${process.versions.node} is unsafe (SIGSEGV)`+E.default.dim(`
1008
+ ${Ae("gray",l+T_.repeat(c+2)+fP)}
1009
+ `)};var SP=t=>Ae("magenta",t),Wl=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:o=Zl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=Zl?80:120,signal:a,...c}={})=>{let u=aP(),d,l,m=!1,h=!1,p="",f,g=performance.now(),y=Hl(r),b=c?.styleFrame??SP,_=fe=>{let it=fe>1?s??xr.messages.error:n??xr.messages.cancel;h=fe===1,m&&(X(it,fe),h&&typeof e=="function"&&e())},S=()=>_(2),v=()=>_(1),P=()=>{process.on("uncaughtExceptionMonitor",S),process.on("unhandledRejection",S),process.on("SIGINT",v),process.on("SIGTERM",v),process.on("exit",_),a&&a.addEventListener("abort",v)},T=()=>{process.removeListener("uncaughtExceptionMonitor",S),process.removeListener("unhandledRejection",S),process.removeListener("SIGINT",v),process.removeListener("SIGTERM",v),process.removeListener("exit",_),a&&a.removeEventListener("abort",v)},$=()=>{if(f===void 0)return;u&&r.write(`
1010
+ `);let fe=Ts(f,y,{hard:!0,trim:!1}).split(`
1011
+ `);fe.length>1&&r.write(zo.cursor.up(fe.length-1)),r.write(zo.cursor.to(0)),r.write(zo.erase.down())},D=fe=>fe.replace(/\.+$/,""),R=fe=>{let it=(performance.now()-fe)/1e3,pt=Math.floor(it/60),nr=Math.floor(it%60);return pt>0?`[${pt}m ${nr}s]`:`[${nr}s]`},C=c.withGuide??xr.withGuide,L=(fe="")=>{m=!0,d=$_({output:r}),p=D(fe),g=performance.now(),C&&r.write(`${Ae("gray",tn)}
1012
+ `);let it=0,pt=0;P(),l=setInterval(()=>{if(u&&p===f)return;$(),f=p;let nr=b(o[it]),On;if(u)On=`${nr} ${p}...`;else if(t==="timer")On=`${nr} ${p} ${R(g)}`;else{let Sa=".".repeat(Math.floor(pt)).slice(0,3);On=`${nr} ${p}${Sa}`}let Do=Ts(On,y,{hard:!0,trim:!1});r.write(Do),it=it+1<o.length?it+1:0,pt=pt<4?pt+.125:0},i)},X=(fe="",it=0,pt=!1)=>{if(!m)return;m=!1,clearInterval(l),$();let nr=it===0?Ae("green",Bl):it===1?Ae("red",cP):Ae("red",uP);p=fe??p,pt||(t==="timer"?r.write(`${nr} ${p} ${R(g)}
1013
+ `):r.write(`${nr} ${p}
1014
+ `)),T(),d()};return{start:L,stop:(fe="")=>X(fe,0),message:(fe="")=>{p=D(fe??p)},cancel:(fe="")=>X(fe,1),error:(fe="")=>X(fe,2),clear:()=>X("",0,!0),get isCancelled(){return h}}},CH={light:ye("\u2500","-"),heavy:ye("\u2501","="),block:ye("\u2588","#")};var OH=`${Ae("gray",tn)} `;var E=Mo(C_(),1);Aa();Yl();rn();Gd();Yd();import{execFileSync as Ao,execSync as vU,execFile as xU}from"node:child_process";import{readFileSync as Qr,writeFileSync as SU,cpSync as $T,accessSync as TT,existsSync as He,rmSync as No,closeSync as kU,openSync as wU,chmodSync as EU,constants as PT}from"node:fs";import{request as $U}from"node:https";import{resolve as ie,dirname as i_,join as bt}from"node:path";import{tmpdir as TU,devNull as PU,homedir as a_}from"node:os";import{fileURLToPath as RU,pathToFileURL as Rl}from"node:url";import{existsSync as wC}from"node:fs";import{execSync as EC,execFileSync as dq,spawnSync as pq}from"node:child_process";function nv({platform:t=process.platform,existsSync:e=wC,exec:r=EC,now:n=()=>new Date().getFullYear()}={}){if(t!=="win32")return null;try{let s="C:\\Program Files (x86)\\Microsoft Visual Studio\\Installer\\vswhere.exe";if(!e(s))return null;let i=r(`"${s}" -latest -property displayName`,{encoding:"utf-8",stdio:"pipe",timeout:15e3}).trim().match(/\b(20\d{2})\b/);if(!i)return null;let a=Number(i[1]),c=n()+5;if(a>c){try{process.stderr.write(`[context-mode] vswhere displayName reports VS year ${a} (> ${c}); ignoring as likely corrupted output. Falling back to node-gyp default detection.
1015
+ `)}catch{}return null}return i[1]}catch{return null}}on();function CU(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 OU={"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 IU(t,e){try{kU(2),wU(PU,"w")}catch{process.stderr.write=(()=>!0)}let r=OU[t]?.[e];r||process.exit(1);let n=$s();await import(Rl(bt(n,r)).href)}var rr=process.argv.slice(2);if(rr[0]==="doctor")zU().then(t=>process.exit(t));else if(rr[0]==="upgrade"){let t=rr.indexOf("--platform"),e=t>=0&&rr[t+1]?rr[t+1]:void 0;FU(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 rr[0]==="hook"?IU(rr[1],rr[2]):rr[0]==="insight"?LU(rr[1]?Number(rr[1]):4747):rr[0]==="statusline"?UU():Promise.resolve().then(()=>(yT(),gT));function fK(t){return t.replace(/\\/g,"/")}var Cl=process.platform==="win32";function Pl(t,e={}){Ao(Cl?"npm.cmd":"npm",t,{...e,...Cl?{shell:!0}:{}})}function AU(t,e={}){let r={...e,...Cl?{shell:!0}:{}};vU(Cl?t.replace(/^npm /,"npm.cmd "):t,r)}function NU(t,e=process.platform,r=xU){let n={stdio:"ignore"},s=()=>console.error(`
1016
+ Could not auto-open browser. Open manually: ${t}`),o=CU(t,e),i=!1;for(let{cmd:a,args:c}of o)try{r(a,c,n),i=!0;break}catch{}i||s()}function DU(){let t=RU(import.meta.url),e=i_(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?ie(e,".."):e}function MU(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?ie(r,t,...e):ie(a_(),"AppData","Local",t,...e)}return ie(a_(),".cache",t,...e)}function $s(){let t=It().platform;return t==="opencode"||t==="kilo"?MU(t):DU()}function RT(){try{return JSON.parse(Qr(ie($s(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function jU(){return new Promise(t=>{let e=$U("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 zU(){process.stdout.isTTY&&console.clear();let t=It(),e=await Vo(t.platform);ql(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=Wl();n.start("Running diagnostics");let s,o;try{s=Ps(),o=Ia(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")),Ta(E.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),Vl(Oa(s),"Runtimes");{let{hasModernSqlite:f}=await Promise.resolve().then(()=>(Pn(),wy));process.platform==="linux"&&!f()&&!In()&&(r++,A.error(E.default.red("Node version: FAIL")+` \u2014 Linux + Node ${process.versions.node} is unsafe (SIGSEGV)`+E.default.dim(`
1015
1017
  context-mode requires Node.js >= 22.5 (or Bun) on Linux to avoid the
1016
1018
  V8 madvise(MADV_DONTNEED) SIGSEGV in better-sqlite3 (1-4/hour).
1017
1019
  Refs: https://github.com/nodejs/node/issues/62515
1018
1020
  https://github.com/mksglu/context-mode/issues/564
1019
1021
  Fix: nvm install 22.5 && nvm use 22.5 && npm install -g context-mode
1020
- Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}Cn()?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:f}=await Promise.resolve().then(()=>(my(),DE)),y=await new f({runtimes:s}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(y.exitCode===0&&y.stdout.trim()==="ok")A.success(E.default.green("Server test: PASS"));else{r++;let b=y.stderr?.trim()?` (${y.stderr.trim().slice(0,200)})`:"";A.error(E.default.red("Server test: FAIL")+` \u2014 exit ${y.exitCode}${b}`)}}catch(f){let g=f instanceof Error?f.message:String(f);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=Es(),u=e.validateHooks(c);for(let f of u)f.status==="pass"?A.success(E.default.green(`${f.check}: PASS`)+` \u2014 ${f.message}`):f.status==="warn"?A.warn(E.default.yellow(`${f.check}: WARN`)+` \u2014 ${f.message}`+(f.fix?E.default.dim(`
1022
+ Or: curl -fsSL https://bun.sh/install | bash && bun add -g context-mode`)))}In()?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:f}=await Promise.resolve().then(()=>(vy(),UE)),y=await new f({runtimes:s}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(y.exitCode===0&&y.stdout.trim()==="ok")A.success(E.default.green("Server test: PASS"));else{r++;let b=y.stderr?.trim()?` (${y.stderr.trim().slice(0,200)})`:"";A.error(E.default.red("Server test: FAIL")+` \u2014 exit ${y.exitCode}${b}`)}}catch(f){let g=f instanceof Error?f.message:String(f);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 f of u)f.status==="pass"?A.success(E.default.green(`${f.check}: PASS`)+` \u2014 ${f.message}`):f.status==="warn"?A.warn(E.default.yellow(`${f.check}: WARN`)+` \u2014 ${f.message}`+(f.fix?E.default.dim(`
1021
1023
  Run: ${f.fix}`):"")):A.error(E.default.red(`${f.check}: FAIL`)+` \u2014 ${f.message}`+(f.fix?E.default.dim(`
1022
- Run: ${f.fix}`):""));A.step("Checking hook scripts...");let d=e.getHealthChecks?.(c)??[];if(d.length>0)for(let f of d){let g=f.check();g.status==="OK"?A.success(E.default.green(`${f.name}: PASS`)+(g.detail?E.default.dim(` \u2014 ${g.detail}`):"")):A.error(E.default.red(`${f.name}: FAIL`)+(g.detail?E.default.dim(` \u2014 ${g.detail}`):""))}else{let f=Oa(e,c);if(f.length===0)A.success(E.default.green("Hook scripts: PASS")+E.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let g of f){let y=ce(c,g);try{ST(y,kT.R_OK),A.success(E.default.green("Hook script exists: PASS")+E.default.dim(` \u2014 ${y}`))}catch{A.error(E.default.red("Hook script exists: FAIL")+E.default.dim(` \u2014 not found at ${y}`))}}}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 f=(await Promise.resolve().then(()=>($n(),yy))).loadDatabase(),g=new f(":memory:");g.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),g.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let y=g.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();g.close(),y&&y.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(f){let g=f instanceof Error?f.message:String(f),y=Es(),b=ce(y,"node_modules","better-sqlite3");!He(b)?(r++,A.error(E.default.red("FTS5 / better-sqlite3: FAIL")+E.default.dim(" \u2014 package-missing")+E.default.dim(`
1024
+ Run: ${f.fix}`):""));A.step("Checking hook scripts...");let d=e.getHealthChecks?.(c)??[];if(d.length>0)for(let f of d){let g=f.check();g.status==="OK"?A.success(E.default.green(`${f.name}: PASS`)+(g.detail?E.default.dim(` \u2014 ${g.detail}`):"")):A.error(E.default.red(`${f.name}: FAIL`)+(g.detail?E.default.dim(` \u2014 ${g.detail}`):""))}else{let f=Da(e,c);if(f.length===0)A.success(E.default.green("Hook scripts: PASS")+E.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let g of f){let y=ie(c,g);try{TT(y,PT.R_OK),A.success(E.default.green("Hook script exists: PASS")+E.default.dim(` \u2014 ${y}`))}catch{A.error(E.default.red("Hook script exists: FAIL")+E.default.dim(` \u2014 not found at ${y}`))}}}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 f=(await Promise.resolve().then(()=>(Pn(),wy))).loadDatabase(),g=new f(":memory:");g.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),g.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let y=g.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();g.close(),y&&y.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(f){let g=f instanceof Error?f.message:String(f),y=$s(),b=ie(y,"node_modules","better-sqlite3");!He(b)?(r++,A.error(E.default.red("FTS5 / better-sqlite3: FAIL")+E.default.dim(" \u2014 package-missing")+E.default.dim(`
1023
1025
  Path: ${b}
1024
1026
  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).
1025
1027
  Try (primary): cd "${y}" && npm install better-sqlite3 --no-optional
@@ -1027,19 +1029,19 @@ Could not auto-open browser. Open manually: ${t}`),o=kU(t,e),i=!1;for(let{cmd:a,
1027
1029
  Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
1028
1030
  Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
1029
1031
  Try (fallback): npm rebuild better-sqlite3`)):A.error(E.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${g}`+E.default.dim(`
1030
- Try: npm rebuild better-sqlite3`)))}A.step("Checking versions...");let m=wT(),h=await CU(),p=e.getInstalledVersion();return h==="unknown"?A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, could not reach npm registry`):m===h?A.success(E.default.green("npm (MCP): PASS")+` \u2014 v${m}`):A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, latest v${h}`+E.default.dim(`
1032
+ Try: npm rebuild better-sqlite3`)))}A.step("Checking versions...");let m=RT(),h=await jU(),p=e.getInstalledVersion();return h==="unknown"?A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, could not reach npm registry`):m===h?A.success(E.default.green("npm (MCP): PASS")+` \u2014 v${m}`):A.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, latest v${h}`+E.default.dim(`
1031
1033
  Run: /context-mode:ctx-upgrade`)),p==="not installed"?A.info(E.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):h!=="unknown"&&p===h?A.success(E.default.green(`${e.name}: PASS`)+` \u2014 v${p}`):h!=="unknown"?A.warn(E.default.yellow(`${e.name}: WARN`)+` \u2014 v${p}, latest v${h}`+E.default.dim(`
1032
- Run: /context-mode:ctx-upgrade`)):A.info(`${e.name}: v${p}`+E.default.dim(" \u2014 could not verify against npm registry")),r>0?(ka(E.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(ka(o.length>=4?E.default.green("Diagnostics complete!"):E.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function IU(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:s,cpSync:o}=await import("node:fs"),i=ce(Es(),"insight"),a=ir(),u=(await Bo(a.platform)).getSessionDir(),d=bt(Qy(u),"content"),l=bt(Qy(u),"insight-cache");He(bt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),s(l,{recursive:!0});let m=n(bt(i,"server.mjs")).mtimeMs,h=He(bt(l,"server.mjs"))?n(bt(l,"server.mjs")).mtimeMs:0;if(m>h&&(console.log("Copying Insight source..."),o(i,l,{recursive:!0,force:!0})),!He(bt(l,"node_modules"))){console.log("Installing dependencies (first run)...");try{$U("npm install --production=false",{cwd:l,stdio:"inherit",timeout:3e5})}catch{try{Io(bt(l,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!He(bt(l,"node_modules","vite"))||!He(bt(l,"node_modules","better-sqlite3")))throw Io(bt(l,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:l,stdio:"pipe",timeout:6e4});let p=`http://localhost:${t}`;console.log(`
1034
+ Run: /context-mode:ctx-upgrade`)):A.info(`${e.name}: v${p}`+E.default.dim(" \u2014 could not verify against npm registry")),r>0?(Ta(E.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(Ta(o.length>=4?E.default.green("Diagnostics complete!"):E.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function LU(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:s,cpSync:o}=await import("node:fs"),i=ie($s(),"insight"),a=It(),u=(await Vo(a.platform)).getSessionDir(),d=bt(i_(u),"content"),l=bt(i_(u),"insight-cache");He(bt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),s(l,{recursive:!0});let m=n(bt(i,"server.mjs")).mtimeMs,h=He(bt(l,"server.mjs"))?n(bt(l,"server.mjs")).mtimeMs:0;if(m>h&&(console.log("Copying Insight source..."),o(i,l,{recursive:!0,force:!0})),!He(bt(l,"node_modules"))){console.log("Installing dependencies (first run)...");try{AU("npm install --production=false",{cwd:l,stdio:"inherit",timeout:3e5})}catch{try{No(bt(l,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!He(bt(l,"node_modules","vite"))||!He(bt(l,"node_modules","better-sqlite3")))throw No(bt(l,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:l,stdio:"pipe",timeout:6e4});let p=`http://localhost:${t}`;console.log(`
1033
1035
  context-mode Insight
1034
1036
  ${p}
1035
1037
  `);let f=r("node",[bt(l,"server.mjs")],{cwd:l,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:d},stdio:"inherit"});f.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((y,b)=>{let _=g(`http://127.0.0.1:${t}/api/overview`,{timeout:3e3},S=>{y(),S.resume()});_.on("error",b),_.on("timeout",()=>{_.destroy(),b(new Error("timeout"))}),_.end()})}catch{console.error(`
1036
1038
  Error: Port ${t} appears to be in use. Either a previous dashboard is still running, or another service is using this port.`),console.error(`
1037
- To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),f.kill(),process.exit(1)}TU(p),process.on("SIGINT",()=>{f.kill(),process.exit(0)}),process.on("SIGTERM",()=>{f.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
1038
- Insight error: ${r}`),process.exit(1)}}async function AU(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:ir(),r=await Bo(e.platform);zl(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=Es(),s=[],o=Fl(),i=ce(Be(),"plugins","marketplaces","context-mode");if(He(bt(i,".git"))){o.start("Syncing marketplace clone");try{Oo("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`))):(Oo("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),Oo("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(m){let h=m instanceof Error?m.message:String(m);o.stop(E.default.yellow("Marketplace sync skipped")),A.warn(E.default.yellow("git refresh on marketplace failed")+` \u2014 ${h}`),A.info(E.default.dim(" Continuing \u2014 cache dir update will still happen."))}}A.step("Pulling latest from GitHub...");let a=wT(),c=bt(vU(),`context-mode-upgrade-${Date.now()}`);o.start("Cloning mksglu/context-mode");try{Oo("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),o.stop("Downloaded");let m=c,p=JSON.parse(Xr(ce(m,"package.json"),"utf-8")).version??"unknown";if(p===a)A.success(E.default.green("Already on latest")+` \u2014 v${a}`),Io(c,{recursive:!0,force:!0});else{A.info(`Update available: ${E.default.yellow("v"+a)} \u2192 ${E.default.green("v"+p)}`);try{let v=Ia({ownPid:process.pid,ownPpid:process.ppid});if(v.length>0){let R=await Aa({pids:v});if(R.totalKilled>0){let $=R.totalKilled===1?"sibling MCP server":"sibling MCP servers";A.info(E.default.dim(`Stopped ${R.totalKilled} ${$} (SIGTERM: ${R.terminatedBySigterm}, SIGKILL: ${R.terminatedBySigkill})`))}}}catch{}o.start("Installing dependencies & building");let f=A_();xl(["install","--no-audit","--no-fund"],{cwd:m,stdio:"pipe",timeout:12e4,...f?{env:{...process.env,npm_config_msvs_version:f}}:{}}),xl(["run","build"],{cwd:m,stdio:"pipe",timeout:6e4}),o.stop("Built successfully"),o.start("Updating files in-place");let y=[...JSON.parse(Xr(ce(m,"package.json"),"utf-8")).files||[],"src","package.json"];for(let v of y)try{Io(ce(n,v),{recursive:!0,force:!0}),vT(ce(m,v),ce(n,v),{recursive:!0})}catch{}let b={mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}};hU(ce(n,".mcp.json"),JSON.stringify(b,null,2)+`
1039
- `);try{(await Promise.resolve().then(()=>(bT(),_T))).normalizeHooksOnStartup({pluginRoot:n,nodePath:process.execPath,platform:process.platform})}catch{}o.stop(E.default.green(`Updated in-place to v${p}`));let _=ce(n,".claude-plugin","plugin.json"),S=null;try{let v=JSON.parse(Xr(_,"utf-8"));v&&typeof v.version=="string"&&(S=v.version)}catch{}if(S!==p)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${S??"<missing>"}" but newVersion is "${p}". Refusing to bump registry.`);r.updatePluginRegistry(n,p),A.info(E.default.dim(" Registry synced to "+n));try{let v=ce(Be(),"plugins","installed_plugins.json");if(He(v)){let $=JSON.parse(Xr(v,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray($))for(let T of $){let D=T?.installPath;if(typeof D!="string"||!D)continue;if(!He(D))throw new Error(`installPath does not exist on disk: ${D}`);let P=ce(D,".claude-plugin","plugin.json");if(!He(P))throw new Error(`missing plugin.json manifest at ${P}`);let C=JSON.parse(Xr(P,"utf-8"));if(C?.version!==T.version)throw new Error(`version mismatch \u2014 registry says "${T.version}" but ${P} says "${C?.version}"`)}}}catch(v){let R=v instanceof Error?v.message:String(v);throw new Error(`Registry consistency check failed: ${R}`)}try{let v=ce(Be(),"plugins","cache"),R="context-mode@context-mode",$=Kl({pluginRoot:n,pluginCacheRoot:v,pluginKey:R});if($&&$.error)throw new Error($.error);let T=Kl({pluginRoot:n,pluginCacheRoot:v,pluginKey:R});if(T&&Array.isArray(T.healed)&&T.healed.length>0)throw new Error(`Plugin manifest drift: plugin.json mcpServers.args still poisoned after first heal pass (healed=${T.healed.join(",")})`)}catch(v){let R=v instanceof Error?v.message:String(v);throw new Error(`plugin.json drift check failed: ${R}`)}try{let v=ce(Be(),"plugins","cache"),R="context-mode@context-mode",$=Jl({pluginRoot:n,pluginCacheRoot:v,pluginKey:R});if($&&$.error)throw new Error($.error);let T=Jl({pluginRoot:n,pluginCacheRoot:v,pluginKey:R});if(T&&Array.isArray(T.healed)&&T.healed.length>0)throw new Error(`.mcp.json drift: mcpServers.args still poisoned after first heal pass (healed=${T.healed.join(",")})`)}catch(v){let R=v instanceof Error?v.message:String(v);throw new Error(`.mcp.json drift check failed: ${R}`)}try{let v=ce(i,".claude-plugin","plugin.json");if(He(v)){let R=JSON.parse(Xr(v,"utf-8"));R?.version!==p&&(A.warn(E.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${R?.version}" but expected "${p}"`),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"),xl(["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 v=ce(n,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let $=ce(n,"hooks","ensure-deps.mjs");if(!He($))throw new Error(`missing ${$}`);await import(`${Sl($).href}?upgrade=${Date.now()}`),He(v)?(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($){let T=$ instanceof Error?$.message:String($);o.stop(E.default.yellow("Native addon ABI bootstrap unavailable")),A.warn(E.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${T}`+E.default.dim(`
1040
- Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let R=ce(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!He(R))try{let $=ce(n,"scripts","heal-better-sqlite3.mjs");if(He($)){let T=await import(`${Sl($).href}?upgrade=${Date.now()}`);typeof T.healBetterSqlite3Binding=="function"&&T.healBetterSqlite3Binding(n)}}catch{}He(R)||(process.exitCode=1,A.error(E.default.red("better-sqlite3 native binding: MISSING")+E.default.dim(`
1041
- Path: ${R}`)+E.default.dim(`
1039
+ To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),f.kill(),process.exit(1)}NU(p),process.on("SIGINT",()=>{f.kill(),process.exit(0)}),process.on("SIGTERM",()=>{f.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
1040
+ Insight error: ${r}`),process.exit(1)}}async function FU(t){process.stdout.isTTY&&console.clear();let e=t?.platform?{platform:t.platform,confidence:"high",reason:`--platform ${t.platform} from ctx_upgrade handler`}:It(),r=await Vo(e.platform);ql(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=Wl(),i=ie(Ze(),"plugins","marketplaces","context-mode");if(He(bt(i,".git"))){o.start("Syncing marketplace clone");try{Ao("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`))):(Ao("git",["-C",i,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),Ao("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(m){let h=m instanceof Error?m.message:String(m);o.stop(E.default.yellow("Marketplace sync skipped")),A.warn(E.default.yellow("git refresh on marketplace failed")+` \u2014 ${h}`),A.info(E.default.dim(" Continuing \u2014 cache dir update will still happen."))}}A.step("Pulling latest from GitHub...");let a=RT(),c=bt(TU(),`context-mode-upgrade-${Date.now()}`);o.start("Cloning mksglu/context-mode");try{Ao("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",c],{stdio:"pipe",timeout:3e4}),o.stop("Downloaded");let m=c,p=JSON.parse(Qr(ie(m,"package.json"),"utf-8")).version??"unknown";if(p===a)A.success(E.default.green("Already on latest")+` \u2014 v${a}`),No(c,{recursive:!0,force:!0});else{A.info(`Update available: ${E.default.yellow("v"+a)} \u2192 ${E.default.green("v"+p)}`);try{let v=Ja({ownPid:process.pid,ownPpid:process.ppid});if(v.length>0){let P=await Ya({pids:v});if(P.totalKilled>0){let T=P.totalKilled===1?"sibling MCP server":"sibling MCP servers";A.info(E.default.dim(`Stopped ${P.totalKilled} ${T} (SIGTERM: ${P.terminatedBySigterm}, SIGKILL: ${P.terminatedBySigkill})`))}}}catch{}o.start("Installing dependencies & building");let f=nv();Pl(["install","--no-audit","--no-fund"],{cwd:m,stdio:"pipe",timeout:12e4,...f?{env:{...process.env,npm_config_msvs_version:f}}:{}}),Pl(["run","build"],{cwd:m,stdio:"pipe",timeout:6e4}),o.stop("Built successfully"),o.start("Updating files in-place");let y=[...JSON.parse(Qr(ie(m,"package.json"),"utf-8")).files||[],"src","package.json"];for(let v of y)try{No(ie(n,v),{recursive:!0,force:!0}),$T(ie(m,v),ie(n,v),{recursive:!0})}catch{}let b={mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}};SU(ie(n,".mcp.json"),JSON.stringify(b,null,2)+`
1041
+ `);try{(await Promise.resolve().then(()=>(ET(),wT))).normalizeHooksOnStartup({pluginRoot:n,nodePath:process.execPath,platform:process.platform})}catch{}o.stop(E.default.green(`Updated in-place to v${p}`));let _=ie(n,".claude-plugin","plugin.json"),S=null;try{let v=JSON.parse(Qr(_,"utf-8"));v&&typeof v.version=="string"&&(S=v.version)}catch{}if(S!==p)throw new Error(`pluginRoot manifest version mismatch \u2014 disk says "${S??"<missing>"}" but newVersion is "${p}". Refusing to bump registry.`);r.updatePluginRegistry(n,p),A.info(E.default.dim(" Registry synced to "+n));try{let v=ie(Ze(),"plugins","installed_plugins.json");if(He(v)){let T=JSON.parse(Qr(v,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(T))for(let $ of T){let D=$?.installPath;if(typeof D!="string"||!D)continue;if(!He(D))throw new Error(`installPath does not exist on disk: ${D}`);let R=ie(D,".claude-plugin","plugin.json");if(!He(R))throw new Error(`missing plugin.json manifest at ${R}`);let C=JSON.parse(Qr(R,"utf-8"));if(C?.version!==$.version)throw new Error(`version mismatch \u2014 registry says "${$.version}" but ${R} says "${C?.version}"`)}}}catch(v){let P=v instanceof Error?v.message:String(v);throw new Error(`Registry consistency check failed: ${P}`)}try{let v=ie(Ze(),"plugins","cache"),P="context-mode@context-mode",T=Xa({pluginRoot:n,pluginCacheRoot:v,pluginKey:P});if(T&&T.error)throw new Error(T.error);let $=Xa({pluginRoot:n,pluginCacheRoot:v,pluginKey:P});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(v){let P=v instanceof Error?v.message:String(v);throw new Error(`plugin.json drift check failed: ${P}`)}try{let v=ie(Ze(),"plugins","cache"),P="context-mode@context-mode",T=Qa({pluginRoot:n,pluginCacheRoot:v,pluginKey:P});if(T&&T.error)throw new Error(T.error);let $=Qa({pluginRoot:n,pluginCacheRoot:v,pluginKey:P});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(v){let P=v instanceof Error?v.message:String(v);throw new Error(`.mcp.json drift check failed: ${P}`)}try{let{healClaudeJsonMcpArgs:v}=await Promise.resolve().then(()=>(Yd(),rv)),P=ie(a_(),".claude.json"),T=ie(Ze(),"plugins","cache","context-mode","context-mode"),$=v({dotClaudeJsonPath:P,pluginCacheParent:T,newPluginRoot:n});$.healed&&$.healed.length>0&&A.info(E.default.dim(" ~/.claude.json user MCP registrations updated \u2192 "+p))}catch{}try{let v=ie(i,".claude-plugin","plugin.json");if(He(v)){let P=JSON.parse(Qr(v,"utf-8"));P?.version!==p&&(A.warn(E.default.yellow("Marketplace clone version mismatch")+` \u2014 ${i} reports "${P?.version}" but expected "${p}"`),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"),Pl(["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 v=ie(n,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let T=ie(n,"hooks","ensure-deps.mjs");if(!He(T))throw new Error(`missing ${T}`);await import(`${Rl(T).href}?upgrade=${Date.now()}`),He(v)?(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(T){let $=T instanceof Error?T.message:String(T);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(`
1042
+ Try manually: cd "${n}" && npm rebuild better-sqlite3`))}let P=ie(n,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(!He(P))try{let T=ie(n,"scripts","heal-better-sqlite3.mjs");if(He(T)){let $=await import(`${Rl(T).href}?upgrade=${Date.now()}`);typeof $.healBetterSqlite3Binding=="function"&&$.healBetterSqlite3Binding(n)}}catch{}He(P)||(process.exitCode=1,A.error(E.default.red("better-sqlite3 native binding: MISSING")+E.default.dim(`
1043
+ Path: ${P}`)+E.default.dim(`
1042
1044
  Cause: npm silently skipped the package (Node engine mismatch, issue #514)`)+E.default.dim(`
1043
1045
  Try (primary): cd "${n}" && npm install better-sqlite3 --no-optional`)+E.default.dim(`
1044
- Try (fallback): /context-mode:ctx-doctor`)))}o.start("Updating npm global package");try{xl(["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"))}Io(c,{recursive:!0,force:!0});try{let v=ce(Be(),"plugins","installed_plugins.json");if(He(v)){let $=JSON.parse(Xr(v,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray($))for(let T of $){let D=T.installPath;if(D&&D!==n&&He(D)){let P=ce(m,"skills");He(P)&&(vT(P,ce(D,"skills"),{recursive:!0}),s.push("Synced skills to active install path"))}}}}catch{}s.push(`Updated v${a} \u2192 v${p}`),A.success(E.default.green("Plugin reinstalled from GitHub!")+E.default.dim(` \u2014 v${p}`))}}catch(m){let h=m instanceof Error?m.message:String(m);o.stop(E.default.red("Update failed")),A.error(E.default.red("GitHub pull failed")+` \u2014 ${h}`),A.info(E.default.dim("Continuing with hooks/settings fix..."));try{Io(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 m=r.configureAllHooks(n);for(let h of m)A.info(E.default.dim(` ${h}`)),s.push(h);A.success(E.default.green("Hooks configured")+E.default.dim(` \u2014 ${r.name}`))}catch(m){let h=m instanceof Error?m.message:String(m);throw new Error(`Hook configuration failed: ${h}`)}A.step("Setting hook script permissions...");let d=r.setHookPermissions(n);if(process.platform!=="win32")for(let m of["build/cli.js","cli.bundle.mjs"]){let h=ce(n,m);try{ST(h,kT.F_OK),_U(h,493),d.push(h)}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 "+ce(n,"hooks"))),s.length>0?Ll(s.map(m=>E.default.green(" + ")+m).join(`
1045
- `),"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 m=ce(n,"cli.bundle.mjs"),h=ce(n,"build","cli.js"),p=He(m)?m:h;Oo("node",[p,"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 NU(){let t=Be(),e=[ce(Es(),"bin","statusline.mjs"),ce(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=ce(t,"plugins","installed_plugins.json");if(He(n)){let o=JSON.parse(Xr(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(ce(a,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>He(n));r||process.exit(0),import(Sl(r).href).catch(()=>{process.exit(0)})}export{$U as npmExec,xl as npmExecFile,TU as openInBrowser,cK as toUnixPath};
1046
+ Try (fallback): /context-mode:ctx-doctor`)))}o.start("Updating npm global package");try{Pl(["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"))}No(c,{recursive:!0,force:!0});try{let v=ie(Ze(),"plugins","installed_plugins.json");if(He(v)){let T=JSON.parse(Qr(v,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(T))for(let $ of T){let D=$.installPath;if(D&&D!==n&&He(D)){let R=ie(m,"skills");He(R)&&($T(R,ie(D,"skills"),{recursive:!0}),s.push("Synced skills to active install path"))}}}}catch{}s.push(`Updated v${a} \u2192 v${p}`),A.success(E.default.green("Plugin reinstalled from GitHub!")+E.default.dim(` \u2014 v${p}`))}}catch(m){let h=m instanceof Error?m.message:String(m);o.stop(E.default.red("Update failed")),A.error(E.default.red("GitHub pull failed")+` \u2014 ${h}`),A.info(E.default.dim("Continuing with hooks/settings fix..."));try{No(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 m=r.configureAllHooks(n);for(let h of m)A.info(E.default.dim(` ${h}`)),s.push(h);A.success(E.default.green("Hooks configured")+E.default.dim(` \u2014 ${r.name}`))}catch(m){let h=m instanceof Error?m.message:String(m);throw new Error(`Hook configuration failed: ${h}`)}A.step("Setting hook script permissions...");let d=r.setHookPermissions(n);if(process.platform!=="win32")for(let m of["build/cli.js","cli.bundle.mjs"]){let h=ie(n,m);try{TT(h,PT.F_OK),EU(h,493),d.push(h)}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 "+ie(n,"hooks"))),s.length>0?Vl(s.map(m=>E.default.green(" + ")+m).join(`
1047
+ `),"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 m=ie(n,"cli.bundle.mjs"),h=ie(n,"build","cli.js"),p=He(m)?m:h;Ao("node",[p,"doctor"],{stdio:"inherit",timeout:3e4,cwd:n,env:{...process.env,CONTEXT_MODE_PLATFORM:e.platform}})}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 UU(){let t=Ze(),e=[ie($s(),"bin","statusline.mjs"),ie(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=ie(t,"plugins","installed_plugins.json");if(He(n)){let o=JSON.parse(Qr(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(ie(a,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>He(n));r||process.exit(0),import(Rl(r).href).catch(()=>{process.exit(0)})}export{AU as npmExec,Pl as npmExecFile,NU as openInBrowser,fK as toUnixPath};