context-mode 1.0.110 → 1.0.112

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 (151) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/.openclaw-plugin/index.ts +3 -2
  4. package/.openclaw-plugin/openclaw.plugin.json +1 -1
  5. package/.openclaw-plugin/package.json +1 -1
  6. package/README.md +152 -34
  7. package/bin/statusline.mjs +144 -127
  8. package/build/adapters/base.d.ts +8 -5
  9. package/build/adapters/base.js +8 -18
  10. package/build/adapters/claude-code/index.d.ts +24 -3
  11. package/build/adapters/claude-code/index.js +44 -11
  12. package/build/adapters/codex/hooks.d.ts +10 -5
  13. package/build/adapters/codex/hooks.js +10 -5
  14. package/build/adapters/codex/index.d.ts +17 -5
  15. package/build/adapters/codex/index.js +337 -37
  16. package/build/adapters/codex/paths.d.ts +1 -0
  17. package/build/adapters/codex/paths.js +12 -0
  18. package/build/adapters/cursor/index.d.ts +6 -0
  19. package/build/adapters/cursor/index.js +83 -2
  20. package/build/adapters/detect.d.ts +1 -1
  21. package/build/adapters/detect.js +29 -6
  22. package/build/adapters/omp/index.d.ts +65 -0
  23. package/build/adapters/omp/index.js +182 -0
  24. package/build/adapters/omp/plugin.d.ts +75 -0
  25. package/build/adapters/omp/plugin.js +220 -0
  26. package/build/adapters/openclaw/mcp-tools.d.ts +54 -0
  27. package/build/adapters/openclaw/mcp-tools.js +198 -0
  28. package/build/adapters/openclaw/plugin.d.ts +130 -0
  29. package/build/adapters/openclaw/plugin.js +629 -0
  30. package/build/adapters/openclaw/workspace-router.d.ts +29 -0
  31. package/build/adapters/openclaw/workspace-router.js +64 -0
  32. package/build/adapters/opencode/plugin.d.ts +145 -0
  33. package/build/adapters/opencode/plugin.js +457 -0
  34. package/build/adapters/pi/extension.d.ts +26 -0
  35. package/build/adapters/pi/extension.js +552 -0
  36. package/build/adapters/pi/index.d.ts +57 -0
  37. package/build/adapters/pi/index.js +173 -0
  38. package/build/adapters/pi/mcp-bridge.d.ts +113 -0
  39. package/build/adapters/pi/mcp-bridge.js +251 -0
  40. package/build/adapters/types.d.ts +11 -6
  41. package/build/cli.js +186 -170
  42. package/build/db-base.d.ts +15 -2
  43. package/build/db-base.js +50 -5
  44. package/build/executor.d.ts +2 -0
  45. package/build/executor.js +15 -2
  46. package/build/opencode-plugin.js +1 -1
  47. package/build/runPool.d.ts +36 -0
  48. package/build/runPool.js +51 -0
  49. package/build/runtime.js +64 -5
  50. package/build/search/auto-memory.js +6 -4
  51. package/build/security.js +30 -10
  52. package/build/server.d.ts +23 -1
  53. package/build/server.js +652 -174
  54. package/build/session/analytics.d.ts +404 -1
  55. package/build/session/analytics.js +1347 -42
  56. package/build/session/db.d.ts +114 -5
  57. package/build/session/db.js +275 -27
  58. package/build/session/event-emit.d.ts +48 -0
  59. package/build/session/event-emit.js +101 -0
  60. package/build/session/extract.d.ts +1 -0
  61. package/build/session/extract.js +79 -12
  62. package/build/session/purge.d.ts +111 -0
  63. package/build/session/purge.js +138 -0
  64. package/build/store.d.ts +7 -0
  65. package/build/store.js +69 -6
  66. package/build/util/claude-config.d.ts +26 -0
  67. package/build/util/claude-config.js +91 -0
  68. package/build/util/hook-config.d.ts +4 -0
  69. package/build/util/hook-config.js +39 -0
  70. package/cli.bundle.mjs +411 -208
  71. package/configs/antigravity/GEMINI.md +0 -3
  72. package/configs/claude-code/CLAUDE.md +1 -4
  73. package/configs/codex/AGENTS.md +1 -4
  74. package/configs/codex/config.toml +3 -0
  75. package/configs/codex/hooks.json +8 -0
  76. package/configs/cursor/context-mode.mdc +0 -3
  77. package/configs/gemini-cli/GEMINI.md +0 -3
  78. package/configs/jetbrains-copilot/copilot-instructions.md +0 -3
  79. package/configs/kilo/AGENTS.md +0 -3
  80. package/configs/kiro/KIRO.md +0 -3
  81. package/configs/omp/SYSTEM.md +85 -0
  82. package/configs/omp/mcp.json +7 -0
  83. package/configs/openclaw/AGENTS.md +0 -3
  84. package/configs/opencode/AGENTS.md +0 -3
  85. package/configs/pi/AGENTS.md +0 -3
  86. package/configs/qwen-code/QWEN.md +1 -4
  87. package/configs/vscode-copilot/copilot-instructions.md +0 -3
  88. package/configs/zed/AGENTS.md +0 -3
  89. package/hooks/codex/posttooluse.mjs +9 -2
  90. package/hooks/codex/precompact.mjs +69 -0
  91. package/hooks/codex/sessionstart.mjs +13 -9
  92. package/hooks/codex/stop.mjs +1 -2
  93. package/hooks/codex/userpromptsubmit.mjs +1 -2
  94. package/hooks/core/routing.mjs +237 -18
  95. package/hooks/cursor/afteragentresponse.mjs +1 -1
  96. package/hooks/cursor/hooks.json +31 -0
  97. package/hooks/cursor/posttooluse.mjs +1 -1
  98. package/hooks/cursor/sessionstart.mjs +5 -5
  99. package/hooks/cursor/stop.mjs +1 -1
  100. package/hooks/ensure-deps.mjs +12 -13
  101. package/hooks/gemini-cli/aftertool.mjs +1 -1
  102. package/hooks/gemini-cli/beforeagent.mjs +1 -1
  103. package/hooks/gemini-cli/precompress.mjs +3 -2
  104. package/hooks/gemini-cli/sessionstart.mjs +9 -9
  105. package/hooks/jetbrains-copilot/posttooluse.mjs +1 -1
  106. package/hooks/jetbrains-copilot/precompact.mjs +3 -2
  107. package/hooks/jetbrains-copilot/sessionstart.mjs +9 -9
  108. package/hooks/kiro/agentspawn.mjs +5 -5
  109. package/hooks/kiro/posttooluse.mjs +2 -2
  110. package/hooks/kiro/userpromptsubmit.mjs +1 -1
  111. package/hooks/posttooluse.mjs +45 -0
  112. package/hooks/precompact.mjs +17 -0
  113. package/hooks/pretooluse.mjs +23 -0
  114. package/hooks/routing-block.mjs +0 -12
  115. package/hooks/run-hook.mjs +16 -3
  116. package/hooks/session-db.bundle.mjs +27 -18
  117. package/hooks/session-extract.bundle.mjs +2 -2
  118. package/hooks/session-helpers.mjs +101 -64
  119. package/hooks/sessionstart.mjs +51 -2
  120. package/hooks/vscode-copilot/posttooluse.mjs +1 -1
  121. package/hooks/vscode-copilot/precompact.mjs +3 -2
  122. package/hooks/vscode-copilot/sessionstart.mjs +9 -9
  123. package/openclaw.plugin.json +1 -1
  124. package/package.json +14 -8
  125. package/server.bundle.mjs +349 -147
  126. package/skills/UPSTREAM-CREDITS.md +0 -51
  127. package/skills/context-mode-ops/SKILL.md +0 -299
  128. package/skills/context-mode-ops/agent-teams.md +0 -198
  129. package/skills/context-mode-ops/communication.md +0 -224
  130. package/skills/context-mode-ops/marketing.md +0 -124
  131. package/skills/context-mode-ops/release.md +0 -214
  132. package/skills/context-mode-ops/review-pr.md +0 -269
  133. package/skills/context-mode-ops/tdd.md +0 -329
  134. package/skills/context-mode-ops/triage-issue.md +0 -266
  135. package/skills/context-mode-ops/validation.md +0 -307
  136. package/skills/diagnose/SKILL.md +0 -122
  137. package/skills/diagnose/scripts/hitl-loop.template.sh +0 -41
  138. package/skills/grill-me/SKILL.md +0 -15
  139. package/skills/grill-with-docs/ADR-FORMAT.md +0 -47
  140. package/skills/grill-with-docs/CONTEXT-FORMAT.md +0 -77
  141. package/skills/grill-with-docs/SKILL.md +0 -93
  142. package/skills/improve-codebase-architecture/DEEPENING.md +0 -37
  143. package/skills/improve-codebase-architecture/INTERFACE-DESIGN.md +0 -44
  144. package/skills/improve-codebase-architecture/LANGUAGE.md +0 -53
  145. package/skills/improve-codebase-architecture/SKILL.md +0 -76
  146. package/skills/tdd/SKILL.md +0 -114
  147. package/skills/tdd/deep-modules.md +0 -33
  148. package/skills/tdd/interface-design.md +0 -31
  149. package/skills/tdd/mocking.md +0 -59
  150. package/skills/tdd/refactoring.md +0 -10
  151. package/skills/tdd/tests.md +0 -61
package/cli.bundle.mjs CHANGED
@@ -1,62 +1,77 @@
1
1
  #!/usr/bin/env node
2
- var t$=Object.create;var Eu=Object.defineProperty;var r$=Object.getOwnPropertyDescriptor;var n$=Object.getOwnPropertyNames;var o$=Object.getPrototypeOf,s$=Object.prototype.hasOwnProperty;var Cg=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var C=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ze=(t,e)=>{for(var r in e)Eu(t,r,{get:e[r],enumerable:!0})},i$=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of n$(e))!s$.call(t,o)&&o!==r&&Eu(t,o,{get:()=>e[o],enumerable:!(n=r$(e,o))||n.enumerable});return t};var fs=(t,e,r)=>(r=t!=null?t$(o$(t)):{},i$(e||!t||!t.__esModule?Eu(r,"default",{value:t,enumerable:!0}):r,t));var Au=C((nL,Hg)=>{"use strict";var Iu={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"},g$={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},_$={screen:"\x1B[2J",up:(t=1)=>"\x1B[1J".repeat(t),down:(t=1)=>"\x1B[J".repeat(t),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(t){let e="";for(let r=0;r<t;r++)e+=this.line+(r<t-1?Iu.up():"");return t&&(e+=Iu.left),e}};Hg.exports={cursor:Iu,scroll:g$,erase:_$,beep:"\x07"}});var Jg=C((LL,Fu)=>{var Wi=process||{},Gg=Wi.argv||[],Vi=Wi.env||{},Z$=!(Vi.NO_COLOR||Gg.includes("--no-color"))&&(!!Vi.FORCE_COLOR||Gg.includes("--color")||Wi.platform==="win32"||(Wi.stdout||{}).isTTY&&Vi.TERM!=="dumb"||!!Vi.CI),H$=(t,e,r=t)=>n=>{let o=""+n,s=o.indexOf(e,t.length);return~s?t+q$(o,e,r,s)+e:t+o+e},q$=(t,e,r,n)=>{let o="",s=0;do o+=t.substring(s,n)+r,s=n+e.length,n=t.indexOf(e,s);while(~n);return o+t.substring(s)},Kg=(t=Z$)=>{let e=t?H$:()=>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")}};Fu.exports=Kg();Fu.exports.createColors=Kg});import{execFileSync as B$,execSync as Yg}from"node:child_process";import{existsSync as Gi}from"node:fs";function W$(t){let e=t.split(/[\\/]/),r=e[e.length-1];return V$.test(r)}function Ve(t){try{let e=Uu?`where ${t}`:`command -v ${t}`;return Yg(e,{stdio:"pipe"}),!0}catch{return!1}}function Xg(){if(Ve("bun"))return!0;for(let t of Qg())if(Gi(t))return!0;return!1}function G$(){if(Ve("bun"))return"bun";for(let e of Qg())if(Gi(e))return e;let t=process.env.HOME??process.env.USERPROFILE??"";return Uu?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Qg(){let t=process.env.HOME??process.env.USERPROFILE??"";if(Uu){let e=process.env.LOCALAPPDATA??"";return[...t?[`${t}\\.bun\\bin\\bun.exe`]:[],...e?[`${e}\\bun\\bin\\bun.exe`]:[]]}return t?[`${t}/.bun/bin/bun`]:[]}function K$(){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(Gi(e))return e;try{let r=Yg("where bash",{encoding:"utf-8",stdio:"pipe"}).trim().split(/\r?\n/).map(n=>n.trim()).filter(Boolean);for(let n of r){let o=n.toLowerCase();if(!(o.includes("system32")||o.includes("windowsapps")))return n}return null}catch{return null}}function Bt(t,e=["--version"]){try{return B$(t,e,{encoding:"utf-8",shell:process.platform==="win32",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function so(){let e=Xg()?G$():null,r=process.env.SHELL,n=r&&Gi(r)&&W$(r)?r:null,o=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(Ve("tsx")?"tsx":Ve("ts-node")?"ts-node":null),python:Ve("python3")?"python3":Ve("python")?"python":null,shell:n??(o?K$()??(Ve("sh")?"sh":Ve("powershell")?"powershell":"cmd.exe"):Ve("bash")?"bash":"sh"),ruby:Ve("ruby")?"ruby":null,go:Ve("go")?"go":null,rust:Ve("rustc")?"rustc":null,php:Ve("php")?"php":null,perl:Ve("perl")?"perl":null,r:Ve("Rscript")?"Rscript":Ve("r")?"r":null,elixir:Ve("elixir")?"elixir":null}}function io(){return Xg()}function Ki(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${Bt(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${Bt(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${Bt(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${Bt(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${Bt(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${Bt(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${Bt(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${Bt(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${Bt(t.perl)})`),t.r&&e.push(` R: ${t.r} (${Bt(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${Bt(t.elixir)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
3
- `)}function Ji(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),e}function e_(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 o=t.shell.toLowerCase();if(o.includes("bash")||o.endsWith("/sh")||o.endsWith("\\sh.exe")){let s=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${s}'`]}if(o.includes("powershell")||o.includes("pwsh"))return[t.shell,"-File",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r]}}var V$,Uu,Yi=v(()=>{"use strict";V$=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i;Uu=process.platform==="win32"});var t_,r_=v(()=>{"use strict";t_={"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",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code"}});import{createHash as n_}from"node:crypto";import{join as _s}from"node:path";import{accessSync as J$,copyFileSync as Y$,constants as X$,mkdirSync as Q$}from"node:fs";import{homedir as o_}from"node:os";var Me,Vt=v(()=>{"use strict";Me=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=_s(o_(),...this.sessionDirSegments,"context-mode","sessions");return Q$(e,{recursive:!0}),e}getSessionDBPath(e){let r=n_("sha256").update(e).digest("hex").slice(0,16);return _s(this.getSessionDir(),`${r}.db`)}getSessionEventsPath(e){let r=n_("sha256").update(e).digest("hex").slice(0,16);return _s(this.getSessionDir(),`${r}-events.md`)}getConfigDir(e){return _s(o_(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(){return _s(this.getConfigDir(),"memory")}backupSettings(){let e=this.getSettingsPath();try{J$(e,X$.R_OK);let r=e+".bak";return Y$(e,r),r}catch{return null}}}});var ao,Zu=v(()=>{"use strict";Vt();ao=class extends Me{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});function ye(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}var Sr=v(()=>{"use strict"});function ys(t,e){let r=co[e],n=Hu(e);return t.hooks?.some(o=>o.command?.includes(r)||o.command?.includes(n))??!1}function Hu(t,e){if(e){let r=co[t];return ye(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function qu(t){let e=t.match(/"[^"]+"\s+"([^"]+\.mjs)"/);return e?e[1]:t.match(/node\s+"?([^"]+\.mjs)"?/)?.[1]??null}function a_(t){let e=Object.values(co);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var Wt,eE,s_,tE,QL,co,i_,e2,c_=v(()=>{"use strict";Sr();Wt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},eE=["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"],s_=eE.join("|"),tE=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],QL=tE.join("|"),co={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},i_=[Wt.PRE_TOOL_USE,Wt.SESSION_START],e2=[Wt.POST_TOOL_USE,Wt.PRE_COMPACT,Wt.USER_PROMPT_SUBMIT]});var Vu={};Ze(Vu,{ClaudeCodeAdapter:()=>Bu});import{readFileSync as Xi,writeFileSync as u_,existsSync as rE,readdirSync as nE,chmodSync as oE,accessSync as sE,constants as iE}from"node:fs";import{resolve as pn,join as l_}from"node:path";import{homedir as xs}from"node:os";var Bu,Wu=v(()=>{"use strict";Zu();c_();Bu=class extends ao{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};getSettingsPath(){return pn(xs(),".claude","settings.json")}generateHookConfig(e){let r=`node ${e}/hooks/pretooluse.mjs`;return{PreToolUse:["Bash","WebFetch","Read","Grep","Task","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"].map(o=>({matcher:o,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/posttooluse.mjs`}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/precompact.mjs`}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/userpromptsubmit.mjs`}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/sessionstart.mjs`}]}]}}readSettings(){try{let e=Xi(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){u_(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 ~/.claude/settings.json",fix:"context-mode upgrade"}),r;let o=n.hooks,s=this.readPluginHooks(e),i=this.checkHookType(o,s,Wt.PRE_TOOL_USE);r.push({check:"PreToolUse hook",status:i?"pass":"fail",message:i?"PreToolUse hook configured":"No PreToolUse hooks found",fix:i?void 0:"context-mode upgrade"});let a=this.checkHookType(o,s,Wt.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}readPluginHooks(e){let r=[l_(e,"hooks","hooks.json"),l_(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let o=Xi(n,"utf-8"),s=JSON.parse(o);if(s.hooks)return s.hooks}catch{}}checkHookType(e,r,n){let o=e?.[n];if(o&&o.length>0&&o.some(i=>ys(i,n)))return!0;let s=r?.[n];return!!(s&&s.length>0&&s.some(i=>ys(i,n)))}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read settings.json"};let r=e.enabledPlugins;if(!r)return{check:"Plugin registration",status:"warn",message:"No enabledPlugins section found (might be using standalone MCP mode)"};let n=Object.keys(r).find(o=>o.startsWith("context-mode"));return n&&r[n]?{check:"Plugin registration",status:"pass",message:`Plugin enabled: ${n}`}:{check:"Plugin registration",status:"warn",message:"context-mode not in enabledPlugins (might be using standalone MCP mode)"}}getInstalledVersion(){try{let r=pn(xs(),".claude","plugins","installed_plugins.json"),o=JSON.parse(Xi(r,"utf-8")).plugins??{};for(let[s,i]of Object.entries(o)){if(!s.toLowerCase().includes("context-mode"))continue;let a=i;if(a.length>0&&typeof a[0].version=="string")return a[0].version}}catch{}let e=[pn(xs(),".claude"),pn(xs(),".config","claude")];for(let r of e){let n=pn(r,"plugins","cache","context-mode","context-mode");try{let s=nE(n).filter(i=>/^\d+\.\d+\.\d+/.test(i)).sort((i,a)=>{let c=i.split(".").map(Number),u=a.split(".").map(Number);for(let l=0;l<3;l++)if((c[l]??0)!==(u[l]??0))return(c[l]??0)-(u[l]??0);return 0});if(s.length>0)return s[s.length-1]}catch{}}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let a of Object.keys(n)){let c=n[a];if(!Array.isArray(c))continue;let u=c.filter(d=>{let p=d;if(!a_(p))return!0;let f=p.hooks??[];return f.every(h=>!h.command||!qu(h.command))?!0:f.every(h=>{let g=h.command?qu(h.command):null;return g?rE(g):!0})}),l=c.length-u.length;l>0&&(n[a]=u,o.push(`Removed ${l} stale ${a} hook(s)`))}let s=this.readPluginHooks(e);if(s&&i_.every(c=>this.checkHookType(void 0,s,c))){let c=Object.values(co),u=l=>l!=null&&(c.some(d=>l.includes(d))||l.includes("context-mode hook"));for(let l of Object.keys(n)){let d=n[l];if(!Array.isArray(d))continue;let p=0;for(let m of d){let h=m,g=h.hooks??[],y=g.length;h.hooks=g.filter(_=>!u(_.command)),p+=y-h.hooks.length}let f=d.filter(m=>{let h=m.hooks;return Array.isArray(h)&&h.length>0});(p>0||f.length!==d.length)&&(n[l]=f,p>0&&o.push(`Removed ${p} duplicate ${l} hook(s) \u2014 covered by plugin hooks.json`))}return r.hooks=n,this.writeSettings(r),o.push("Skipped settings.json registration \u2014 plugin hooks.json is sufficient"),o}let i=[Wt.PRE_TOOL_USE,Wt.SESSION_START];for(let a of i){let c=Hu(a,e);if(a===Wt.PRE_TOOL_USE){let u={matcher:s_,hooks:[{type:"command",command:c}]},l=n.PreToolUse;if(l&&Array.isArray(l)){let d=l.findIndex(p=>ys(p,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n.PreToolUse=l}else n.PreToolUse=[u],o.push(`Created ${a} hooks section`)}else{let u={matcher:"",hooks:[{type:"command",command:c}]},l=n[a];if(l&&Array.isArray(l)){let d=l.findIndex(p=>ys(p,a));d>=0?(l[d]=u,o.push(`Updated existing ${a} hook entry`)):(l.push(u),o.push(`Added ${a} hook entry`)),n[a]=l}else n[a]=[u],o.push(`Created ${a} hooks section`)}}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[];for(let[,n]of Object.entries(co)){let o=pn(e,"hooks",n);try{sE(o,iE.R_OK),oE(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=pn(xs(),".claude","plugins","installed_plugins.json"),o=JSON.parse(Xi(n,"utf-8"));for(let[s,i]of Object.entries(o.plugins||{}))if(s.toLowerCase().includes("context-mode"))for(let a of i)a.installPath=e,a.version=r,a.lastUpdated=new Date().toISOString();u_(n,JSON.stringify(o,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 mn(t,e){let r=Gu[t];return e&&r?ye(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var we,Gu,c2,u2,d_=v(()=>{"use strict";Sr();we={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Gu={[we.BEFORE_AGENT]:"beforeagent.mjs",[we.BEFORE_TOOL]:"beforetool.mjs",[we.AFTER_TOOL]:"aftertool.mjs",[we.PRE_COMPRESS]:"precompress.mjs",[we.SESSION_START]:"sessionstart.mjs"},c2=[we.BEFORE_TOOL,we.SESSION_START],u2=[we.AFTER_TOOL,we.PRE_COMPRESS]});var m_={};Ze(m_,{GeminiCLIAdapter:()=>Ju});import{readFileSync as Ku,writeFileSync as p_,mkdirSync as aE,accessSync as cE,chmodSync as uE,constants as lE}from"node:fs";import{resolve as vs,join as dE}from"node:path";import{homedir as Qi}from"node:os";var Ju,f_=v(()=>{"use strict";Vt();d_();Ju=class extends Me{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return vs(Qi(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[we.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:mn(we.BEFORE_AGENT,e)}]}],[we.BEFORE_TOOL]:[{matcher:"run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode",hooks:[{type:"command",command:mn(we.BEFORE_TOOL,e)}]}],[we.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:mn(we.AFTER_TOOL,e)}]}],[we.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:mn(we.PRE_COMPRESS,e)}]}],[we.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:mn(we.SESSION_START,e)}]}]}}readSettings(){try{let e=Ku(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=vs(Qi(),".gemini");aE(r,{recursive:!0}),p_(this.getSettingsPath(),JSON.stringify(e,null,2)+`
6
- `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let o=n.hooks,s=o?.[we.BEFORE_TOOL];if(s&&s.length>0){let a=s.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=o?.[we.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(o=>typeof o=="string"&&o.includes("context-mode")):Object.keys(r).some(o=>o.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=vs(Qi(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(Ku(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[],s=[{name:we.BEFORE_AGENT},{name:we.BEFORE_TOOL},{name:we.SESSION_START}];for(let i of s){let c={matcher:"",hooks:[{type:"command",command:mn(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let l=u.findIndex(d=>d.hooks?.some(f=>f.command?.includes("context-mode")));l>=0?(u[l]=c,o.push(`Updated existing ${i.name} hook entry`)):(u.push(c),o.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],o.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){let r=[],n=dE(e,"hooks","gemini-cli");for(let o of Object.values(Gu)){let s=vs(n,o);try{cE(s,lE.R_OK),uE(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=vs(Qi(),".gemini","extensions","context-mode","package.json"),o=JSON.parse(Ku(n,"utf-8"));o.version=r,o.installPath=e,o.lastUpdated=new Date().toISOString(),p_(n,JSON.stringify(o,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 fn,g2,_2,h_=v(()=>{"use strict";fn={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},g2=[fn.BEFORE,fn.AFTER],_2=[fn.COMPACTING]});var __={};Ze(__,{OpenCodeAdapter:()=>Yu});import{readFileSync as g_,writeFileSync as mE,mkdirSync as fE,copyFileSync as hE,accessSync as gE,constants as _E}from"node:fs";import{resolve as Tt,join as Zr}from"node:path";import{homedir as Hr}from"node:os";function pE(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var Yu,y_=v(()=>{"use strict";Vt();h_();Yu=class extends Me{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??Tt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[Tt("kilo.json"),Tt("kilo.jsonc"),Tt(".kilo","kilo.json"),Tt(".kilo","kilo.jsonc"),Tt(".kilocode","kilo.json"),Tt(".kilocode","kilo.jsonc"),Zr(Hr(),".config","kilo","kilo.json"),Zr(Hr(),".config","kilo","kilo.jsonc")]:[Tt("opencode.json"),Tt("opencode.jsonc"),Tt(".opencode","opencode.json"),Tt(".opencode","opencode.jsonc"),Zr(Hr(),".config","opencode","opencode.json"),Zr(Hr(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=Zr(this.getConfigDir(),"context-mode","sessions");return fE(e,{recursive:!0}),e}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Zr(Hr(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Zr(Hr(),".config"),Zr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[fn.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[fn.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[fn.COMPACTING]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){this.settingsPath=void 0;let e=this.paths(),r=new Set(e.filter(s=>s.includes(Hr()))),n=null,o;for(let s of e)try{let i=g_(s,"utf-8"),a=s.endsWith(".jsonc")?pE(i):i,c=JSON.parse(a);n||(n=c,o=s);let u=r.has(s);if(this.hasContextModePlugin(c)||u)return this.settingsPath=s,c}catch{continue}return n?(this.settingsPath=o,n):null}writeSettings(e){mE(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 o=this.hasContextModePlugin(n);return Array.isArray(n.plugin)?r.push({check:"Plugin registration",status:o?"pass":"fail",message:o?"context-mode found in plugin array":"context-mode not found in plugin array",fix:o?void 0:"context-mode upgrade"}):r.push({check:"Plugin registration",status:"fail",message:`No plugin array found in ${this.platform}.json or ${this.platform}.jsonc`,fix:"context-mode upgrade"}),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=Tt(Hr(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(g_(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[],o=r.plugin??[];return o.some(s=>s.includes("context-mode"))?n.push("context-mode already in plugin array"):(o.push("context-mode"),n.push("Added context-mode to plugin array")),r.plugin=o,this.writeSettings(r),n}backupSettings(){let e=this.checkPluginRegistration();if(!this.settingsPath)return null;if(e.status==="pass")return this.settingsPath;try{gE(this.settingsPath,_E.R_OK);let r=this.settingsPath+".bak";return hE(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 hn,w2,$2,x_=v(()=>{"use strict";hn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},w2=[hn.TOOL_CALL_BEFORE,hn.TOOL_CALL_AFTER],$2=[hn.COMMAND_NEW]});var v_={};Ze(v_,{OpenClawAdapter:()=>tl});import{readFileSync as Xu,writeFileSync as yE,copyFileSync as xE,accessSync as vE,constants as bE}from"node:fs";import{resolve as kr,join as Qu}from"node:path";import{homedir as el}from"node:os";var tl,b_=v(()=>{"use strict";Vt();x_();tl=class extends Me{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return kr("openclaw.json")}getConfigDir(e){return kr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(){return Qu(this.getConfigDir(),"memory")}generateHookConfig(e){return{[hn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[hn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[hn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[kr("openclaw.json"),kr(".openclaw","openclaw.json"),Qu(el(),".openclaw","openclaw.json")];for(let r of e)try{let n=Xu(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=kr("openclaw.json");yE(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 o=n.plugins,s=o?.entries;if(s){let a=Object.keys(s).some(c=>c.includes("context-mode"));if(r.push({check:"Plugin registration",status:a?"pass":"fail",message:a?"context-mode found in plugins.entries":"context-mode not found in plugins.entries",fix:a?void 0:"context-mode upgrade"}),a){let u=s["context-mode"]?.enabled!==!1;r.push({check:"Plugin enabled",status:u?"pass":"warn",message:u?"context-mode plugin is enabled":"context-mode plugin is disabled"})}}else r.push({check:"Plugin registration",status:"fail",message:"No plugins.entries found in openclaw.json",fix:"context-mode upgrade"});return o?.slots?.contextEngine==="context-mode"?r.push({check:"Context engine",status:"pass",message:"context-mode registered as context engine (owns compaction)"}):r.push({check:"Context engine",status:"warn",message:"context-mode not set as context engine \u2014 compaction will use default engine"}),r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read openclaw.json"};let n=e.plugins?.entries;return n&&Object.keys(n).some(s=>s.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in plugins.entries"}:{check:"Plugin registration",status:"fail",message:"context-mode not found in openclaw.json plugins.entries",fix:"context-mode upgrade"}}getInstalledVersion(){try{let e=kr(el(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(Xu(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=kr("node_modules","context-mode","package.json"),r=JSON.parse(Xu(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=[];r.plugins||(r.plugins={});let o=r.plugins;o.entries||(o.entries={});let s=o.entries;if(!s["context-mode"])s["context-mode"]={enabled:!0},n.push("Added context-mode to plugins.entries");else{let a=s["context-mode"];a.enabled===!1?(a.enabled=!0,n.push("Enabled context-mode plugin")):n.push("context-mode already configured in plugins.entries")}o.slots||(o.slots={});let i=o.slots;return i.contextEngine?i.contextEngine!=="context-mode"&&n.push(`Context engine already set to "${i.contextEngine}" \u2014 not overwriting`):(i.contextEngine="context-mode",n.push("Set context-mode as context engine (owns compaction)")),this.writeSettings(r),n}backupSettings(){let e=[kr("openclaw.json"),kr(".openclaw","openclaw.json"),Qu(el(),".openclaw","openclaw.json")];for(let r of e)try{vE(r,bE.R_OK);let n=r+".bak";return xE(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}`}}});var k_={};Ze(k_,{CodexAdapter:()=>ol});import{readFileSync as rl}from"node:fs";import{resolve as nl,dirname as SE}from"node:path";import{fileURLToPath as kE}from"node:url";import{homedir as S_}from"node:os";var ol,w_=v(()=>{"use strict";Vt();Sr();ol=class extends Me{constructor(){super([".codex"])}name="Codex CLI";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:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return e.context?{hookSpecificOutput:{additionalContext:e.context}}:{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getSettingsPath(){return nl(S_(),".codex","config.toml")}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(){return nl(S_(),".codex","memories")}generateHookConfig(e){return{PreToolUse:[{matcher:"local_shell|shell|shell_command|exec_command|container.exec|Bash|Shell|grep_files|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",hooks:[{type:"command",command:ye(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:ye(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:ye(`${e}/hooks/sessionstart.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:ye(`${e}/hooks/codex/userpromptsubmit.mjs`)}]}],Stop:[{matcher:"",hooks:[{type:"command",command:ye(`${e}/hooks/codex/stop.mjs`)}]}]}}readSettings(){try{return{_raw_toml:rl(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){return[{check:"Hook support",status:"pass",message:"Codex CLI hooks are stable. Configure ~/.codex/hooks.json for PreToolUse, PostToolUse, SessionStart, UserPromptSubmit, and Stop."}]}checkPluginRegistration(){try{let e=rl(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 ~/.codex/config.toml"}:{check:"MCP registration",status:"fail",message:"No [mcp_servers] section in config.toml",fix:"Add [mcp_servers.context-mode] to ~/.codex/config.toml"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.codex/config.toml"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=nl(SE(kE(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return rl(e,"utf-8")}catch{return`# context-mode
10
-
11
- 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()}extractSessionId(e){return e.session_id?e.session_id:`pid-${process.ppid}`}}});import{readFileSync as $_,writeFileSync as wE,mkdirSync as $E,accessSync as EE,chmodSync as TE,constants as PE}from"node:fs";import{resolve as ea,join as RE}from"node:path";var uo,sl=v(()=>{"use strict";Vt();uo=class extends Me{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return ea(".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=$_(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=$_(ea(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();$E(ea(".github","hooks"),{recursive:!0}),wE(r,JSON.stringify(e,null,2)+`
12
- `,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},o=n.hooks??{},{HOOK_TYPES:s,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[s.PRE_TOOL_USE,s.POST_TOOL_USE,s.PRE_COMPACT,s.SESSION_START];for(let u of c)i[u]&&(o[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=o,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=RE(e,"hooks",this.hookSubdir);for(let o of Object.values(this.hookModule.HOOK_SCRIPTS)){let s=ea(n,o);try{EE(s,PE.R_OK),TE(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}}});function E_(t,e){let r=il[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?ye(`${e}/hooks/vscode-copilot/${r}`):`context-mode hook vscode-copilot ${t.toLowerCase()}`}var Pt,il,H2,q2,T_=v(()=>{"use strict";Sr();Pt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},il={[Pt.PRE_TOOL_USE]:"pretooluse.mjs",[Pt.POST_TOOL_USE]:"posttooluse.mjs",[Pt.PRE_COMPACT]:"precompact.mjs",[Pt.SESSION_START]:"sessionstart.mjs"},H2=[Pt.PRE_TOOL_USE,Pt.SESSION_START],q2=[Pt.POST_TOOL_USE,Pt.PRE_COMPACT]});var P_={};Ze(P_,{VSCodeCopilotAdapter:()=>ul});import{readFileSync as al,mkdirSync as CE,accessSync as OE,existsSync as IE,constants as AE}from"node:fs";import{resolve as lo,join as ta}from"node:path";import{homedir as cl}from"node:os";var ul,R_=v(()=>{"use strict";sl();T_();ul=class extends uo{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:Pt,HOOK_SCRIPTS:il,buildHookCommand:E_};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=lo(".github","context-mode","sessions"),r=ta(cl(),".vscode","context-mode","sessions"),n=IE(lo(".github"))?e:r;return CE(n,{recursive:!0}),n}getConfigDir(e){return lo(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=lo(".github","hooks");try{OE(n,AE.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let o=lo(n,"context-mode.json");try{let s=al(o,"utf-8"),a=JSON.parse(s).hooks;a?.[Pt.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?.[Pt.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=lo(".vscode","mcp.json"),r=al(e,"utf-8"),o=JSON.parse(r).servers;return o&&Object.keys(o).some(i=>i.includes("context-mode"))?{check:"MCP registration",status:"pass",message:"context-mode found in .vscode/mcp.json"}:{check:"MCP registration",status:"fail",message:"context-mode not found in .vscode/mcp.json",fix:"Add context-mode server to .vscode/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read .vscode/mcp.json"}}}getInstalledVersion(){let e=[ta(cl(),".vscode","extensions"),ta(cl(),".vscode-insiders","extensions")];for(let r of e)try{let n=al(ta(r,"extensions.json"),"utf-8"),s=JSON.parse(n).find(i=>typeof i.identifier=="object"&&i.identifier!==null&&i.identifier.id?.toString().includes("context-mode"));if(s&&typeof s.version=="string")return s.version}catch{continue}return"not installed"}}});function C_(t,e){let r=ll[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?ye(`${e}/hooks/jetbrains-copilot/${r}`):`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Rt,ll,X2,Q2,O_=v(()=>{"use strict";Sr();Rt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},ll={[Rt.PRE_TOOL_USE]:"pretooluse.mjs",[Rt.POST_TOOL_USE]:"posttooluse.mjs",[Rt.PRE_COMPACT]:"precompact.mjs",[Rt.SESSION_START]:"sessionstart.mjs"},X2=[Rt.PRE_TOOL_USE,Rt.SESSION_START],Q2=[Rt.POST_TOOL_USE,Rt.PRE_COMPACT]});var I_={};Ze(I_,{JetBrainsCopilotAdapter:()=>dl});import{readFileSync as NE}from"node:fs";import{resolve as zE}from"node:path";var dl,A_=v(()=>{"use strict";sl();O_();dl=class extends uo{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Rt,HOOK_SCRIPTS:ll,buildHookCommand:C_};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 zE(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=NE(this.getSettingsPath(),"utf-8"),s=JSON.parse(n).hooks;s?.[Rt.PRE_TOOL_USE]?r.push({check:"PreToolUse hook",status:"pass",message:"PreToolUse hook configured in .github/hooks/context-mode.json"}):r.push({check:"PreToolUse hook",status:"fail",message:"PreToolUse not found in .github/hooks/context-mode.json",fix:"context-mode upgrade"}),s?.[Rt.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 ra(t,e){let r=pl[e],n=Ct(e);if("command"in t){let s=t.command??"";return r!=null&&s.includes(r)||s.includes(n)}return t.hooks?.some(s=>{let i=s.command??"";return r!=null&&i.includes(r)||i.includes(n)})??!1}function Ct(t){return`context-mode hook cursor ${t.toLowerCase()}`}var he,pl,jE,ml,N_,z_,j_=v(()=>{"use strict";he={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},pl={[he.PRE_TOOL_USE]:"pretooluse.mjs",[he.POST_TOOL_USE]:"posttooluse.mjs",[he.SESSION_START]:"sessionstart.mjs",[he.STOP]:"stop.mjs",[he.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},jE=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute"],ml=jE.join("|"),N_=[he.PRE_TOOL_USE],z_=[he.POST_TOOL_USE]});var L_={};Ze(L_,{CursorAdapter:()=>gl});import{readFileSync as fl,writeFileSync as DE,mkdirSync as ME,accessSync as LE,chmodSync as FE,constants as UE,existsSync as D_}from"node:fs";import{execSync as ZE}from"node:child_process";import{resolve as gn,join as na}from"node:path";import{homedir as hl}from"node:os";var M_,gl,F_=v(()=>{"use strict";Vt();j_();M_="/Library/Application Support/Cursor/hooks.json",gl=class extends Me{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",o;switch(n){case"compact":o="compact";break;case"resume":o="resume";break;case"clear":o="clear";break;default:o="startup"}return{sessionId:this.extractSessionId(r),source:o,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return gn(".cursor","hooks.json")}getConfigDir(e){return gn(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[he.PRE_TOOL_USE]:[{type:"command",command:Ct(he.PRE_TOOL_USE),matcher:ml,loop_limit:null,failClosed:!1}],[he.POST_TOOL_USE]:[{type:"command",command:Ct(he.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[he.SESSION_START]:[{type:"command",command:Ct(he.SESSION_START),loop_limit:null,failClosed:!1}],[he.STOP]:[{type:"command",command:Ct(he.STOP),loop_limit:null,failClosed:!1}],[he.AFTER_AGENT_RESPONSE]:[{type:"command",command:Ct(he.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=fl(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();ME(gn(".cursor"),{recursive:!0}),DE(r,JSON.stringify(e,null,2)+`
13
- `,"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 s of N_){let i=o[s],a=Array.isArray(i)&&i.some(c=>ra(c,s));r.push({check:s,status:a?"pass":"fail",message:a?`${s} hook configured`:`${s} hook not configured in ${n.path}`,fix:a?void 0:"context-mode upgrade"})}for(let s of z_){let i=o[s],a=Array.isArray(i)&&i.some(c=>ra(c,s));r.push({check:s,status:a?"pass":"warn",message:a?`${s} hook configured`:`${s} hook missing \u2014 session event capture will be reduced`})}}return D_(M_)&&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"}),r}checkPluginRegistration(){let e=[gn(".cursor","mcp.json"),na(hl(),".cursor","mcp.json")];for(let r of e)try{let n=fl(r,"utf-8"),o=JSON.parse(n),s=o.mcpServers??o.servers;if(!s)continue;if(Object.entries(s).some(([a,c])=>a.includes("context-mode")?!0:!c||typeof c!="object"?!1:c.command==="context-mode"))return{check:"MCP registration",status:"pass",message:`context-mode found in ${r}`}}catch{continue}return{check:"MCP registration",status:"warn",message:"Could not find context-mode in .cursor/mcp.json or ~/.cursor/mcp.json"}}getInstalledVersion(){try{return ZE("cursor --version",{encoding:"utf-8",stdio:["ignore","pipe","ignore"]}).trim().split(/\r?\n/)[0]||"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=this.readSettings()??{version:1,hooks:{}},n=r.hooks??{},o=[];return this.upsertHookEntry(n,he.PRE_TOOL_USE,{type:"command",command:Ct(he.PRE_TOOL_USE),matcher:ml,loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.POST_TOOL_USE,{type:"command",command:Ct(he.POST_TOOL_USE),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.SESSION_START,{type:"command",command:Ct(he.SESSION_START),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.STOP,{type:"command",command:Ct(he.STOP),loop_limit:null,failClosed:!1},o),this.upsertHookEntry(n,he.AFTER_AGENT_RESPONSE,{type:"command",command:Ct(he.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1},o),r.version=1,r.hooks=n,this.writeSettings(r),o.push(`Wrote native Cursor hooks to ${this.getSettingsPath()}`),o}setHookPermissions(e){let r=[],n=na(e,"hooks","cursor");for(let o of Object.values(pl)){let s=gn(n,o);try{LE(s,UE.R_OK),FE(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),na(hl(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(M_),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=fl(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[gn(".claude","settings.json"),gn(".claude","settings.local.json"),na(hl(),".claude","settings.json")].some(r=>D_(r))}upsertHookEntry(e,r,n,o){let s=e[r],i=Array.isArray(s)?[...s]:[],a=i.findIndex(c=>ra(c,r));a>=0?(i[a]=n,o.push(`Updated existing ${r} hook entry`)):(i.push(n),o.push(`Added ${r} hook entry`)),e[r]=i}}});var Z_={};Ze(Z_,{AntigravityAdapter:()=>yl});import{readFileSync as oa,writeFileSync as HE,mkdirSync as qE}from"node:fs";import{resolve as sa,dirname as U_}from"node:path";import{fileURLToPath as BE}from"node:url";import{homedir as _l}from"node:os";var yl,H_=v(()=>{"use strict";Vt();yl=class extends Me{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 sa(_l(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return sa(_l(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=oa(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();qE(U_(r),{recursive:!0}),HE(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=oa(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=sa(_l(),".gemini","extensions","context-mode","package.json");return JSON.parse(oa(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=sa(U_(BE(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return oa(e,"utf-8")}catch{return`# context-mode
14
-
15
- 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 ia(t,e){let r=q_[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function po(t,e){let r=q_[t];return e&&r?ye(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Ne,q_,VE,xl,xF,vF,B_=v(()=>{"use strict";Sr();Ne={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},q_={[Ne.PRE_TOOL_USE]:"pretooluse.mjs",[Ne.POST_TOOL_USE]:"posttooluse.mjs",[Ne.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Ne.AGENT_SPAWN]:"agentspawn.mjs"},VE=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute"],xl=VE.join("|"),xF=[Ne.PRE_TOOL_USE,Ne.AGENT_SPAWN],vF=[Ne.POST_TOOL_USE,Ne.USER_PROMPT_SUBMIT]});var K_={};Ze(K_,{KiroAdapter:()=>vl});import{readFileSync as mo,writeFileSync as V_,mkdirSync as W_}from"node:fs";import{resolve as _n,dirname as G_}from"node:path";import{fileURLToPath as WE}from"node:url";import{homedir as aa}from"node:os";var vl,J_=v(()=>{"use strict";Vt();B_();vl=class extends Me{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 _n(aa(),".kiro","settings","mcp.json")}getConfigDir(e){return _n(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Ne.PRE_TOOL_USE]:[{matcher:xl,hooks:[{type:"command",command:po(Ne.PRE_TOOL_USE,e)}]}],[Ne.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:po(Ne.POST_TOOL_USE,e)}]}],[Ne.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:po(Ne.AGENT_SPAWN,e)}]}],[Ne.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:po(Ne.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=mo(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();W_(G_(r),{recursive:!0}),V_(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=_n(aa(),".kiro","agents","default.json");try{let s=JSON.parse(mo(n,"utf-8")).hooks??{};for(let i of[Ne.PRE_TOOL_USE]){let c=(s[i]??[]).some(u=>ia(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[Ne.POST_TOOL_USE]){let c=(s[i]??[]).some(u=>ia(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=mo(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=_n(aa(),".kiro","extensions","context-mode","package.json");return JSON.parse(mo(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=_n(aa(),".kiro","agents"),o=_n(n,"default.json");try{W_(n,{recursive:!0});let s={};try{s=JSON.parse(mo(o,"utf-8"))}catch{}let i=s.hooks??{},a=[[Ne.PRE_TOOL_USE,xl],[Ne.POST_TOOL_USE,"*"],[Ne.AGENT_SPAWN,"*"],[Ne.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let l=i[c]??[];l.some(d=>ia(d,c))||(l.push({matcher:u,command:po(c,e)}),i[c]=l,r.push(`Added ${c} hook to ${o}`))}s.hooks=i,V_(o,JSON.stringify(s,null,2),"utf-8")}catch(s){r.push(`Failed to configure hooks: ${s.message}`)}return r}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=_n(G_(WE(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return mo(e,"utf-8")}catch{return`# context-mode
16
-
17
- 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 Q_={};Ze(Q_,{ZedAdapter:()=>Sl});import{readFileSync as bl,writeFileSync as GE,mkdirSync as KE}from"node:fs";import{resolve as Y_,dirname as X_}from"node:path";import{fileURLToPath as JE}from"node:url";import{homedir as YE}from"node:os";var Sl,ey=v(()=>{"use strict";Vt();Sl=class extends Me{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 Y_(YE(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=bl(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();KE(X_(r),{recursive:!0}),GE(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=bl(this.getSettingsPath(),"utf-8"),n=JSON.parse(e).context_servers!==void 0,o=e.includes("context-mode");return n&&o?{check:"MCP registration",status:"pass",message:"context-mode found in context_servers config"}:n?{check:"MCP registration",status:"fail",message:"context_servers section exists but context-mode not found",fix:"Add context-mode to context_servers in ~/.config/zed/settings.json"}:{check:"MCP registration",status:"fail",message:"No context_servers section in settings.json",fix:"Add context_servers.context-mode to ~/.config/zed/settings.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.config/zed/settings.json"}}}getInstalledVersion(){return"not installed"}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=Y_(X_(JE(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return bl(e,"utf-8")}catch{return`# context-mode
18
-
19
- Use context-mode MCP tools (execute, execute_file, batch_execute, fetch_and_index, search) instead of bash/cat/curl for data-heavy operations.`}}}});var ny={};Ze(ny,{QwenCodeAdapter:()=>kl});import{readFileSync as XE,existsSync as QE}from"node:fs";import{resolve as ty,join as eT}from"node:path";import{homedir as ry}from"node:os";var kl,oy=v(()=>{"use strict";Zu();Sr();kl=class extends ao{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 ty(ry(),".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"].join("|"),hooks:[{type:"command",command:ye(`${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:ye(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:ye(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:ye(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:ye(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=XE(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let{writeFileSync:r}=Cg("node:fs");r(this.getSettingsPath(),JSON.stringify(e,null,2))}validateHooks(e){let r=[],o=this.readSettings()?.hooks??{};for(let s of["PreToolUse","PostToolUse","SessionStart","PreCompact","UserPromptSubmit"]){let i=Array.isArray(o[s])&&o[s].length>0;r.push({check:`${s} hook`,status:i?"pass":"fail",message:i?`${s} hook configured in ~/.qwen/settings.json`:`${s} hook not found in ~/.qwen/settings.json`,...i?{}:{fix:`Add ${s} hook to ~/.qwen/settings.json`}})}return r}checkPluginRegistration(){try{let e=this.readSettings();if(e?.mcpServers&&typeof e.mcpServers=="object"){let r=e.mcpServers;return Object.keys(r).some(n=>n.includes("context-mode"))?{check:"Plugin registration",status:"pass",message:"context-mode found in mcpServers"}:{check:"Plugin registration",status:"fail",message:"mcpServers exists but context-mode not found",fix:"Add context-mode to mcpServers in ~/.qwen/settings.json"}}return{check:"Plugin registration",status:"warn",message:"No mcpServers in ~/.qwen/settings.json"}}catch{return{check:"Plugin registration",status:"warn",message:"Could not read ~/.qwen/settings.json"}}}getInstalledVersion(){let e=this.readSettings();if(!e)return"not installed";let r=e.hooks;if(!r)return"not installed";let n=["pretooluse.mjs","posttooluse.mjs","precompact.mjs","sessionstart.mjs","userpromptsubmit.mjs"];for(let[,o]of Object.entries(r))if(Array.isArray(o)){for(let s of o)if(s.hooks?.some(a=>a.command&&n.some(c=>a.command.includes(c))))return"installed (hooks configured)"}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},o=[];for(let i of Object.keys(n)){let a=n[i];if(!Array.isArray(a))continue;let c=a.filter(l=>{let p=l.hooks??[];return p.some(m=>m.command&&/context-mode|pretooluse|posttooluse|precompact|sessionstart|userpromptsubmit/i.test(m.command))?p.every(m=>{if(!m.command)return!0;let h=m.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=m.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?QE(y[1]):!0}):!0}),u=a.length-c.length;u>0&&(n[i]=c,o.push(`Removed ${u} stale ${i} hook(s)`))}let s=[{name:"PreToolUse",script:"pretooluse.mjs",matcher:["run_shell_command","read_file","read_many_files","grep_search","web_fetch","agent","mcp__plugin_context-mode_context-mode__ctx_execute","mcp__plugin_context-mode_context-mode__ctx_execute_file","mcp__plugin_context-mode_context-mode__ctx_batch_execute"].join("|")},{name:"PostToolUse",script:"posttooluse.mjs",matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__"},{name:"SessionStart",script:"sessionstart.mjs",matcher:""},{name:"PreCompact",script:"precompact.mjs",matcher:""},{name:"UserPromptSubmit",script:"userpromptsubmit.mjs",matcher:""}];for(let{name:i,script:a,matcher:c}of s){let u={matcher:c,hooks:[{type:"command",command:ye(`${e}/hooks/${a}`)}]},l=n[i];if(l&&Array.isArray(l)){let d=l.findIndex(p=>p.hooks?.some(m=>m.command?.includes(a))??!1);d>=0?(l[d]=u,o.push(`Updated ${i} hook`)):(l.push(u),o.push(`Added ${i} hook`)),n[i]=l}else n[i]=[u],o.push(`Created ${i} hooks`)}return r.hooks=n,this.writeSettings(r),o}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructionsConfig(){return{instructionsPath:ty(eT(ry(),".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 iy={};Ze(iy,{PLATFORM_ENV_VARS:()=>sy,detectPlatform:()=>wr,getAdapter:()=>bs,getSessionDirSegments:()=>wl});import{existsSync as Ot}from"node:fs";import{resolve as It}from"node:path";import{homedir as tT}from"node:os";function wl(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"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 wr(t){if(t?.name){let n=t_[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","zed","qwen-code"].includes(e))return{platform:e,confidence:"high",reason:`CONTEXT_MODE_PLATFORM=${e} override`};for(let[n,o]of sy)if(o.some(s=>process.env[s]))return{platform:n,confidence:"high",reason:`${o.join(" or ")} env var set`};let r=tT();return Ot(It(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Ot(It(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Ot(It(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Ot(It(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Ot(It(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Ot(It(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Ot(It(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Ot(It(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Ot(It(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Ot(It(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Ot(It(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Ot(It(r,".config","zed"))?{platform:"zed",confidence:"medium",reason:"~/.config/zed/ directory exists"}:{platform:"claude-code",confidence:"low",reason:"No platform detected, defaulting to Claude Code"}}async function bs(t){let e=t??wr().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Wu(),Vu));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(f_(),m_));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(y_(),__));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(b_(),v_));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(w_(),k_));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(R_(),P_));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(A_(),I_));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(F_(),L_));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(H_(),Z_));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(J_(),K_));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(ey(),Q_));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(oy(),ny));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Wu(),Vu));return new r}}}var sy,ca=v(()=>{"use strict";r_();sy=[["claude-code",["CLAUDE_PROJECT_DIR","CLAUDE_SESSION_ID"]],["antigravity",["ANTIGRAVITY_CLI_ALIAS"]],["cursor",["CURSOR_TRACE_ID","CURSOR_CLI"]],["kilo",["KILO_PID"]],["opencode",["OPENCODE","OPENCODE_PID"]],["zed",["ZED_SESSION_ID","ZED_TERM"]],["codex",["CODEX_THREAD_ID","CODEX_CI"]],["gemini-cli",["GEMINI_PROJECT_DIR","GEMINI_CLI"]],["vscode-copilot",["VSCODE_PID","VSCODE_CWD"]],["jetbrains-copilot",["IDEA_INITIAL_DIRECTORY"]],["qwen-code",["QWEN_PROJECT_DIR"]],["pi",["PI_PROJECT_DIR"]]]});var ne,$l,O,ir,Ss=v(()=>{(function(t){t.assertEqual=o=>{};function e(o){}t.assertIs=e;function r(o){throw new Error}t.assertNever=r,t.arrayToEnum=o=>{let s={};for(let i of o)s[i]=i;return s},t.getValidEnumValues=o=>{let s=t.objectKeys(o).filter(a=>typeof o[o[a]]!="number"),i={};for(let a of s)i[a]=o[a];return t.objectValues(i)},t.objectValues=o=>t.objectKeys(o).map(function(s){return o[s]}),t.objectKeys=typeof Object.keys=="function"?o=>Object.keys(o):o=>{let s=[];for(let i in o)Object.prototype.hasOwnProperty.call(o,i)&&s.push(i);return s},t.find=(o,s)=>{for(let i of o)if(s(i))return i},t.isInteger=typeof Number.isInteger=="function"?o=>Number.isInteger(o):o=>typeof o=="number"&&Number.isFinite(o)&&Math.floor(o)===o;function n(o,s=" | "){return o.map(i=>typeof i=="string"?`'${i}'`:i).join(s)}t.joinValues=n,t.jsonStringifyReplacer=(o,s)=>typeof s=="bigint"?s.toString():s})(ne||(ne={}));(function(t){t.mergeShapes=(e,r)=>({...e,...r})})($l||($l={}));O=ne.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ir=t=>{switch(typeof t){case"undefined":return O.undefined;case"string":return O.string;case"number":return Number.isNaN(t)?O.nan:O.number;case"boolean":return O.boolean;case"function":return O.function;case"bigint":return O.bigint;case"symbol":return O.symbol;case"object":return Array.isArray(t)?O.array:t===null?O.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?O.promise:typeof Map<"u"&&t instanceof Map?O.map:typeof Set<"u"&&t instanceof Set?O.set:typeof Date<"u"&&t instanceof Date?O.date:O.object;default:return O.unknown}}});var $,rT,pt,ua=v(()=>{Ss();$=ne.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"]),rT=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),pt=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union")i.unionErrors.map(o);else if(i.code==="invalid_return_type")o(i.returnTypeError);else if(i.code==="invalid_arguments")o(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ne.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let o of this.issues)if(o.path.length>0){let s=o.path[0];r[s]=r[s]||[],r[s].push(e(o))}else n.push(e(o));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};pt.create=t=>new pt(t)});var nT,$r,El=v(()=>{ua();Ss();nT=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===O.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ne.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${ne.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ne.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${ne.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.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}"`:ne.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case $.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 $.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 $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,ne.assertNever(t)}return{message:r}},$r=nT});function oT(t){ay=t}function fo(){return ay}var ay,la=v(()=>{El();ay=$r});function R(t,e){let r=fo(),n=ks({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===$r?void 0:$r].filter(o=>!!o)});t.common.issues.push(n)}var ks,sT,We,q,yn,et,da,pa,qr,ho,Tl=v(()=>{la();El();ks=t=>{let{data:e,path:r,errorMaps:n,issueData:o}=t,s=[...r,...o.path||[]],i={...o,path:s};if(o.message!==void 0)return{...o,path:s,message:o.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(i,{data:e,defaultError:a}).message;return{...o,path:s,message:a}},sT=[];We=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let o of r){if(o.status==="aborted")return q;o.status==="dirty"&&e.dirty(),n.push(o.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let o of r){let s=await o.key,i=await o.value;n.push({key:s,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let o of r){let{key:s,value:i}=o;if(s.status==="aborted"||i.status==="aborted")return q;s.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof i.value<"u"||o.alwaysSet)&&(n[s.value]=i.value)}return{status:e.value,value:n}}},q=Object.freeze({status:"aborted"}),yn=t=>({status:"dirty",value:t}),et=t=>({status:"valid",value:t}),da=t=>t.status==="aborted",pa=t=>t.status==="dirty",qr=t=>t.status==="valid",ho=t=>typeof Promise<"u"&&t instanceof Promise});var cy=v(()=>{});var j,uy=v(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(j||(j={}))});function J(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:o}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:o}:{errorMap:(i,a)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:i.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:o}}function my(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 ST(t){return new RegExp(`^${my(t)}$`)}function fy(t){let e=`${py}T${my(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 kT(t,e){return!!((e==="v4"||!e)&&hT.test(t)||(e==="v6"||!e)&&_T.test(t))}function wT(t,e){if(!dT.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),o=JSON.parse(atob(n));return!(typeof o!="object"||o===null||"typ"in o&&o?.typ!=="JWT"||!o.alg||e&&o.alg!==e)}catch{return!1}}function $T(t,e){return!!((e==="v4"||!e)&&gT.test(t)||(e==="v6"||!e)&&yT.test(t))}function ET(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function go(t){if(t instanceof ft){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=mt.create(go(n))}return new ft({...t._def,shape:()=>e})}else return t instanceof Pr?new Pr({...t._def,type:go(t.element)}):t instanceof mt?mt.create(go(t.unwrap())):t instanceof cr?cr.create(go(t.unwrap())):t instanceof ar?ar.create(t.items.map(e=>go(e))):t}function Rl(t,e){let r=ir(t),n=ir(e);if(t===e)return{valid:!0,data:t};if(r===O.object&&n===O.object){let o=ne.objectKeys(e),s=ne.objectKeys(t).filter(a=>o.indexOf(a)!==-1),i={...t,...e};for(let a of s){let c=Rl(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===O.array&&n===O.array){if(t.length!==e.length)return{valid:!1};let o=[];for(let s=0;s<t.length;s++){let i=t[s],a=e[s],c=Rl(i,a);if(!c.valid)return{valid:!1};o.push(c.data)}return{valid:!0,data:o}}else return r===O.date&&n===O.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function hy(t,e){return new Rn({values:t,typeName:T.ZodEnum,...J(e)})}function dy(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function gy(t,e={},r){return t?Vr.create().superRefine((n,o)=>{let s=t(n);if(s instanceof Promise)return s.then(i=>{if(!i){let a=dy(e,n),c=a.fatal??r??!0;o.addIssue({code:"custom",...a,fatal:c})}});if(!s){let i=dy(e,n),a=i.fatal??r??!0;o.addIssue({code:"custom",...i,fatal:a})}}):Vr.create()}var At,ly,X,iT,aT,cT,uT,lT,dT,pT,mT,fT,Pl,hT,gT,_T,yT,xT,vT,py,bT,Br,xn,vn,bn,Sn,_o,kn,wn,Vr,Tr,Gt,yo,Pr,ft,$n,Er,ma,En,ar,fa,xo,vo,ha,Tn,Pn,Rn,Cn,Wr,Nt,mt,cr,On,In,bo,TT,ws,$s,An,PT,T,RT,_y,yy,CT,OT,xy,IT,AT,NT,zT,jT,DT,MT,LT,FT,Cl,UT,ZT,HT,qT,BT,VT,WT,GT,KT,JT,YT,XT,QT,eP,tP,rP,nP,oP,sP,iP,aP,cP,uP,lP,vy=v(()=>{ua();la();uy();Tl();Ss();At=class{constructor(e,r,n,o){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=o}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},ly=(t,e)=>{if(qr(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 pt(t.common.issues);return this._error=r,this._error}}};X=class{get description(){return this._def.description}_getType(e){return ir(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ir(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new We,ctx:{common:e.parent.common,data:e.data,parsedType:ir(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(ho(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:ir(e)},o=this._parseSync({data:e,path:n.path,parent:n});return ly(n,o)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ir(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return qr(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=>qr(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:ir(e)},o=this._parse({data:e,path:n.path,parent:n}),s=await(ho(o)?o:Promise.resolve(o));return ly(n,s)}refine(e,r){let n=o=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(o):r;return this._refinement((o,s)=>{let i=e(o),a=()=>s.addIssue({code:$.custom,...n(o)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,r){return this._refinement((n,o)=>e(n)?!0:(o.addIssue(typeof r=="function"?r(n,o):r),!1))}_refinement(e){return new Nt({schema:this,typeName:T.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 mt.create(this,this._def)}nullable(){return cr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Pr.create(this)}promise(){return Wr.create(this,this._def)}or(e){return $n.create([this,e],this._def)}and(e){return En.create(this,e,this._def)}transform(e){return new Nt({...J(this._def),schema:this,typeName:T.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new On({...J(this._def),innerType:this,defaultValue:r,typeName:T.ZodDefault})}brand(){return new ws({typeName:T.ZodBranded,type:this,...J(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new In({...J(this._def),innerType:this,catchValue:r,typeName:T.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return $s.create(this,e)}readonly(){return An.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},iT=/^c[^\s-]{8,}$/i,aT=/^[0-9a-z]+$/,cT=/^[0-9A-HJKMNP-TV-Z]{26}$/i,uT=/^[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,lT=/^[a-z0-9_-]{21}$/i,dT=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pT=/^[-+]?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)?)??$/,mT=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,fT="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",hT=/^(?:(?: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])$/,gT=/^(?:(?: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])$/,_T=/^(([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]))$/,yT=/^(([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])$/,xT=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,vT=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,py="((\\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])))",bT=new RegExp(`^${py}$`);Br=class t extends X{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==O.string){let s=this._getOrReturnCtx(e);return R(s,{code:$.invalid_type,expected:O.string,received:s.parsedType}),q}let n=new We,o;for(let s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(o=this._getOrReturnCtx(e,o),R(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="max")e.data.length>s.value&&(o=this._getOrReturnCtx(e,o),R(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),n.dirty());else if(s.kind==="length"){let i=e.data.length>s.value,a=e.data.length<s.value;(i||a)&&(o=this._getOrReturnCtx(e,o),i?R(o,{code:$.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):a&&R(o,{code:$.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),n.dirty())}else if(s.kind==="email")mT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"email",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="emoji")Pl||(Pl=new RegExp(fT,"u")),Pl.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"emoji",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="uuid")uT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"uuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="nanoid")lT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"nanoid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid")iT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"cuid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="cuid2")aT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"cuid2",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="ulid")cT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"ulid",code:$.invalid_string,message:s.message}),n.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{o=this._getOrReturnCtx(e,o),R(o,{validation:"url",code:$.invalid_string,message:s.message}),n.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"regex",code:$.invalid_string,message:s.message}),n.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(o=this._getOrReturnCtx(e,o),R(o,{code:$.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),n.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(o=this._getOrReturnCtx(e,o),R(o,{code:$.invalid_string,validation:{startsWith:s.value},message:s.message}),n.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(o=this._getOrReturnCtx(e,o),R(o,{code:$.invalid_string,validation:{endsWith:s.value},message:s.message}),n.dirty()):s.kind==="datetime"?fy(s).test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{code:$.invalid_string,validation:"datetime",message:s.message}),n.dirty()):s.kind==="date"?bT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{code:$.invalid_string,validation:"date",message:s.message}),n.dirty()):s.kind==="time"?ST(s).test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{code:$.invalid_string,validation:"time",message:s.message}),n.dirty()):s.kind==="duration"?pT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"duration",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="ip"?kT(e.data,s.version)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"ip",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="jwt"?wT(e.data,s.alg)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"jwt",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="cidr"?$T(e.data,s.version)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"cidr",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64"?xT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"base64",code:$.invalid_string,message:s.message}),n.dirty()):s.kind==="base64url"?vT.test(e.data)||(o=this._getOrReturnCtx(e,o),R(o,{validation:"base64url",code:$.invalid_string,message:s.message}),n.dirty()):ne.assertNever(s);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(o=>e.test(o),{validation:r,code:$.invalid_string,...j.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...j.errToObj(e)})}url(e){return this._addCheck({kind:"url",...j.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...j.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...j.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...j.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...j.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...j.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...j.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...j.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...j.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...j.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...j.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...j.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,...j.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,...j.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...j.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...j.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...j.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...j.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...j.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...j.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...j.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...j.errToObj(r)})}nonempty(e){return this.min(1,j.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}};Br.create=t=>new Br({checks:[],typeName:T.ZodString,coerce:t?.coerce??!1,...J(t)});xn=class t extends X{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)!==O.number){let s=this._getOrReturnCtx(e);return R(s,{code:$.invalid_type,expected:O.number,received:s.parsedType}),q}let n,o=new We;for(let s of this._def.checks)s.kind==="int"?ne.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:$.invalid_type,expected:"integer",received:"float",message:s.message}),o.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:$.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:$.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),o.dirty()):s.kind==="multipleOf"?ET(e.data,s.value)!==0&&(n=this._getOrReturnCtx(e,n),R(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),R(n,{code:$.not_finite,message:s.message}),o.dirty()):ne.assertNever(s);return{status:o.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,j.toString(r))}gt(e,r){return this.setLimit("min",e,!1,j.toString(r))}lte(e,r){return this.setLimit("max",e,!0,j.toString(r))}lt(e,r){return this.setLimit("max",e,!1,j.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:j.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:j.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:j.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:j.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:j.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:j.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:j.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"&&ne.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)}};xn.create=t=>new xn({checks:[],typeName:T.ZodNumber,coerce:t?.coerce||!1,...J(t)});vn=class t extends X{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)!==O.bigint)return this._getInvalidInput(e);let n,o=new We;for(let s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:$.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(n=this._getOrReturnCtx(e,n),R(n,{code:$.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),o.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),R(n,{code:$.not_multiple_of,multipleOf:s.value,message:s.message}),o.dirty()):ne.assertNever(s);return{status:o.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return R(r,{code:$.invalid_type,expected:O.bigint,received:r.parsedType}),q}gte(e,r){return this.setLimit("min",e,!0,j.toString(r))}gt(e,r){return this.setLimit("min",e,!1,j.toString(r))}lte(e,r){return this.setLimit("max",e,!0,j.toString(r))}lt(e,r){return this.setLimit("max",e,!1,j.toString(r))}setLimit(e,r,n,o){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:j.toString(o)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:j.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:j.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:j.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:j.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:j.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}};vn.create=t=>new vn({checks:[],typeName:T.ZodBigInt,coerce:t?.coerce??!1,...J(t)});bn=class extends X{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==O.boolean){let n=this._getOrReturnCtx(e);return R(n,{code:$.invalid_type,expected:O.boolean,received:n.parsedType}),q}return et(e.data)}};bn.create=t=>new bn({typeName:T.ZodBoolean,coerce:t?.coerce||!1,...J(t)});Sn=class t extends X{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==O.date){let s=this._getOrReturnCtx(e);return R(s,{code:$.invalid_type,expected:O.date,received:s.parsedType}),q}if(Number.isNaN(e.data.getTime())){let s=this._getOrReturnCtx(e);return R(s,{code:$.invalid_date}),q}let n=new We,o;for(let s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(o=this._getOrReturnCtx(e,o),R(o,{code:$.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),n.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(o=this._getOrReturnCtx(e,o),R(o,{code:$.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),n.dirty()):ne.assertNever(s);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:j.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:j.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}};Sn.create=t=>new Sn({checks:[],coerce:t?.coerce||!1,typeName:T.ZodDate,...J(t)});_o=class extends X{_parse(e){if(this._getType(e)!==O.symbol){let n=this._getOrReturnCtx(e);return R(n,{code:$.invalid_type,expected:O.symbol,received:n.parsedType}),q}return et(e.data)}};_o.create=t=>new _o({typeName:T.ZodSymbol,...J(t)});kn=class extends X{_parse(e){if(this._getType(e)!==O.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:$.invalid_type,expected:O.undefined,received:n.parsedType}),q}return et(e.data)}};kn.create=t=>new kn({typeName:T.ZodUndefined,...J(t)});wn=class extends X{_parse(e){if(this._getType(e)!==O.null){let n=this._getOrReturnCtx(e);return R(n,{code:$.invalid_type,expected:O.null,received:n.parsedType}),q}return et(e.data)}};wn.create=t=>new wn({typeName:T.ZodNull,...J(t)});Vr=class extends X{constructor(){super(...arguments),this._any=!0}_parse(e){return et(e.data)}};Vr.create=t=>new Vr({typeName:T.ZodAny,...J(t)});Tr=class extends X{constructor(){super(...arguments),this._unknown=!0}_parse(e){return et(e.data)}};Tr.create=t=>new Tr({typeName:T.ZodUnknown,...J(t)});Gt=class extends X{_parse(e){let r=this._getOrReturnCtx(e);return R(r,{code:$.invalid_type,expected:O.never,received:r.parsedType}),q}};Gt.create=t=>new Gt({typeName:T.ZodNever,...J(t)});yo=class extends X{_parse(e){if(this._getType(e)!==O.undefined){let n=this._getOrReturnCtx(e);return R(n,{code:$.invalid_type,expected:O.void,received:n.parsedType}),q}return et(e.data)}};yo.create=t=>new yo({typeName:T.ZodVoid,...J(t)});Pr=class t extends X{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),o=this._def;if(r.parsedType!==O.array)return R(r,{code:$.invalid_type,expected:O.array,received:r.parsedType}),q;if(o.exactLength!==null){let i=r.data.length>o.exactLength.value,a=r.data.length<o.exactLength.value;(i||a)&&(R(r,{code:i?$.too_big:$.too_small,minimum:a?o.exactLength.value:void 0,maximum:i?o.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:o.exactLength.message}),n.dirty())}if(o.minLength!==null&&r.data.length<o.minLength.value&&(R(r,{code:$.too_small,minimum:o.minLength.value,type:"array",inclusive:!0,exact:!1,message:o.minLength.message}),n.dirty()),o.maxLength!==null&&r.data.length>o.maxLength.value&&(R(r,{code:$.too_big,maximum:o.maxLength.value,type:"array",inclusive:!0,exact:!1,message:o.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,a)=>o.type._parseAsync(new At(r,i,r.path,a)))).then(i=>We.mergeArray(n,i));let s=[...r.data].map((i,a)=>o.type._parseSync(new At(r,i,r.path,a)));return We.mergeArray(n,s)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:j.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:j.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:j.toString(r)}})}nonempty(e){return this.min(1,e)}};Pr.create=(t,e)=>new Pr({type:t,minLength:null,maxLength:null,exactLength:null,typeName:T.ZodArray,...J(e)});ft=class t extends X{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=ne.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==O.object){let u=this._getOrReturnCtx(e);return R(u,{code:$.invalid_type,expected:O.object,received:u.parsedType}),q}let{status:n,ctx:o}=this._processInputParams(e),{shape:s,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Gt&&this._def.unknownKeys==="strip"))for(let u in o.data)i.includes(u)||a.push(u);let c=[];for(let u of i){let l=s[u],d=o.data[u];c.push({key:{status:"valid",value:u},value:l._parse(new At(o,d,o.path,u)),alwaysSet:u in o.data})}if(this._def.catchall instanceof Gt){let u=this._def.unknownKeys;if(u==="passthrough")for(let l of a)c.push({key:{status:"valid",value:l},value:{status:"valid",value:o.data[l]}});else if(u==="strict")a.length>0&&(R(o,{code:$.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let l of a){let d=o.data[l];c.push({key:{status:"valid",value:l},value:u._parse(new At(o,d,o.path,l)),alwaysSet:l in o.data})}}return o.common.async?Promise.resolve().then(async()=>{let u=[];for(let l of c){let d=await l.key,p=await l.value;u.push({key:d,value:p,alwaysSet:l.alwaysSet})}return u}).then(u=>We.mergeObjectSync(n,u)):We.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return j.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let o=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:j.errToObj(e).message??o}:{message:o}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:T.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 ne.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 ne.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return go(this)}partial(e){let r={};for(let n of ne.objectKeys(this.shape)){let o=this.shape[n];e&&!e[n]?r[n]=o:r[n]=o.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of ne.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let s=this.shape[n];for(;s instanceof mt;)s=s._def.innerType;r[n]=s}return new t({...this._def,shape:()=>r})}keyof(){return hy(ne.objectKeys(this.shape))}};ft.create=(t,e)=>new ft({shape:()=>t,unknownKeys:"strip",catchall:Gt.create(),typeName:T.ZodObject,...J(e)});ft.strictCreate=(t,e)=>new ft({shape:()=>t,unknownKeys:"strict",catchall:Gt.create(),typeName:T.ZodObject,...J(e)});ft.lazycreate=(t,e)=>new ft({shape:t,unknownKeys:"strip",catchall:Gt.create(),typeName:T.ZodObject,...J(e)});$n=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function o(s){for(let a of s)if(a.result.status==="valid")return a.result;for(let a of s)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let i=s.map(a=>new pt(a.ctx.common.issues));return R(r,{code:$.invalid_union,unionErrors:i}),q}if(r.common.async)return Promise.all(n.map(async s=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await s._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(o);{let s,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},l=c._parseSync({data:r.data,path:r.path,parent:u});if(l.status==="valid")return l;l.status==="dirty"&&!s&&(s={result:l,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(s)return r.common.issues.push(...s.ctx.common.issues),s.result;let a=i.map(c=>new pt(c));return R(r,{code:$.invalid_union,unionErrors:a}),q}}get options(){return this._def.options}};$n.create=(t,e)=>new $n({options:t,typeName:T.ZodUnion,...J(e)});Er=t=>t instanceof Tn?Er(t.schema):t instanceof Nt?Er(t.innerType()):t instanceof Pn?[t.value]:t instanceof Rn?t.options:t instanceof Cn?ne.objectValues(t.enum):t instanceof On?Er(t._def.innerType):t instanceof kn?[void 0]:t instanceof wn?[null]:t instanceof mt?[void 0,...Er(t.unwrap())]:t instanceof cr?[null,...Er(t.unwrap())]:t instanceof ws||t instanceof An?Er(t.unwrap()):t instanceof In?Er(t._def.innerType):[],ma=class t extends X{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.object)return R(r,{code:$.invalid_type,expected:O.object,received:r.parsedType}),q;let n=this.discriminator,o=r.data[n],s=this.optionsMap.get(o);return s?r.common.async?s._parseAsync({data:r.data,path:r.path,parent:r}):s._parseSync({data:r.data,path:r.path,parent:r}):(R(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),q)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let o=new Map;for(let s of r){let i=Er(s.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let a of i){if(o.has(a))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(a)}`);o.set(a,s)}}return new t({typeName:T.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:o,...J(n)})}};En=class extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=(s,i)=>{if(da(s)||da(i))return q;let a=Rl(s.value,i.value);return a.valid?((pa(s)||pa(i))&&r.dirty(),{status:r.value,value:a.data}):(R(n,{code:$.invalid_intersection_types}),q)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([s,i])=>o(s,i)):o(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};En.create=(t,e,r)=>new En({left:t,right:e,typeName:T.ZodIntersection,...J(r)});ar=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.array)return R(n,{code:$.invalid_type,expected:O.array,received:n.parsedType}),q;if(n.data.length<this._def.items.length)return R(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&n.data.length>this._def.items.length&&(R(n,{code:$.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let s=[...n.data].map((i,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new At(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(s).then(i=>We.mergeArray(r,i)):We.mergeArray(r,s)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};ar.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ar({items:t,typeName:T.ZodTuple,rest:null,...J(e)})};fa=class t extends X{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!==O.object)return R(n,{code:$.invalid_type,expected:O.object,received:n.parsedType}),q;let o=[],s=this._def.keyType,i=this._def.valueType;for(let a in n.data)o.push({key:s._parse(new At(n,a,n.path,a)),value:i._parse(new At(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?We.mergeObjectAsync(r,o):We.mergeObjectSync(r,o)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof X?new t({keyType:e,valueType:r,typeName:T.ZodRecord,...J(n)}):new t({keyType:Br.create(),valueType:e,typeName:T.ZodRecord,...J(r)})}},xo=class extends X{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!==O.map)return R(n,{code:$.invalid_type,expected:O.map,received:n.parsedType}),q;let o=this._def.keyType,s=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:o._parse(new At(n,a,n.path,[u,"key"])),value:s._parse(new At(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,l=await c.value;if(u.status==="aborted"||l.status==="aborted")return q;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,l=c.value;if(u.status==="aborted"||l.status==="aborted")return q;(u.status==="dirty"||l.status==="dirty")&&r.dirty(),a.set(u.value,l.value)}return{status:r.value,value:a}}}};xo.create=(t,e,r)=>new xo({valueType:e,keyType:t,typeName:T.ZodMap,...J(r)});vo=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==O.set)return R(n,{code:$.invalid_type,expected:O.set,received:n.parsedType}),q;let o=this._def;o.minSize!==null&&n.data.size<o.minSize.value&&(R(n,{code:$.too_small,minimum:o.minSize.value,type:"set",inclusive:!0,exact:!1,message:o.minSize.message}),r.dirty()),o.maxSize!==null&&n.data.size>o.maxSize.value&&(R(n,{code:$.too_big,maximum:o.maxSize.value,type:"set",inclusive:!0,exact:!1,message:o.maxSize.message}),r.dirty());let s=this._def.valueType;function i(c){let u=new Set;for(let l of c){if(l.status==="aborted")return q;l.status==="dirty"&&r.dirty(),u.add(l.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>s._parse(new At(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:j.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:j.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};vo.create=(t,e)=>new vo({valueType:t,minSize:null,maxSize:null,typeName:T.ZodSet,...J(e)});ha=class t extends X{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.function)return R(r,{code:$.invalid_type,expected:O.function,received:r.parsedType}),q;function n(a,c){return ks({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fo(),$r].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function o(a,c){return ks({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fo(),$r].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let s={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Wr){let a=this;return et(async function(...c){let u=new pt([]),l=await a._def.args.parseAsync(c,s).catch(f=>{throw u.addIssue(n(c,f)),u}),d=await Reflect.apply(i,this,l);return await a._def.returns._def.type.parseAsync(d,s).catch(f=>{throw u.addIssue(o(d,f)),u})})}else{let a=this;return et(function(...c){let u=a._def.args.safeParse(c,s);if(!u.success)throw new pt([n(c,u.error)]);let l=Reflect.apply(i,this,u.data),d=a._def.returns.safeParse(l,s);if(!d.success)throw new pt([o(l,d.error)]);return d.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:ar.create(e).rest(Tr.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||ar.create([]).rest(Tr.create()),returns:r||Tr.create(),typeName:T.ZodFunction,...J(n)})}},Tn=class extends X{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})}};Tn.create=(t,e)=>new Tn({getter:t,typeName:T.ZodLazy,...J(e)});Pn=class extends X{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return R(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:e.data}}get value(){return this._def.value}};Pn.create=(t,e)=>new Pn({value:t,typeName:T.ZodLiteral,...J(e)});Rn=class t extends X{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return R(r,{expected:ne.joinValues(n),received:r.parsedType,code:$.invalid_type}),q}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 R(r,{received:r.data,code:$.invalid_enum_value,options:n}),q}return et(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})}};Rn.create=hy;Cn=class extends X{_parse(e){let r=ne.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==O.string&&n.parsedType!==O.number){let o=ne.objectValues(r);return R(n,{expected:ne.joinValues(o),received:n.parsedType,code:$.invalid_type}),q}if(this._cache||(this._cache=new Set(ne.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let o=ne.objectValues(r);return R(n,{received:n.data,code:$.invalid_enum_value,options:o}),q}return et(e.data)}get enum(){return this._def.values}};Cn.create=(t,e)=>new Cn({values:t,typeName:T.ZodNativeEnum,...J(e)});Wr=class extends X{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==O.promise&&r.common.async===!1)return R(r,{code:$.invalid_type,expected:O.promise,received:r.parsedType}),q;let n=r.parsedType===O.promise?r.data:Promise.resolve(r.data);return et(n.then(o=>this._def.type.parseAsync(o,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Wr.create=(t,e)=>new Wr({type:t,typeName:T.ZodPromise,...J(e)});Nt=class extends X{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===T.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),o=this._def.effect||null,s={addIssue:i=>{R(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(s.addIssue=s.addIssue.bind(s),o.type==="preprocess"){let i=o.transform(n.data,s);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return q;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?q:c.status==="dirty"?yn(c.value):r.value==="dirty"?yn(c.value):c});{if(r.value==="aborted")return q;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?q:a.status==="dirty"?yn(a.value):r.value==="dirty"?yn(a.value):a}}if(o.type==="refinement"){let i=a=>{let c=o.refinement(a,s);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?q:(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"?q:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(o.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!qr(i))return q;let a=o.transform(i.value,s);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>qr(i)?Promise.resolve(o.transform(i.value,s)).then(a=>({status:r.value,value:a})):q);ne.assertNever(o)}};Nt.create=(t,e,r)=>new Nt({schema:t,typeName:T.ZodEffects,effect:e,...J(r)});Nt.createWithPreprocess=(t,e,r)=>new Nt({schema:e,effect:{type:"preprocess",transform:t},typeName:T.ZodEffects,...J(r)});mt=class extends X{_parse(e){return this._getType(e)===O.undefined?et(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};mt.create=(t,e)=>new mt({innerType:t,typeName:T.ZodOptional,...J(e)});cr=class extends X{_parse(e){return this._getType(e)===O.null?et(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};cr.create=(t,e)=>new cr({innerType:t,typeName:T.ZodNullable,...J(e)});On=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===O.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};On.create=(t,e)=>new On({innerType:t,typeName:T.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...J(e)});In=class extends X{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},o=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ho(o)?o.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new pt(n.common.issues)},input:n.data})})):{status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new pt(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};In.create=(t,e)=>new In({innerType:t,typeName:T.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...J(e)});bo=class extends X{_parse(e){if(this._getType(e)!==O.nan){let n=this._getOrReturnCtx(e);return R(n,{code:$.invalid_type,expected:O.nan,received:n.parsedType}),q}return{status:"valid",value:e.data}}};bo.create=t=>new bo({typeName:T.ZodNaN,...J(t)});TT=Symbol("zod_brand"),ws=class extends X{_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}},$s=class t extends X{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let s=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?q:s.status==="dirty"?(r.dirty(),yn(s.value)):this._def.out._parseAsync({data:s.value,path:n.path,parent:n})})();{let o=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?q:o.status==="dirty"?(r.dirty(),{status:"dirty",value:o.value}):this._def.out._parseSync({data:o.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:T.ZodPipeline})}},An=class extends X{_parse(e){let r=this._def.innerType._parse(e),n=o=>(qr(o)&&(o.value=Object.freeze(o.value)),o);return ho(r)?r.then(o=>n(o)):n(r)}unwrap(){return this._def.innerType}};An.create=(t,e)=>new An({innerType:t,typeName:T.ZodReadonly,...J(e)});PT={object:ft.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"})(T||(T={}));RT=(t,e={message:`Input not instance of ${t.name}`})=>gy(r=>r instanceof t,e),_y=Br.create,yy=xn.create,CT=bo.create,OT=vn.create,xy=bn.create,IT=Sn.create,AT=_o.create,NT=kn.create,zT=wn.create,jT=Vr.create,DT=Tr.create,MT=Gt.create,LT=yo.create,FT=Pr.create,Cl=ft.create,UT=ft.strictCreate,ZT=$n.create,HT=ma.create,qT=En.create,BT=ar.create,VT=fa.create,WT=xo.create,GT=vo.create,KT=ha.create,JT=Tn.create,YT=Pn.create,XT=Rn.create,QT=Cn.create,eP=Wr.create,tP=Nt.create,rP=mt.create,nP=cr.create,oP=Nt.createWithPreprocess,sP=$s.create,iP=()=>_y().optional(),aP=()=>yy().optional(),cP=()=>xy().optional(),uP={string:(t=>Br.create({...t,coerce:!0})),number:(t=>xn.create({...t,coerce:!0})),boolean:(t=>bn.create({...t,coerce:!0})),bigint:(t=>vn.create({...t,coerce:!0})),date:(t=>Sn.create({...t,coerce:!0}))},lP=q});var M={};Ze(M,{BRAND:()=>TT,DIRTY:()=>yn,EMPTY_PATH:()=>sT,INVALID:()=>q,NEVER:()=>lP,OK:()=>et,ParseStatus:()=>We,Schema:()=>X,ZodAny:()=>Vr,ZodArray:()=>Pr,ZodBigInt:()=>vn,ZodBoolean:()=>bn,ZodBranded:()=>ws,ZodCatch:()=>In,ZodDate:()=>Sn,ZodDefault:()=>On,ZodDiscriminatedUnion:()=>ma,ZodEffects:()=>Nt,ZodEnum:()=>Rn,ZodError:()=>pt,ZodFirstPartyTypeKind:()=>T,ZodFunction:()=>ha,ZodIntersection:()=>En,ZodIssueCode:()=>$,ZodLazy:()=>Tn,ZodLiteral:()=>Pn,ZodMap:()=>xo,ZodNaN:()=>bo,ZodNativeEnum:()=>Cn,ZodNever:()=>Gt,ZodNull:()=>wn,ZodNullable:()=>cr,ZodNumber:()=>xn,ZodObject:()=>ft,ZodOptional:()=>mt,ZodParsedType:()=>O,ZodPipeline:()=>$s,ZodPromise:()=>Wr,ZodReadonly:()=>An,ZodRecord:()=>fa,ZodSchema:()=>X,ZodSet:()=>vo,ZodString:()=>Br,ZodSymbol:()=>_o,ZodTransformer:()=>Nt,ZodTuple:()=>ar,ZodType:()=>X,ZodUndefined:()=>kn,ZodUnion:()=>$n,ZodUnknown:()=>Tr,ZodVoid:()=>yo,addIssueToContext:()=>R,any:()=>jT,array:()=>FT,bigint:()=>OT,boolean:()=>xy,coerce:()=>uP,custom:()=>gy,date:()=>IT,datetimeRegex:()=>fy,defaultErrorMap:()=>$r,discriminatedUnion:()=>HT,effect:()=>tP,enum:()=>XT,function:()=>KT,getErrorMap:()=>fo,getParsedType:()=>ir,instanceof:()=>RT,intersection:()=>qT,isAborted:()=>da,isAsync:()=>ho,isDirty:()=>pa,isValid:()=>qr,late:()=>PT,lazy:()=>JT,literal:()=>YT,makeIssue:()=>ks,map:()=>WT,nan:()=>CT,nativeEnum:()=>QT,never:()=>MT,null:()=>zT,nullable:()=>nP,number:()=>yy,object:()=>Cl,objectUtil:()=>$l,oboolean:()=>cP,onumber:()=>aP,optional:()=>rP,ostring:()=>iP,pipeline:()=>sP,preprocess:()=>oP,promise:()=>eP,quotelessJson:()=>rT,record:()=>VT,set:()=>GT,setErrorMap:()=>oT,strictObject:()=>UT,string:()=>_y,symbol:()=>AT,transformer:()=>tP,tuple:()=>BT,undefined:()=>NT,union:()=>ZT,unknown:()=>DT,util:()=>ne,void:()=>LT});var ga=v(()=>{la();Tl();cy();Ss();vy();ua()});var Es=v(()=>{ga()});function S(t,e,r){function n(a,c){var u;Object.defineProperty(a,"_zod",{value:a._zod??{},enumerable:!1}),(u=a._zod).traits??(u.traits=new Set),a._zod.traits.add(t),e(a,c);for(let l in i.prototype)l in a||Object.defineProperty(a,l,{value:i.prototype[l].bind(a)});a._zod.constr=i,a._zod.def=c}let o=r?.Parent??Object;class s extends o{}Object.defineProperty(s,"name",{value:t});function i(a){var c;let u=r?.Parent?new s:this;n(u,a),(c=u._zod).deferred??(c.deferred=[]);for(let l of u._zod.deferred)l();return u}return Object.defineProperty(i,"init",{value:n}),Object.defineProperty(i,Symbol.hasInstance,{value:a=>r?.Parent&&a instanceof r.Parent?!0:a?._zod?.traits?.has(t)}),Object.defineProperty(i,"name",{value:t}),i}function vt(t){return t&&Object.assign(_a,t),_a}var pP,Rr,_a,So=v(()=>{pP=Object.freeze({status:"aborted"});Rr=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},_a={}});var oe={};Ze(oe,{BIGINT_FORMAT_RANGES:()=>Sy,Class:()=>Il,NUMBER_FORMAT_RANGES:()=>Ll,aborted:()=>zn,allowsEval:()=>jl,assert:()=>_P,assertEqual:()=>mP,assertIs:()=>hP,assertNever:()=>gP,assertNotEqual:()=>fP,assignProp:()=>zl,cached:()=>Rs,captureStackTrace:()=>xa,cleanEnum:()=>CP,cleanRegex:()=>Os,clone:()=>bt,createTransparentProxy:()=>kP,defineLazy:()=>be,esc:()=>Nn,escapeRegex:()=>Gr,extend:()=>EP,finalizeIssue:()=>Kt,floatSafeRemainder:()=>Nl,getElementAtPath:()=>yP,getEnumValues:()=>Ps,getLengthableOrigin:()=>Is,getParsedType:()=>SP,getSizableOrigin:()=>ky,isObject:()=>ko,isPlainObject:()=>wo,issue:()=>Fl,joinValues:()=>ya,jsonStringifyReplacer:()=>Al,merge:()=>TP,normalizeParams:()=>B,nullish:()=>Cs,numKeys:()=>bP,omit:()=>$P,optionalKeys:()=>Ml,partial:()=>PP,pick:()=>wP,prefixIssues:()=>ur,primitiveTypes:()=>by,promiseAllObject:()=>xP,propertyKeyTypes:()=>Dl,randomString:()=>vP,required:()=>RP,stringifyPrimitive:()=>va,unwrapMessage:()=>Ts});function mP(t){return t}function fP(t){return t}function hP(t){}function gP(t){throw new Error}function _P(t){}function Ps(t){let e=Object.values(t).filter(n=>typeof n=="number");return Object.entries(t).filter(([n,o])=>e.indexOf(+n)===-1).map(([n,o])=>o)}function ya(t,e="|"){return t.map(r=>va(r)).join(e)}function Al(t,e){return typeof e=="bigint"?e.toString():e}function Rs(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Cs(t){return t==null}function Os(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function Nl(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,o=r>n?r:n,s=Number.parseInt(t.toFixed(o).replace(".","")),i=Number.parseInt(e.toFixed(o).replace(".",""));return s%i/10**o}function be(t,e,r){Object.defineProperty(t,e,{get(){{let o=r();return t[e]=o,o}throw new Error("cached value already set")},set(o){Object.defineProperty(t,e,{value:o})},configurable:!0})}function zl(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function yP(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function xP(t){let e=Object.keys(t),r=e.map(n=>t[n]);return Promise.all(r).then(n=>{let o={};for(let s=0;s<e.length;s++)o[e[s]]=n[s];return o})}function vP(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Nn(t){return JSON.stringify(t)}function ko(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function wo(t){if(ko(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(ko(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function bP(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function Gr(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bt(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function B(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 kP(t){let e;return new Proxy({},{get(r,n,o){return e??(e=t()),Reflect.get(e,n,o)},set(r,n,o,s){return e??(e=t()),Reflect.set(e,n,o,s)},has(r,n){return e??(e=t()),Reflect.has(e,n)},deleteProperty(r,n){return e??(e=t()),Reflect.deleteProperty(e,n)},ownKeys(r){return e??(e=t()),Reflect.ownKeys(e)},getOwnPropertyDescriptor(r,n){return e??(e=t()),Reflect.getOwnPropertyDescriptor(e,n)},defineProperty(r,n,o){return e??(e=t()),Reflect.defineProperty(e,n,o)}})}function va(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Ml(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function wP(t,e){let r={},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(r[o]=n.shape[o])}return bt(t,{...t._zod.def,shape:r,checks:[]})}function $P(t,e){let r={...t._zod.def.shape},n=t._zod.def;for(let o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete r[o]}return bt(t,{...t._zod.def,shape:r,checks:[]})}function EP(t,e){if(!wo(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 zl(this,"shape",n),n},checks:[]};return bt(t,r)}function TP(t,e){return bt(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return zl(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function PP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in n))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=t?new t({type:"optional",innerType:n[s]}):n[s])}else for(let s in n)o[s]=t?new t({type:"optional",innerType:n[s]}):n[s];return bt(e,{...e._zod.def,shape:o,checks:[]})}function RP(t,e,r){let n=e._zod.def.shape,o={...n};if(r)for(let s in r){if(!(s in o))throw new Error(`Unrecognized key: "${s}"`);r[s]&&(o[s]=new t({type:"nonoptional",innerType:n[s]}))}else for(let s in n)o[s]=new t({type:"nonoptional",innerType:n[s]});return bt(e,{...e._zod.def,shape:o,checks:[]})}function zn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function ur(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function Ts(t){return typeof t=="string"?t:t?.message}function Kt(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let o=Ts(t.inst?._zod.def?.error?.(t))??Ts(e?.error?.(t))??Ts(r.customError?.(t))??Ts(r.localeError?.(t))??"Invalid input";n.message=o}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function ky(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Is(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Fl(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function CP(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var xa,jl,SP,Dl,by,Ll,Sy,Il,lr=v(()=>{xa=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};jl=Rs(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});SP=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}`)}},Dl=new Set(["string","number","symbol"]),by=new Set(["string","number","bigint","boolean","symbol","undefined"]);Ll={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]},Sy={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Il=class{constructor(...e){}}});function Ul(t,e=r=>r.message){let r={},n=[];for(let o of t.issues)o.path.length>0?(r[o.path[0]]=r[o.path[0]]||[],r[o.path[0]].push(e(o))):n.push(e(o));return{formErrors:n,fieldErrors:r}}function Zl(t,e){let r=e||function(s){return s.message},n={_errors:[]},o=s=>{for(let i of s.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map(a=>o({issues:a}));else if(i.code==="invalid_key")o({issues:i.issues});else if(i.code==="invalid_element")o({issues:i.issues});else if(i.path.length===0)n._errors.push(r(i));else{let a=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(i))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return o(t),n}var wy,ba,As,Hl=v(()=>{So();lr();wy=(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,Al,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},ba=S("$ZodError",wy),As=S("$ZodError",wy,{Parent:Error})});var ql,Bl,Vl,Wl,Gl,jn,Kl,Dn,Jl=v(()=>{So();Hl();lr();ql=t=>(e,r,n,o)=>{let s=n?Object.assign(n,{async:!1}):{async:!1},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise)throw new Rr;if(i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Kt(c,s,vt())));throw xa(a,o?.callee),a}return i.value},Bl=ql(As),Vl=t=>async(e,r,n,o)=>{let s=n?Object.assign(n,{async:!0}):{async:!0},i=e._zod.run({value:r,issues:[]},s);if(i instanceof Promise&&(i=await i),i.issues.length){let a=new(o?.Err??t)(i.issues.map(c=>Kt(c,s,vt())));throw xa(a,o?.callee),a}return i.value},Wl=Vl(As),Gl=t=>(e,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=e._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Rr;return s.issues.length?{success:!1,error:new(t??ba)(s.issues.map(i=>Kt(i,o,vt())))}:{success:!0,data:s.value}},jn=Gl(As),Kl=t=>async(e,r,n)=>{let o=n?Object.assign(n,{async:!0}):{async:!0},s=e._zod.run({value:r,issues:[]},o);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(i=>Kt(i,o,vt())))}:{success:!0,data:s.value}},Dn=Kl(As)});function Ny(){return new RegExp(IP,"u")}function qy(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 By(t){return new RegExp(`^${qy(t)}$`)}function Vy(t){let e=qy({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(`^${Zy}T(?:${n})$`)}var $y,Ey,Ty,Py,Ry,Cy,Oy,Iy,Yl,Ay,IP,zy,jy,Dy,My,Ly,Xl,Fy,Uy,Zy,Hy,Wy,Gy,Ky,Jy,Yy,Xy,Qy,ka=v(()=>{$y=/^[cC][^\s-]{8,}$/,Ey=/^[0-9a-z]+$/,Ty=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Py=/^[0-9a-vA-V]{20}$/,Ry=/^[A-Za-z0-9]{27}$/,Cy=/^[a-zA-Z0-9_-]{21}$/,Oy=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Iy=/^([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})$/,Yl=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)$/,Ay=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,IP="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";zy=/^(?:(?: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])$/,jy=/^(([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})$/,Dy=/^((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])$/,My=/^(([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])$/,Ly=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Xl=/^[A-Za-z0-9_-]*$/,Fy=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Uy=/^\+(?:[0-9]){6,14}[0-9]$/,Zy="(?:(?:\\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])))",Hy=new RegExp(`^${Zy}$`);Wy=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Gy=/^\d+$/,Ky=/^-?\d+(?:\.\d+)?/i,Jy=/true|false/i,Yy=/null/i,Xy=/^[^A-Z]*$/,Qy=/^[^a-z]*$/});var Ge,ex,Ql,ed,tx,rx,nx,ox,sx,Ns,ix,ax,cx,ux,lx,dx,px,wa=v(()=>{So();ka();lr();Ge=S("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ex={number:"number",bigint:"bigint",object:"date"},Ql=S("$ZodCheckLessThan",(t,e)=>{Ge.init(t,e);let r=ex[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.maximum:o.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?o.maximum=e.value:o.exclusiveMaximum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value<=e.value:n.value<e.value)||n.issues.push({origin:r,code:"too_big",maximum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),ed=S("$ZodCheckGreaterThan",(t,e)=>{Ge.init(t,e);let r=ex[typeof e.value];t._zod.onattach.push(n=>{let o=n._zod.bag,s=(e.inclusive?o.minimum:o.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?o.minimum=e.value:o.exclusiveMinimum=e.value)}),t._zod.check=n=>{(e.inclusive?n.value>=e.value:n.value>e.value)||n.issues.push({origin:r,code:"too_small",minimum:e.value,input:n.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),tx=S("$ZodCheckMultipleOf",(t,e)=>{Ge.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):Nl(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})}}),rx=S("$ZodCheckNumberFormat",(t,e)=>{Ge.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[o,s]=Ll[e.format];t._zod.onattach.push(i=>{let a=i._zod.bag;a.format=e.format,a.minimum=o,a.maximum=s,r&&(a.pattern=Gy)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<o&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:t,continue:!e.abort}),a>s&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inst:t})}}),nx=S("$ZodCheckMaxLength",(t,e)=>{var r;Ge.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Cs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<o&&(n._zod.bag.maximum=e.maximum)}),t._zod.check=n=>{let o=n.value;if(o.length<=e.maximum)return;let i=Is(o);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),ox=S("$ZodCheckMinLength",(t,e)=>{var r;Ge.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Cs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>o&&(n._zod.bag.minimum=e.minimum)}),t._zod.check=n=>{let o=n.value;if(o.length>=e.minimum)return;let i=Is(o);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:o,inst:t,continue:!e.abort})}}),sx=S("$ZodCheckLengthEquals",(t,e)=>{var r;Ge.init(t,e),(r=t._zod.def).when??(r.when=n=>{let o=n.value;return!Cs(o)&&o.length!==void 0}),t._zod.onattach.push(n=>{let o=n._zod.bag;o.minimum=e.length,o.maximum=e.length,o.length=e.length}),t._zod.check=n=>{let o=n.value,s=o.length;if(s===e.length)return;let i=Is(o),a=s>e.length;n.issues.push({origin:i,...a?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:n.value,inst:t,continue:!e.abort})}}),Ns=S("$ZodCheckStringFormat",(t,e)=>{var r,n;Ge.init(t,e),t._zod.onattach.push(o=>{let s=o._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(r=t._zod).check??(r.check=o=>{e.pattern.lastIndex=0,!e.pattern.test(o.value)&&o.issues.push({origin:"string",code:"invalid_format",format:e.format,input:o.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(n=t._zod).check??(n.check=()=>{})}),ix=S("$ZodCheckRegex",(t,e)=>{Ns.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})}}),ax=S("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=Xy),Ns.init(t,e)}),cx=S("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=Qy),Ns.init(t,e)}),ux=S("$ZodCheckIncludes",(t,e)=>{Ge.init(t,e);let r=Gr(e.includes),n=new RegExp(typeof e.position=="number"?`^.{${e.position}}${r}`:r);e.pattern=n,t._zod.onattach.push(o=>{let s=o._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(n)}),t._zod.check=o=>{o.value.includes(e.includes,e.position)||o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:o.value,inst:t,continue:!e.abort})}}),lx=S("$ZodCheckStartsWith",(t,e)=>{Ge.init(t,e);let r=new RegExp(`^${Gr(e.prefix)}.*`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.startsWith(e.prefix)||n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:n.value,inst:t,continue:!e.abort})}}),dx=S("$ZodCheckEndsWith",(t,e)=>{Ge.init(t,e);let r=new RegExp(`.*${Gr(e.suffix)}$`);e.pattern??(e.pattern=r),t._zod.onattach.push(n=>{let o=n._zod.bag;o.patterns??(o.patterns=new Set),o.patterns.add(r)}),t._zod.check=n=>{n.value.endsWith(e.suffix)||n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:n.value,inst:t,continue:!e.abort})}}),px=S("$ZodCheckOverwrite",(t,e)=>{Ge.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var $a,td=v(()=>{$a=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(`
20
- `).filter(i=>i),o=Math.min(...n.map(i=>i.length-i.trimStart().length)),s=n.map(i=>i.slice(o)).map(i=>" ".repeat(this.indent*2)+i);for(let i of s)this.content.push(i)}compile(){let e=Function,r=this?.args,o=[...(this?.content??[""]).map(s=>` ${s}`)];return new e(...r,o.join(`
21
- `))}}});var fx,rd=v(()=>{fx={major:4,minor:0,patch:0}});function Px(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function AP(t){if(!Xl.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Px(r)}function NP(t,e=null){try{let r=t.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));return!("typ"in o&&o?.typ!=="JWT"||!o.alg||e&&(!("alg"in o)||o.alg!==e))}catch{return!1}}function hx(t,e,r){t.issues.length&&e.issues.push(...ur(r,t.issues)),e.value[r]=t.value}function Ea(t,e,r){t.issues.length&&e.issues.push(...ur(r,t.issues)),e.value[r]=t.value}function gx(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(...ur(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function _x(t,e,r,n){for(let o of t)if(o.issues.length===0)return e.value=o.value,e;return e.issues.push({code:"invalid_union",input:e.value,inst:r,errors:t.map(o=>o.issues.map(s=>Kt(s,n,vt())))}),e}function nd(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(wo(t)&&wo(e)){let r=Object.keys(e),n=Object.keys(t).filter(s=>r.indexOf(s)!==-1),o={...t,...e};for(let s of n){let i=nd(t[s],e[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<t.length;n++){let o=t[n],s=e[n],i=nd(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function yx(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),zn(t))return t;let n=nd(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 xx(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function vx(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 bx(t,e,r){return zn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Sx(t){return t.value=Object.freeze(t.value),t}function kx(t,e,r,n){if(!t){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};n._zod.def.params&&(o.params=n._zod.def.params),e.issues.push(Fl(o))}}var ge,zs,Se,od,sd,id,ad,cd,ud,ld,dd,pd,md,fd,wx,$x,Ex,Tx,hd,gd,_d,yd,xd,vd,bd,Sd,Ta,kd,wd,$d,Ed,Td,Pd,Pa,Ra,Rd,Cd,Od,Id,Ad,Nd,zd,jd,Dd,Md,Ld,Fd,Ud,Zd,Hd,Rx=v(()=>{wa();So();td();Jl();ka();lr();rd();lr();ge=S("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=fx;let n=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&n.unshift(t);for(let o of n)for(let s of o._zod.onattach)s(t);if(n.length===0)(r=t._zod).deferred??(r.deferred=[]),t._zod.deferred?.push(()=>{t._zod.run=t._zod.parse});else{let o=(s,i,a)=>{let c=zn(s),u;for(let l of i){if(l._zod.def.when){if(!l._zod.def.when(s))continue}else if(c)continue;let d=s.issues.length,p=l._zod.check(s);if(p instanceof Promise&&a?.async===!1)throw new Rr;if(u||p instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await p,s.issues.length!==d&&(c||(c=zn(s,d)))});else{if(s.issues.length===d)continue;c||(c=zn(s,d))}}return u?u.then(()=>s):s};t._zod.run=(s,i)=>{let a=t._zod.parse(s,i);if(a instanceof Promise){if(i.async===!1)throw new Rr;return a.then(c=>o(c,n,i))}return o(a,n,i)}}t["~standard"]={validate:o=>{try{let s=jn(t,o);return s.success?{value:s.data}:{issues:s.error?.issues}}catch{return Dn(t,o).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),zs=S("$ZodString",(t,e)=>{ge.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Wy(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}}),Se=S("$ZodStringFormat",(t,e)=>{Ns.init(t,e),zs.init(t,e)}),od=S("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=Iy),Se.init(t,e)}),sd=S("$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=Yl(n))}else e.pattern??(e.pattern=Yl());Se.init(t,e)}),id=S("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=Ay),Se.init(t,e)}),ad=S("$ZodURL",(t,e)=>{Se.init(t,e),t._zod.check=r=>{try{let n=r.value,o=new URL(n),s=o.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(o.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:Fy.source,input:r.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(o.protocol.endsWith(":")?o.protocol.slice(0,-1):o.protocol)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:r.value,inst:t,continue:!e.abort})),!n.endsWith("/")&&s.endsWith("/")?r.value=s.slice(0,-1):r.value=s;return}catch{r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:t,continue:!e.abort})}}}),cd=S("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Ny()),Se.init(t,e)}),ud=S("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Cy),Se.init(t,e)}),ld=S("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=$y),Se.init(t,e)}),dd=S("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ey),Se.init(t,e)}),pd=S("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ty),Se.init(t,e)}),md=S("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Py),Se.init(t,e)}),fd=S("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Ry),Se.init(t,e)}),wx=S("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Vy(e)),Se.init(t,e)}),$x=S("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Hy),Se.init(t,e)}),Ex=S("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=By(e)),Se.init(t,e)}),Tx=S("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Oy),Se.init(t,e)}),hd=S("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=zy),Se.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),gd=S("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=jy),Se.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})}}}),_d=S("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Dy),Se.init(t,e)}),yd=S("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=My),Se.init(t,e),t._zod.check=r=>{let[n,o]=r.value.split("/");try{if(!o)throw new Error;let s=Number(o);if(`${s}`!==o)throw new Error;if(s<0||s>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});xd=S("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Ly),Se.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Px(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});vd=S("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Xl),Se.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{AP(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),bd=S("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Uy),Se.init(t,e)});Sd=S("$ZodJWT",(t,e)=>{Se.init(t,e),t._zod.check=r=>{NP(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Ta=S("$ZodNumber",(t,e)=>{ge.init(t,e),t._zod.pattern=t._zod.bag.pattern??Ky,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=Number(r.value)}catch{}let o=r.value;if(typeof o=="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o=="number"?Number.isNaN(o)?"NaN":Number.isFinite(o)?void 0:"Infinity":void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:t,...s?{received:s}:{}}),r}}),kd=S("$ZodNumber",(t,e)=>{rx.init(t,e),Ta.init(t,e)}),wd=S("$ZodBoolean",(t,e)=>{ge.init(t,e),t._zod.pattern=Jy,t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=!!r.value}catch{}let o=r.value;return typeof o=="boolean"||r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:t}),r}}),$d=S("$ZodNull",(t,e)=>{ge.init(t,e),t._zod.pattern=Yy,t._zod.values=new Set([null]),t._zod.parse=(r,n)=>{let o=r.value;return o===null||r.issues.push({expected:"null",code:"invalid_type",input:o,inst:t}),r}}),Ed=S("$ZodUnknown",(t,e)=>{ge.init(t,e),t._zod.parse=r=>r}),Td=S("$ZodNever",(t,e)=>{ge.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});Pd=S("$ZodArray",(t,e)=>{ge.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!Array.isArray(o))return r.issues.push({expected:"array",code:"invalid_type",input:o,inst:t}),r;r.value=Array(o.length);let s=[];for(let i=0;i<o.length;i++){let a=o[i],c=e.element._zod.run({value:a,issues:[]},n);c instanceof Promise?s.push(c.then(u=>hx(u,r,i))):hx(c,r,i)}return s.length?Promise.all(s).then(()=>r):r}});Pa=S("$ZodObject",(t,e)=>{ge.init(t,e);let r=Rs(()=>{let d=Object.keys(e.shape);for(let f of d)if(!(e.shape[f]instanceof ge))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let p=Ml(e.shape);return{shape:e.shape,keys:d,keySet:new Set(d),numKeys:d.length,optionalKeys:new Set(p)}});be(t._zod,"propValues",()=>{let d=e.shape,p={};for(let f in d){let m=d[f]._zod;if(m.values){p[f]??(p[f]=new Set);for(let h of m.values)p[f].add(h)}}return p});let n=d=>{let p=new $a(["shape","payload","ctx"]),f=r.value,m=_=>{let x=Nn(_);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};p.write("const input = payload.value;");let h=Object.create(null),g=0;for(let _ of f.keys)h[_]=`key_${g++}`;p.write("const newResult = {}");for(let _ of f.keys)if(f.optionalKeys.has(_)){let x=h[_];p.write(`const ${x} = ${m(_)};`);let k=Nn(_);p.write(`
2
+ var O$=Object.create;var nl=Object.defineProperty;var I$=Object.getOwnPropertyDescriptor;var A$=Object.getOwnPropertyNames;var N$=Object.getPrototypeOf,D$=Object.prototype.hasOwnProperty;var Py=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var v=(t,e)=>()=>(t&&(e=t(t=0)),e);var N=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Le=(t,e)=>{for(var r in e)nl(t,r,{get:e[r],enumerable:!0})},M$=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of A$(e))!D$.call(t,s)&&s!==r&&nl(t,s,{get:()=>e[s],enumerable:!(n=I$(e,s))||n.enumerable});return t};var wo=(t,e,r)=>(r=t!=null?O$(N$(t)):{},M$(e||!t||!t.__esModule?nl(r,"default",{value:t,enumerable:!0}):r,t));var ll=N((m2,Uy)=>{"use strict";var ul={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"},V$={up:(t=1)=>"\x1B[S".repeat(t),down:(t=1)=>"\x1B[T".repeat(t)},W$={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?ul.up():"");return t&&(e+=ul.left),e}};Uy.exports={cursor:ul,scroll:V$,erase:W$,beep:"\x07"}});var Gy=N((K2,yl)=>{var la=process||{},Vy=la.argv||[],ua=la.env||{},_T=!(ua.NO_COLOR||Vy.includes("--no-color"))&&(!!ua.FORCE_COLOR||Vy.includes("--color")||la.platform==="win32"||(la.stdout||{}).isTTY&&ua.TERM!=="dumb"||!!ua.CI),xT=(t,e,r=t)=>n=>{let s=""+n,o=s.indexOf(e,t.length);return~o?t+vT(s,e,r,o)+e:t+s+e},vT=(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)},Wy=(t=_T)=>{let e=t?xT:()=>String;return{isColorSupported:t,reset:e("\x1B[0m","\x1B[0m"),bold:e("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:e("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:e("\x1B[3m","\x1B[23m"),underline:e("\x1B[4m","\x1B[24m"),inverse:e("\x1B[7m","\x1B[27m"),hidden:e("\x1B[8m","\x1B[28m"),strikethrough:e("\x1B[9m","\x1B[29m"),black:e("\x1B[30m","\x1B[39m"),red:e("\x1B[31m","\x1B[39m"),green:e("\x1B[32m","\x1B[39m"),yellow:e("\x1B[33m","\x1B[39m"),blue:e("\x1B[34m","\x1B[39m"),magenta:e("\x1B[35m","\x1B[39m"),cyan:e("\x1B[36m","\x1B[39m"),white:e("\x1B[37m","\x1B[39m"),gray:e("\x1B[90m","\x1B[39m"),bgBlack:e("\x1B[40m","\x1B[49m"),bgRed:e("\x1B[41m","\x1B[49m"),bgGreen:e("\x1B[42m","\x1B[49m"),bgYellow:e("\x1B[43m","\x1B[49m"),bgBlue:e("\x1B[44m","\x1B[49m"),bgMagenta:e("\x1B[45m","\x1B[49m"),bgCyan:e("\x1B[46m","\x1B[49m"),bgWhite:e("\x1B[47m","\x1B[49m"),blackBright:e("\x1B[90m","\x1B[39m"),redBright:e("\x1B[91m","\x1B[39m"),greenBright:e("\x1B[92m","\x1B[39m"),yellowBright:e("\x1B[93m","\x1B[39m"),blueBright:e("\x1B[94m","\x1B[39m"),magentaBright:e("\x1B[95m","\x1B[39m"),cyanBright:e("\x1B[96m","\x1B[39m"),whiteBright:e("\x1B[97m","\x1B[39m"),bgBlackBright:e("\x1B[100m","\x1B[49m"),bgRedBright:e("\x1B[101m","\x1B[49m"),bgGreenBright:e("\x1B[102m","\x1B[49m"),bgYellowBright:e("\x1B[103m","\x1B[49m"),bgBlueBright:e("\x1B[104m","\x1B[49m"),bgMagentaBright:e("\x1B[105m","\x1B[49m"),bgCyanBright:e("\x1B[106m","\x1B[49m"),bgWhiteBright:e("\x1B[107m","\x1B[49m")}};yl.exports=Wy();yl.exports.createColors=Wy});import{execFileSync as Ky,execSync as xl}from"node:child_process";import{existsSync as da}from"node:fs";function ST(t){let e=t.split(/[\\/]/),r=e[e.length-1];return bT.test(r)}function rt(t){try{let e=hs?`where ${t}`:`command -v ${t}`;return xl(e,{stdio:"pipe"}),!0}catch{return!1}}function _l(t){if(hs)try{let r=xl(`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(!rt(t))return!1;try{return Ky(t,["--version"],{shell:hs,stdio:"pipe",timeout:hs?5e3:1500}),!0}catch{return!1}}function Jy(){if(rt("bun"))return!0;for(let t of Yy())if(da(t))return!0;return!1}function kT(){for(let e of Yy())if(da(e))return e;if(rt("bun"))return"bun";let t=process.env.HOME??process.env.USERPROFILE??"";return hs?`${t}\\.bun\\bin\\bun.exe`:`${t}/.bun/bin/bun`}function Yy(){let t=process.env.HOME??process.env.USERPROFILE??"";if(hs){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 wT(){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(da(e))return e;try{let r=xl("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 er(t,e=["--version"]){try{return Ky(t,e,{encoding:"utf-8",shell:process.platform==="win32",stdio:["pipe","pipe","pipe"],timeout:5e3}).trim().split(/\r?\n/)[0]}catch{return"unknown"}}function gs(){let e=Jy()?kT():null,r=process.env.SHELL,n=r&&da(r)&&ST(r)?r:null,s=process.platform==="win32";return{javascript:e??process.execPath,typescript:e||(rt("tsx")?"tsx":rt("ts-node")?"ts-node":null),python:_l("python3")?"python3":_l("python")?"python":_l("py")?"py":null,shell:n??(s?wT()??(rt("sh")?"sh":rt("powershell")?"powershell":"cmd.exe"):rt("bash")?"bash":"sh"),ruby:rt("ruby")?"ruby":null,go:rt("go")?"go":null,rust:rt("rustc")?"rustc":null,php:rt("php")?"php":null,perl:rt("perl")?"perl":null,r:rt("Rscript")?"Rscript":rt("r")?"r":null,elixir:rt("elixir")?"elixir":null}}function ys(){return Jy()}function pa(t){let e=[],r=t.javascript?.endsWith("bun")??!1;return e.push(` JavaScript: ${t.javascript} (${er(t.javascript)})${r?" \u26A1":""}`),t.typescript?e.push(` TypeScript: ${t.typescript} (${er(t.typescript)})`):e.push(" TypeScript: not available (install bun, tsx, or ts-node)"),t.python?e.push(` Python: ${t.python} (${er(t.python)})`):e.push(" Python: not available"),e.push(` Shell: ${t.shell} (${er(t.shell)})`),t.ruby&&e.push(` Ruby: ${t.ruby} (${er(t.ruby)})`),t.go&&e.push(` Go: ${t.go} (${er(t.go,["version"])})`),t.rust&&e.push(` Rust: ${t.rust} (${er(t.rust)})`),t.php&&e.push(` PHP: ${t.php} (${er(t.php)})`),t.perl&&e.push(` Perl: ${t.perl} (${er(t.perl)})`),t.r&&e.push(` R: ${t.r} (${er(t.r)})`),t.elixir&&e.push(` Elixir: ${t.elixir} (${er(t.elixir)})`),r||(e.push(""),e.push(" Tip: Install Bun for 3-5x faster JS/TS execution \u2192 https://bun.sh")),e.join(`
3
+ `)}function ma(t){let e=["javascript","shell"];return t.typescript&&e.push("typescript"),t.python&&e.push("python"),t.ruby&&e.push("ruby"),t.go&&e.push("go"),t.rust&&e.push("rust"),t.php&&e.push("php"),t.perl&&e.push("perl"),t.r&&e.push("r"),t.elixir&&e.push("elixir"),e}function Xy(t,e,r){switch(e){case"javascript":return t.javascript.endsWith("bun")?[t.javascript,"run",r]:[t.javascript,r];case"typescript":if(!t.typescript)throw new Error("No TypeScript runtime available. Install one of: bun (recommended), tsx (npm i -g tsx), or ts-node.");return t.typescript?.endsWith("bun")?[t.typescript,"run",r]:t.typescript==="tsx"?["tsx",r]:["ts-node",r];case"python":if(!t.python)throw new Error("No Python runtime available. Install python3 or python.");return[t.python,r];case"shell":{if(process.platform==="win32"){let s=t.shell.toLowerCase();if(s.includes("bash")||s.endsWith("/sh")||s.endsWith("\\sh.exe")){let o=r.replace(/'/g,"'\\''");return[t.shell,"-c",`source '${o}'`]}if(s.includes("powershell")||s.includes("pwsh"))return[t.shell,"-File",r]}return[t.shell,r]}case"ruby":if(!t.ruby)throw new Error("Ruby not available. Install ruby.");return[t.ruby,r];case"go":if(!t.go)throw new Error("Go not available. Install go.");return["go","run",r];case"rust":{if(!t.rust)throw new Error("Rust not available. Install rustc via https://rustup.rs");return["__rust_compile_run__",r]}case"php":if(!t.php)throw new Error("PHP not available. Install php.");return["php",r];case"perl":if(!t.perl)throw new Error("Perl not available. Install perl.");return["perl",r];case"r":if(!t.r)throw new Error("R not available. Install R / Rscript.");return[t.r,r];case"elixir":if(!t.elixir)throw new Error("Elixir not available. Install elixir.");return["elixir",r]}}var bT,hs,fa=v(()=>{"use strict";bT=/^(bash|sh|zsh|dash|pwsh|powershell|cmd)(\.exe)?$/i;hs=process.platform==="win32"});function ET(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 $T(t){let e=t.match(/(?:"([^"]+\.mjs)"|'([^']+\.mjs)'|(\S+\.mjs))/);return e?.[1]??e?.[2]??e?.[3]??null}function ha(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 ET(o)){let a=$T(i);a&&r.add(a)}return[...r]}var vl=v(()=>{"use strict"});import{resolve as To}from"node:path";import{homedir as bl}from"node:os";import{createRequire as TT}from"node:module";function We(t=process.env){let e=t.CLAUDE_CONFIG_DIR;return e&&e.trim()!==""?e.startsWith("~")?To(bl(),e.replace(/^~[/\\]?/,"")):To(e):To(bl(),".claude")}function PT(t=process.env){return To(We(t),"settings.json")}function Sl(t=process.env){let e=[],r=null,n=null;try{let i=TT(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(To(bl(),...o,"settings.json"))}let s=PT(t);return e.includes(s)||e.push(s),e}var Wr=v(()=>{"use strict"});var Qy,e_=v(()=>{"use strict";Qy={"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",Zed:"zed",zed:"zed","qwen-code":"qwen-code","qwen-cli-mcp-client":"qwen-code"}});import{join as kl}from"node:path";import{accessSync as RT,copyFileSync as CT,constants as OT,mkdirSync as IT}from"node:fs";import{homedir as t_}from"node:os";var Se,Tt=v(()=>{"use strict";Se=class{constructor(e){this.sessionDirSegments=e}getSessionDir(){let e=kl(t_(),...this.sessionDirSegments,"context-mode","sessions");return IT(e,{recursive:!0}),e}getConfigDir(e){return kl(t_(),...this.sessionDirSegments)}getInstructionFiles(){return["CLAUDE.md"]}getMemoryDir(){return kl(this.getConfigDir(),"memory")}backupSettings(){let e=this.getSettingsPath();try{RT(e,OT.R_OK);let r=e+".bak";return CT(e,r),r}catch{return null}}}});var _s,wl=v(()=>{"use strict";Tt();_s=class extends Se{parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:process.env[this.projectDirEnvVar]??process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{updatedInput:e.updatedInput};if(e.decision==="context"&&e.additionalContext)return{additionalContext:e.additionalContext};if(e.decision==="ask")return{permissionDecision:"ask"}}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),e.updatedOutput&&(r.updatedMCPToolOutput=e.updatedOutput),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}}});function Fe(t){let e=process.execPath.replace(/\\/g,"/"),r=t.replace(/\\/g,"/");return`"${e}" "${r}"`}var Gr=v(()=>{"use strict"});function Po(t,e){let r=xs[e],n=El(e);return t.hooks?.some(s=>s.command?.includes(r)||s.command?.includes(n))??!1}function El(t,e){if(e){let r=xs[t];return Fe(`${e}/hooks/${r}`)}return`context-mode hook claude-code ${t.toLowerCase()}`}function $l(t){let e=t.match(/"[^"]+"\s+"([^"]+\.mjs)"/);return e?e[1]:t.match(/node\s+"?([^"]+\.mjs)"?/)?.[1]??null}function s_(t){let e=Object.values(xs);return t.hooks?.some(r=>r.command!=null&&(e.some(n=>r.command.includes(n))||r.command.includes("context-mode hook")))??!1}var tr,AT,r_,NT,mU,xs,n_,fU,o_=v(()=>{"use strict";Gr();tr={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",USER_PROMPT_SUBMIT:"UserPromptSubmit"},AT=["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"],r_=AT.join("|"),NT=["Bash","Read","Write","Edit","NotebookEdit","Glob","Grep","TodoWrite","TaskCreate","TaskUpdate","EnterPlanMode","ExitPlanMode","Skill","Agent","AskUserQuestion","EnterWorktree","mcp__"],mU=NT.join("|"),xs={PreToolUse:"pretooluse.mjs",PostToolUse:"posttooluse.mjs",PreCompact:"precompact.mjs",SessionStart:"sessionstart.mjs",UserPromptSubmit:"userpromptsubmit.mjs"},n_=[tr.PRE_TOOL_USE,tr.SESSION_START],fU=[tr.POST_TOOL_USE,tr.PRE_COMPACT,tr.USER_PROMPT_SUBMIT]});var Pl={};Le(Pl,{ClaudeCodeAdapter:()=>Tl});import{readFileSync as ga,writeFileSync as i_,existsSync as DT,readdirSync as MT,chmodSync as jT,accessSync as zT,mkdirSync as LT,constants as FT}from"node:fs";import{resolve as ya,join as vs}from"node:path";import{homedir as a_}from"node:os";var Tl,Rl=v(()=>{"use strict";wl();Wr();o_();Tl=class extends _s{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 We()}getSessionDir(){let e=vs(this.getConfigDir(),"context-mode","sessions");return LT(e,{recursive:!0}),e}getSettingsPath(){return vs(this.getConfigDir(),"settings.json")}generateHookConfig(e){let r=`node ${e}/hooks/pretooluse.mjs`;return{PreToolUse:["Bash","WebFetch","Read","Grep","Task","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"].map(s=>({matcher:s,hooks:[{type:"command",command:r}]})),PostToolUse:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/posttooluse.mjs`}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/precompact.mjs`}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/userpromptsubmit.mjs`}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:`node ${e}/hooks/sessionstart.mjs`}]}]}}readSettings(){try{let e=ga(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){i_(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,tr.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,tr.SESSION_START);return r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"No SessionStart hooks found",fix:a?void 0:"context-mode upgrade"}),r}readPluginHooks(e){let r=[vs(e,"hooks","hooks.json"),vs(e,".claude-plugin","hooks","hooks.json")];for(let n of r)try{let s=ga(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=>Po(i,n)))return!0;let o=r?.[n];return!!(o&&o.length>0&&o.some(i=>Po(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=vs(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(ga(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(),We(),ya(a_(),".claude"),ya(a_(),".config","claude")]));for(let r of e){let n=ya(r,"plugins","cache","context-mode","context-mode");try{let o=MT(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(!s_(m))return!0;let f=m.hooks??[];return f.every(h=>!h.command||!$l(h.command))?!0:f.every(h=>{let g=h.command?$l(h.command):null;return g?DT(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&&n_.every(c=>this.checkHookType(void 0,o,c))){let c=Object.values(xs),u=d=>d!=null&&(c.some(l=>d.includes(l))||d.includes("context-mode hook"));for(let d of Object.keys(n)){let l=n[d];if(!Array.isArray(l))continue;let m=0;for(let p of l){let h=p,g=h.hooks??[],y=g.length;h.hooks=g.filter(_=>!u(_.command)),m+=y-h.hooks.length}let f=l.filter(p=>{let h=p.hooks;return Array.isArray(h)&&h.length>0});(m>0||f.length!==l.length)&&(n[d]=f,m>0&&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=[tr.PRE_TOOL_USE,tr.SESSION_START];for(let a of i){let c=El(a,e);if(a===tr.PRE_TOOL_USE){let u={matcher:r_,hooks:[{type:"command",command:c}]},d=n.PreToolUse;if(d&&Array.isArray(d)){let l=d.findIndex(m=>Po(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=>Po(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(xs)){let s=ya(e,"hooks",n);try{zT(s,FT.R_OK),jT(s,493),r.push(s)}catch{}}return r}updatePluginRegistry(e,r){try{let n=vs(this.getConfigDir(),"plugins","installed_plugins.json"),s=JSON.parse(ga(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();i_(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 bn(t,e){let r=Cl[t];return e&&r?Fe(`${e}/hooks/${r}`):`context-mode hook gemini-cli ${t.toLowerCase()}`}var $e,Cl,kU,wU,c_=v(()=>{"use strict";Gr();$e={BEFORE_AGENT:"BeforeAgent",BEFORE_TOOL:"BeforeTool",AFTER_TOOL:"AfterTool",PRE_COMPRESS:"PreCompress",SESSION_START:"SessionStart"},Cl={[$e.BEFORE_AGENT]:"beforeagent.mjs",[$e.BEFORE_TOOL]:"beforetool.mjs",[$e.AFTER_TOOL]:"aftertool.mjs",[$e.PRE_COMPRESS]:"precompress.mjs",[$e.SESSION_START]:"sessionstart.mjs"},kU=[$e.BEFORE_TOOL,$e.SESSION_START],wU=[$e.AFTER_TOOL,$e.PRE_COMPRESS]});var l_={};Le(l_,{GeminiCLIAdapter:()=>Il});import{readFileSync as Ol,writeFileSync as u_,mkdirSync as UT,accessSync as HT,chmodSync as ZT,constants as BT}from"node:fs";import{resolve as Ro,join as qT}from"node:path";import{homedir as _a}from"node:os";var Il,d_=v(()=>{"use strict";Tt();c_();Il=class extends Se{constructor(){super([".gemini"])}name="Gemini CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{decision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{tool_input:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}};if(e.decision==="ask")return{decision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{decision:"deny",reason:e.updatedOutput};if(e.additionalContext)return{hookSpecificOutput:{additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Ro(_a(),".gemini","settings.json")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{[$e.BEFORE_AGENT]:[{matcher:"",hooks:[{type:"command",command:bn($e.BEFORE_AGENT,e)}]}],[$e.BEFORE_TOOL]:[{matcher:"run_shell_command|read_file|read_many_files|grep_search|search_file_content|web_fetch|activate_skill|mcp__plugin_context-mode",hooks:[{type:"command",command:bn($e.BEFORE_TOOL,e)}]}],[$e.AFTER_TOOL]:[{matcher:"",hooks:[{type:"command",command:bn($e.AFTER_TOOL,e)}]}],[$e.PRE_COMPRESS]:[{matcher:"",hooks:[{type:"command",command:bn($e.PRE_COMPRESS,e)}]}],[$e.SESSION_START]:[{matcher:"",hooks:[{type:"command",command:bn($e.SESSION_START,e)}]}]}}readSettings(){try{let e=Ol(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=Ro(_a(),".gemini");UT(r,{recursive:!0}),u_(this.getSettingsPath(),JSON.stringify(e,null,2)+`
6
+ `,"utf-8")}validateHooks(e){let r=[],n=this.readSettings();if(!n)return r.push({check:"BeforeTool hook",status:"fail",message:"Could not read ~/.gemini/settings.json",fix:"context-mode upgrade"}),r;let s=n.hooks,o=s?.[$e.BEFORE_TOOL];if(o&&o.length>0){let a=o.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"BeforeTool hook",status:a?"pass":"fail",message:a?"BeforeTool hook configured":"BeforeTool exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"BeforeTool hook",status:"fail",message:"No BeforeTool hooks found",fix:"context-mode upgrade"});let i=s?.[$e.SESSION_START];if(i&&i.length>0){let a=i.some(c=>c.hooks?.some(u=>u.command?.includes("context-mode")));r.push({check:"SessionStart hook",status:a?"pass":"fail",message:a?"SessionStart hook configured":"SessionStart exists but does not point to context-mode",fix:a?void 0:"context-mode upgrade"})}else r.push({check:"SessionStart hook",status:"fail",message:"No SessionStart hooks found",fix:"context-mode upgrade"});return r}checkPluginRegistration(){let e=this.readSettings();if(!e)return{check:"Plugin registration",status:"warn",message:"Could not read ~/.gemini/settings.json"};let r=e.extensions;return r&&(Array.isArray(r)?r.some(s=>typeof s=="string"&&s.includes("context-mode")):Object.keys(r).some(s=>s.includes("context-mode")))?{check:"Plugin registration",status:"pass",message:"context-mode found in extensions"}:{check:"Plugin registration",status:"warn",message:"context-mode not found in extensions (might be using standalone MCP mode)"}}getInstalledVersion(){try{let e=Ro(_a(),".gemini","extensions","context-mode","package.json"),r=JSON.parse(Ol(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}return"not installed"}configureAllHooks(e){let r=this.readSettings()??{},n=r.hooks??{},s=[],o=[{name:$e.BEFORE_AGENT},{name:$e.BEFORE_TOOL},{name:$e.SESSION_START}];for(let i of o){let c={matcher:"",hooks:[{type:"command",command:bn(i.name,e)}]},u=n[i.name];if(u&&Array.isArray(u)){let d=u.findIndex(l=>l.hooks?.some(f=>f.command?.includes("context-mode")));d>=0?(u[d]=c,s.push(`Updated existing ${i.name} hook entry`)):(u.push(c),s.push(`Added ${i.name} hook entry`)),n[i.name]=u}else n[i.name]=[c],s.push(`Created ${i.name} hooks section`)}return r.hooks=n,this.writeSettings(r),s}setHookPermissions(e){let r=[],n=qT(e,"hooks","gemini-cli");for(let s of Object.values(Cl)){let o=Ro(n,s);try{HT(o,BT.R_OK),ZT(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){try{let n=Ro(_a(),".gemini","extensions","context-mode","package.json"),s=JSON.parse(Ol(n,"utf-8"));s.version=r,s.installPath=e,s.lastUpdated=new Date().toISOString(),u_(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 Sn,OU,IU,p_=v(()=>{"use strict";Sn={BEFORE:"tool.execute.before",AFTER:"tool.execute.after",COMPACTING:"experimental.session.compacting"},OU=[Sn.BEFORE,Sn.AFTER],IU=[Sn.COMPACTING]});var f_={};Le(f_,{OpenCodeAdapter:()=>Al});import{readFileSync as m_,writeFileSync as WT,mkdirSync as GT,copyFileSync as KT,accessSync as JT,constants as YT}from"node:fs";import{resolve as jt,join as Kr}from"node:path";import{homedir as Jr}from"node:os";function VT(t){return t.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/,(\s*[}\]])/g,"$1")}var Al,h_=v(()=>{"use strict";Tt();p_();Al=class extends Se{get name(){return this.platform==="kilo"?"KiloCode":"OpenCode"}paradigm="ts-plugin";settingsPath;capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};platform;constructor(e="opencode"){super([".config",e]),this.platform=e}parsePreToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool??"",toolInput:r.args??{},toolOutput:r.output,isError:void 0,sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:process.env.OPENCODE_PROJECT_DIR||process.cwd(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")throw new Error(e.reason??"Blocked by context-mode hook");if(e.decision==="modify"&&e.updatedInput)return{args:e.updatedInput};if(e.decision==="ask")throw new Error(e.reason??"Action requires user confirmation (security policy)")}formatPostToolUseResponse(e){let r={};return e.updatedOutput&&(r.output=e.updatedOutput),e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return this.settingsPath??jt(`${this.platform}.json`)}paths(){return this.platform==="kilo"?[jt("kilo.json"),jt("kilo.jsonc"),jt(".kilo","kilo.json"),jt(".kilo","kilo.jsonc"),jt(".kilocode","kilo.json"),jt(".kilocode","kilo.jsonc"),Kr(Jr(),".config","kilo","kilo.json"),Kr(Jr(),".config","kilo","kilo.jsonc")]:[jt("opencode.json"),jt("opencode.jsonc"),jt(".opencode","opencode.json"),jt(".opencode","opencode.jsonc"),Kr(Jr(),".config","opencode","opencode.json"),Kr(Jr(),".config","opencode","opencode.jsonc")]}getSessionDir(){let e=Kr(this.getConfigDir(),"context-mode","sessions");return GT(e,{recursive:!0}),e}getConfigDir(e){let r;return process.platform==="win32"?r=process.env.APPDATA||Kr(Jr(),"AppData","Roaming"):r=process.env.XDG_CONFIG_HOME||Kr(Jr(),".config"),Kr(r,this.platform)}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{[Sn.BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Sn.AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[Sn.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(Jr()))),n=null,s;for(let o of e)try{let i=m_(o,"utf-8"),a=o.endsWith(".jsonc")?VT(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){WT(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=jt(Jr(),".cache",this.platform,"node_modules","context-mode","package.json"),r=JSON.parse(m_(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{JT(this.settingsPath,YT.R_OK);let r=this.settingsPath+".bak";return KT(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 kn,LU,FU,g_=v(()=>{"use strict";kn={TOOL_CALL_BEFORE:"tool_call:before",TOOL_CALL_AFTER:"tool_call:after",COMMAND_NEW:"command:new",COMMAND_RESET:"command:reset",COMMAND_STOP:"command:stop"},LU=[kn.TOOL_CALL_BEFORE,kn.TOOL_CALL_AFTER],FU=[kn.COMMAND_NEW]});var y_={};Le(y_,{OpenClawAdapter:()=>jl});import{readFileSync as Nl,writeFileSync as XT,copyFileSync as QT,accessSync as eP,constants as tP}from"node:fs";import{resolve as Pr,join as Dl}from"node:path";import{homedir as Ml}from"node:os";var jl,__=v(()=>{"use strict";Tt();g_();jl=class extends Se{constructor(){super([".openclaw"])}name="OpenClaw";paradigm="ts-plugin";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.toolName??r.tool_name??"",toolInput:r.params??r.tool_input??{},toolOutput:r.output??r.tool_output,isError:r.isError??r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{block:!0,blockReason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{params:e.updatedInput};if(e.decision==="ask")return{block:!0,blockReason:e.reason??"Action requires user confirmation (security policy)"};e.decision==="context"&&e.additionalContext}formatPostToolUseResponse(e){let r={};return e.additionalContext&&(r.additionalContext=e.additionalContext),Object.keys(r).length>0?r:void 0}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return Pr("openclaw.json")}getConfigDir(e){return Pr(e??process.cwd())}getInstructionFiles(){return["AGENTS.md"]}getMemoryDir(){return Dl(this.getConfigDir(),"memory")}generateHookConfig(e){return{[kn.TOOL_CALL_BEFORE]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[kn.TOOL_CALL_AFTER]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}],[kn.COMMAND_NEW]:[{matcher:"",hooks:[{type:"plugin",command:"context-mode"}]}]}}readSettings(){let e=[Pr("openclaw.json"),Pr(".openclaw","openclaw.json"),Dl(Ml(),".openclaw","openclaw.json")];for(let r of e)try{let n=Nl(r,"utf-8");return JSON.parse(n)}catch{continue}return null}writeSettings(e){let r=Pr("openclaw.json");XT(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=Pr(Ml(),".openclaw","extensions","context-mode","package.json"),r=JSON.parse(Nl(e,"utf-8"));if(typeof r.version=="string")return r.version}catch{}try{let e=Pr("node_modules","context-mode","package.json"),r=JSON.parse(Nl(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=[Pr("openclaw.json"),Pr(".openclaw","openclaw.json"),Dl(Ml(),".openclaw","openclaw.json")];for(let r of e)try{eP(r,tP.R_OK);let n=r+".bak";return QT(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 x_}from"node:os";import{resolve as zl}from"node:path";function xa(){let t=process.env.CODEX_HOME;return t?t.startsWith("~")?zl(x_(),t.replace(/^~[/\\]?/,"")):zl(t):zl(x_(),".codex")}var Ll=v(()=>{"use strict"});var k_={};Le(k_,{CodexAdapter:()=>Hl});import{readFileSync as bs,writeFileSync as v_,accessSync as rP,copyFileSync as nP,constants as sP,mkdirSync as Fl}from"node:fs";import{resolve as oP,dirname as Ul,join as va}from"node:path";import{fileURLToPath as iP}from"node:url";function b_(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 S_(t){let e=b_(t,"features");return e!==null&&/^\s*hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function uP(t){let e=b_(t,"features");return e!==null&&/^\s*codex_hooks\s*=\s*true\s*(?:#.*)?$/mi.test(e)}function lP(t){if(S_(t))return{text:t,changed:!1};let e=t.includes(`\r
11
+ `)?`\r
12
+ `:`
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 aP,wn,cP,Hl,w_=v(()=>{"use strict";Tt();Ll();aP="local_shell|shell|shell_command|exec_command|container.exec|functions\\.exec_command|Bash|Shell|apply_patch|functions\\.apply_patch|Edit|Write|grep_files|ctx_execute|ctx_execute_file|ctx_batch_execute|ctx_fetch_and_index|ctx_search|ctx_index|mcp__.*__ctx_execute|mcp__.*__ctx_execute_file|mcp__.*__ctx_batch_execute|mcp__.*__ctx_fetch_and_index|mcp__.*__ctx_search|mcp__.*__ctx_index",wn={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"},cP={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"]};Hl=class extends Se{constructor(){super([".codex"])}name="Codex CLI";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_response,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:e.reason??"Blocked by context-mode hook"}}:e.decision==="context"&&e.additionalContext?{}:{}}formatPostToolUseResponse(e){return e.additionalContext?{hookSpecificOutput:{hookEventName:"PostToolUse",additionalContext:e.additionalContext}}:{}}formatPreCompactResponse(e){return{}}formatSessionStartResponse(e){return e.context?{hookSpecificOutput:{hookEventName:"SessionStart",additionalContext:e.context}}:{}}getConfigDir(e){return xa()}getSettingsPath(){return va(this.getConfigDir(),"config.toml")}getSessionDir(){let e=va(this.getConfigDir(),"context-mode","sessions");return Fl(e,{recursive:!0}),e}getInstructionFiles(){return["AGENTS.md","AGENTS.override.md"]}getMemoryDir(){return va(this.getConfigDir(),"memories")}generateHookConfig(e){return{PreToolUse:[{matcher:aP,hooks:[{type:"command",command:wn.PreToolUse}]}],PostToolUse:[{matcher:"",hooks:[{type:"command",command:wn.PostToolUse}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:wn.SessionStart}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:wn.PreCompact}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:wn.UserPromptSubmit}]}],Stop:[{matcher:"",hooks:[{type:"command",command:wn.Stop}]}]}}readSettings(){try{return{_raw_toml:bs(this.getSettingsPath(),"utf-8")}}catch{return null}}writeSettings(e){}validateHooks(e){let r=[];try{let o=bs(this.getSettingsPath(),"utf-8"),i=S_(o),a=!i&&uP(o);r.push({check:"Codex hooks feature flag",status:i?"pass":"fail",message:i?`[features].hooks enabled in ${this.getSettingsPath()}`:a?`[features].codex_hooks is deprecated; [features].hooks is missing in ${this.getSettingsPath()}`:`[features].hooks missing from ${this.getSettingsPath()}`,...i?{}:{fix:"context-mode upgrade"}})}catch{r.push({check:"Codex hooks feature flag",status:"warn",message:`Could not read ${this.getSettingsPath()}`,fix:"context-mode upgrade"})}let n=this.readHooksConfig();if(!n.ok)return n.reason==="missing"?r.concat([{check:"Hooks config",status:"fail",message:`No readable ${this.getHooksPath()} found`,fix:"Copy configs/codex/hooks.json to hooks.json or run context-mode upgrade"}]):n.reason==="invalid_json"?r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is not valid JSON: ${n.error}`,fix:"Repair hooks.json so it contains valid JSON, then rerun context-mode upgrade if needed"}]):r.concat([{check:"Hooks config",status:"fail",message:`Could not read ${this.getHooksPath()}: ${n.error}`,fix:"Check permissions and file accessibility for hooks.json, then rerun context-mode upgrade if needed"}]);if(!n.config.hooks)return r.concat([{check:"Hooks config",status:"fail",message:`${this.getHooksPath()} is missing the top-level hooks object`,fix:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}]);let s=this.generateHookConfig("");return r.concat(Object.entries(s).map(([o,i])=>{let a=n.config.hooks?.[o],c=i[0],u=Array.isArray(a)&&a.some(l=>this.isExpectedHookEntry(o,l,c)),d=o==="PreCompact"?"warn":"fail";return{check:`${o} hook`,status:u?"pass":d,message:u?`${o} hook configured in ${this.getHooksPath()}`:o==="PreCompact"?`${o} hook missing or not pointing to context-mode; compaction snapshots require a Codex build that emits PreCompact`:`${o} hook missing or not pointing to context-mode`,fix:u?void 0:`Update ${this.getHooksPath()} to match configs/codex/hooks.json`}}))}checkPluginRegistration(){try{let e=bs(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=bs(a,"utf-8")}catch{c=""}let u=lP(c);if(u.changed){let d=u.text.includes(`\r
15
+ `)?`\r
16
+ `:`
17
+ `,l=u.text.endsWith(`
18
+ `)?u.text:`${u.text}${d}`;Fl(Ul(a),{recursive:!0}),v_(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{rP(r,sP.R_OK);let n=this.backupFile(r);e??=n}catch{continue}return e}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=oP(Ul(iP(import.meta.url)),"..","..","..","configs","codex","AGENTS.md");try{return bs(e,"utf-8")}catch{return`# context-mode
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 va(this.getConfigDir(),"hooks.json")}backupFile(e,r=""){let n=r?`${e}${r}-${new Date().toISOString().replace(/[:.]/g,"-")}.bak`:`${e}.bak`;return nP(e,n),n}readHooksConfig(){let e=this.getHooksPath();try{return{ok:!0,config:JSON.parse(bs(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();Fl(Ul(r),{recursive:!0}),v_(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(wn[e]??""),o=cP[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 E_,writeFileSync as dP,mkdirSync as pP,accessSync as mP,chmodSync as fP,constants as hP}from"node:fs";import{resolve as ba,join as gP}from"node:path";var Ss,Zl=v(()=>{"use strict";Tt();Ss=class extends Se{paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!0,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!0,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output,isError:r.is_error,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parsePreCompactInput(e){let r=e;return{sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(),raw:e}}formatPreToolUseResponse(e){if(e.decision==="deny")return{permissionDecision:"deny",reason:e.reason??"Blocked by context-mode hook"};if(e.decision==="modify"&&e.updatedInput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,updatedInput:e.updatedInput}};if(e.decision==="context"&&e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.PRE_TOOL_USE,additionalContext:e.additionalContext}};if(e.decision==="ask")return{permissionDecision:"deny",reason:e.reason??"Action requires user confirmation (security policy)"}}formatPostToolUseResponse(e){if(e.updatedOutput)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,decision:"block",reason:e.updatedOutput}};if(e.additionalContext)return{hookSpecificOutput:{hookEventName:this.hookModule.HOOK_TYPES.POST_TOOL_USE,additionalContext:e.additionalContext}}}formatPreCompactResponse(e){return e.context??""}formatSessionStartResponse(e){return e.context??""}getSettingsPath(){return ba(".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=E_(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{}try{let e=E_(ba(".claude","settings.json"),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();pP(ba(".github","hooks"),{recursive:!0}),dP(r,JSON.stringify(e,null,2)+`
22
+ `,"utf-8")}configureAllHooks(e){let r=[],n=this.readSettings()??{},s=n.hooks??{},{HOOK_TYPES:o,HOOK_SCRIPTS:i,buildHookCommand:a}=this.hookModule,c=[o.PRE_TOOL_USE,o.POST_TOOL_USE,o.PRE_COMPACT,o.SESSION_START];for(let u of c)i[u]&&(s[u]=[{matcher:"",hooks:[{type:"command",command:a(u,e)}]}],r.push(`Configured ${u} hook`));return n.hooks=s,this.writeSettings(n),r.push(`Wrote hook config to ${this.getSettingsPath()}`),r}setHookPermissions(e){let r=[],n=gP(e,"hooks",this.hookSubdir);for(let s of Object.values(this.hookModule.HOOK_SCRIPTS)){let o=ba(n,s);try{mP(o,hP.R_OK),fP(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}}});function $_(t,e){let r=Bl[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Fe(`${e}/hooks/vscode-copilot/${r}`):`context-mode hook vscode-copilot ${t.toLowerCase()}`}var zt,Bl,iH,aH,T_=v(()=>{"use strict";Gr();zt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart"},Bl={[zt.PRE_TOOL_USE]:"pretooluse.mjs",[zt.POST_TOOL_USE]:"posttooluse.mjs",[zt.PRE_COMPACT]:"precompact.mjs",[zt.SESSION_START]:"sessionstart.mjs"},iH=[zt.PRE_TOOL_USE,zt.SESSION_START],aH=[zt.POST_TOOL_USE,zt.PRE_COMPACT]});var P_={};Le(P_,{VSCodeCopilotAdapter:()=>Wl});import{readFileSync as ql,mkdirSync as yP,accessSync as _P,existsSync as xP,constants as vP}from"node:fs";import{resolve as ks,join as Sa}from"node:path";import{homedir as Vl}from"node:os";var Wl,R_=v(()=>{"use strict";Zl();T_();Wl=class extends Ss{constructor(){super([".vscode"])}name="VS Code Copilot";hookModule={HOOK_TYPES:zt,HOOK_SCRIPTS:Bl,buildHookCommand:$_};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=ks(".github","context-mode","sessions"),r=Sa(Vl(),".vscode","context-mode","sessions"),n=xP(ks(".github"))?e:r;return yP(n,{recursive:!0}),n}getConfigDir(e){return ks(e??process.cwd(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[],n=ks(".github","hooks");try{_P(n,vP.R_OK)}catch{return r.push({check:"Hooks directory",status:"fail",message:".github/hooks/ directory not found",fix:"context-mode upgrade"}),r}let s=ks(n,"context-mode.json");try{let o=ql(s,"utf-8"),a=JSON.parse(o).hooks;a?.[zt.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?.[zt.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=ks(".vscode","mcp.json"),r=ql(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=[Sa(Vl(),".vscode","extensions"),Sa(Vl(),".vscode-insiders","extensions")];for(let r of e)try{let n=ql(Sa(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 C_(t,e){let r=Gl[t];if(!r)throw new Error(`No script defined for hook type: ${t}`);return e?Fe(`${e}/hooks/jetbrains-copilot/${r}`):`context-mode hook jetbrains-copilot ${t.toLowerCase()}`}var Lt,Gl,hH,gH,O_=v(()=>{"use strict";Gr();Lt={PRE_TOOL_USE:"PreToolUse",POST_TOOL_USE:"PostToolUse",PRE_COMPACT:"PreCompact",SESSION_START:"SessionStart",STOP:"Stop",SUBAGENT_START:"SubagentStart",SUBAGENT_STOP:"SubagentStop"},Gl={[Lt.PRE_TOOL_USE]:"pretooluse.mjs",[Lt.POST_TOOL_USE]:"posttooluse.mjs",[Lt.PRE_COMPACT]:"precompact.mjs",[Lt.SESSION_START]:"sessionstart.mjs"},hH=[Lt.PRE_TOOL_USE,Lt.SESSION_START],gH=[Lt.POST_TOOL_USE,Lt.PRE_COMPACT]});var I_={};Le(I_,{JetBrainsCopilotAdapter:()=>Kl});import{readFileSync as bP}from"node:fs";import{resolve as SP}from"node:path";var Kl,A_=v(()=>{"use strict";Zl();O_();Kl=class extends Ss{constructor(){super([".config","JetBrains"])}name="JetBrains Copilot";hookModule={HOOK_TYPES:Lt,HOOK_SCRIPTS:Gl,buildHookCommand:C_};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 SP(e??this.getProjectDir(),".github")}getInstructionFiles(){return["copilot-instructions.md"]}validateHooks(e){let r=[];try{let n=bP(this.getSettingsPath(),"utf-8"),o=JSON.parse(n).hooks;o?.[Lt.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?.[Lt.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 Co(t,e){let r=Jl[e],n=Ft(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 Ft(t){return`context-mode hook cursor ${t.toLowerCase()}`}var ye,Jl,kP,Yl,N_,D_,M_=v(()=>{"use strict";ye={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",SESSION_START:"sessionStart",STOP:"stop",AFTER_AGENT_RESPONSE:"afterAgentResponse"},Jl={[ye.PRE_TOOL_USE]:"pretooluse.mjs",[ye.POST_TOOL_USE]:"posttooluse.mjs",[ye.SESSION_START]:"sessionstart.mjs",[ye.STOP]:"stop.mjs",[ye.AFTER_AGENT_RESPONSE]:"afteragentresponse.mjs"},kP=["Shell","Read","Grep","WebFetch","mcp_web_fetch","mcp_fetch_tool","Task","MCP:ctx_execute","MCP:ctx_execute_file","MCP:ctx_batch_execute"],Yl=kP.join("|"),N_=[ye.PRE_TOOL_USE],D_=[ye.POST_TOOL_USE]});var U_={};Le(U_,{CursorAdapter:()=>Xl});import{readFileSync as ka,writeFileSync as wP,mkdirSync as EP,accessSync as j_,chmodSync as $P,constants as z_,existsSync as L_,readdirSync as TP}from"node:fs";import{execSync as PP}from"node:child_process";import{resolve as En,join as $n}from"node:path";import{homedir as wa}from"node:os";var F_,Xl,H_=v(()=>{"use strict";Tt();Wr();M_();F_="/Library/Application Support/Cursor/hooks.json",Xl=class extends Se{constructor(){super([".cursor"])}name="Cursor";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!0,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parsePostToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:r.tool_output??r.error_message,isError:!!r.error_message,sessionId:this.extractSessionId(r),projectDir:this.getProjectDir(r),raw:e}}parseSessionStartInput(e){let r=e,n=r.source??r.trigger??"startup",s;switch(n){case"compact":s="compact";break;case"resume":s="resume";break;case"clear":s="clear";break;default:s="startup"}return{sessionId:this.extractSessionId(r),source:s,projectDir:this.getProjectDir(r),raw:e}}formatPreToolUseResponse(e){return e.decision==="deny"?{permission:"deny",user_message:e.reason??"Blocked by context-mode hook"}:e.decision==="modify"&&e.updatedInput?{updated_input:e.updatedInput}:e.decision==="context"&&e.additionalContext?{agent_message:e.additionalContext}:e.decision==="ask"?{permission:"ask",user_message:e.reason??"Action requires user confirmation (security policy)"}:{agent_message:""}}formatPostToolUseResponse(e){return{additional_context:e.additionalContext??""}}formatSessionStartResponse(e){return{additional_context:e.context??""}}parseStopInput(e){let r=e;return{sessionId:r.conversation_id??`pid-${process.ppid}`,status:r.status??"completed",loopCount:r.loop_count??0,generationId:r.generation_id,transcriptPath:r.transcript_path??void 0}}formatStopResponse(e){return e.followupMessage?{followup_message:e.followupMessage}:{}}parseAfterAgentResponseInput(e){return{text:e.text??""}}getSettingsPath(){return En(".cursor","hooks.json")}getConfigDir(e){return En(e??process.cwd(),".cursor")}getInstructionFiles(){return["context-mode.mdc"]}generateHookConfig(e){return{[ye.PRE_TOOL_USE]:[{type:"command",command:Ft(ye.PRE_TOOL_USE),matcher:Yl,loop_limit:null,failClosed:!1}],[ye.POST_TOOL_USE]:[{type:"command",command:Ft(ye.POST_TOOL_USE),loop_limit:null,failClosed:!1}],[ye.SESSION_START]:[{type:"command",command:Ft(ye.SESSION_START),loop_limit:null,failClosed:!1}],[ye.STOP]:[{type:"command",command:Ft(ye.STOP),loop_limit:null,failClosed:!1}],[ye.AFTER_AGENT_RESPONSE]:[{type:"command",command:Ft(ye.AFTER_AGENT_RESPONSE),loop_limit:null,failClosed:!1}]}}readSettings(){for(let e of this.getCandidateHookConfigPaths())try{let r=ka(e,"utf-8");return JSON.parse(r)}catch{continue}return null}writeSettings(e){let r=this.getSettingsPath();EP(En(".cursor"),{recursive:!0}),wP(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 N_){let a=o[i],c=Array.isArray(a)&&a.some(u=>Co(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 D_){let a=o[i],c=Array.isArray(a)&&a.some(u=>Co(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`})}}L_(F_)&&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=>Co(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=[$n(wa(),".cursor","plugins","local"),$n(wa(),".cursor","plugins","cache")],r=[];for(let n of e){try{j_(n,z_.F_OK)}catch{continue}let s=[];try{s=TP(n)}catch{continue}for(let o of s){let i=$n(n,o,".cursor-plugin","plugin.json");try{let a=ka(i,"utf-8");JSON.parse(a)?.name==="context-mode"&&r.push(i)}catch{continue}}}return r}checkPluginRegistration(){let e=[En(".cursor","mcp.json"),$n(wa(),".cursor","mcp.json")];for(let n of e)try{let s=ka(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 PP("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,ye.PRE_TOOL_USE,{type:"command",command:Ft(ye.PRE_TOOL_USE),matcher:Yl,loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,ye.POST_TOOL_USE,{type:"command",command:Ft(ye.POST_TOOL_USE),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,ye.SESSION_START,{type:"command",command:Ft(ye.SESSION_START),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,ye.STOP,{type:"command",command:Ft(ye.STOP),loop_limit:null,failClosed:!1},s),this.upsertHookEntry(n,ye.AFTER_AGENT_RESPONSE,{type:"command",command:Ft(ye.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=$n(e,"hooks","cursor");for(let s of Object.values(Jl)){let o=En(n,s);try{j_(o,z_.R_OK),$P(o,493),r.push(o)}catch{}}return r}updatePluginRegistry(e,r){}getCandidateHookConfigPaths(){let e=[this.getSettingsPath(),$n(wa(),".cursor","hooks.json")];return process.platform==="darwin"&&e.push(F_),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=ka(e,"utf-8"),n=JSON.parse(r);if(n&&typeof n=="object")return{path:e,config:n}}catch{continue}return null}hasClaudeCompatibilityHooks(){return[En(".claude","settings.json"),En(".claude","settings.local.json"),$n(We(),"settings.json")].some(r=>L_(r))}upsertHookEntry(e,r,n,s){let o=e[r],i=Array.isArray(o)?[...o]:[],a=i.findIndex(c=>Co(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 B_={};Le(B_,{AntigravityAdapter:()=>ed});import{readFileSync as Ea,writeFileSync as RP,mkdirSync as CP}from"node:fs";import{resolve as $a,dirname as Z_}from"node:path";import{fileURLToPath as OP}from"node:url";import{homedir as Ql}from"node:os";var ed,q_=v(()=>{"use strict";Tt();ed=class extends Se{constructor(){super([".gemini"])}name="Antigravity";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePostToolUseInput(e){throw new Error("Antigravity does not support hooks")}parsePreCompactInput(e){throw new Error("Antigravity does not support hooks")}parseSessionStartInput(e){throw new Error("Antigravity does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return $a(Ql(),".gemini","antigravity","mcp_config.json")}getConfigDir(e){return $a(Ql(),".gemini","antigravity")}getInstructionFiles(){return["GEMINI.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=Ea(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();CP(Z_(r),{recursive:!0}),RP(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=Ea(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=$a(Ql(),".gemini","extensions","context-mode","package.json");return JSON.parse(Ea(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){let e=$a(Z_(OP(import.meta.url)),"..","..","..","configs","antigravity","GEMINI.md");try{return Ea(e,"utf-8")}catch{return`# context-mode
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 Ta(t,e){let r=V_[e];return r&&(t.command?.includes(r)||t.command?.includes("context-mode hook kiro"))||!1}function ws(t,e){let r=V_[t];return e&&r?Fe(`${e}/hooks/kiro/${r}`):`context-mode hook kiro ${t.toLowerCase()}`}var Me,V_,IP,td,jH,zH,W_=v(()=>{"use strict";Gr();Me={PRE_TOOL_USE:"preToolUse",POST_TOOL_USE:"postToolUse",AGENT_SPAWN:"agentSpawn",USER_PROMPT_SUBMIT:"userPromptSubmit"},V_={[Me.PRE_TOOL_USE]:"pretooluse.mjs",[Me.POST_TOOL_USE]:"posttooluse.mjs",[Me.USER_PROMPT_SUBMIT]:"userpromptsubmit.mjs",[Me.AGENT_SPAWN]:"agentspawn.mjs"},IP=["execute_bash","fs_read","@context-mode/ctx_execute","@context-mode/ctx_execute_file","@context-mode/ctx_batch_execute"],td=IP.join("|"),jH=[Me.PRE_TOOL_USE,Me.AGENT_SPAWN],zH=[Me.POST_TOOL_USE,Me.USER_PROMPT_SUBMIT]});var Y_={};Le(Y_,{KiroAdapter:()=>rd});import{readFileSync as Es,writeFileSync as G_,mkdirSync as K_}from"node:fs";import{resolve as Tn,dirname as J_}from"node:path";import{fileURLToPath as AP}from"node:url";import{homedir as Pa}from"node:os";var rd,X_=v(()=>{"use strict";Tt();W_();rd=class extends Se{constructor(){super([".kiro"])}name="Kiro";paradigm="json-stdio";capabilities={preToolUse:!0,postToolUse:!0,preCompact:!1,sessionStart:!0,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!0};parsePreToolUseInput(e){let r=e;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePostToolUseInput(e){let r=e,n=r.tool_response;return{toolName:r.tool_name??"",toolInput:r.tool_input??{},toolOutput:typeof n=="string"?n:JSON.stringify(n??""),sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}parsePreCompactInput(e){throw new Error("Kiro does not support PreCompact hooks")}parseSessionStartInput(e){let r=e??{};return{source:r.source??"startup",sessionId:`pid-${process.ppid}`,projectDir:r.cwd??process.cwd(),raw:e}}formatPreToolUseResponse(e){switch(e.decision){case"deny":return{exitCode:2,stderr:e.reason??"Blocked by context-mode"};case"context":return{exitCode:0,stdout:e.additionalContext??""};default:return}}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){if(e?.context)return{hookSpecificOutput:{hookEventName:"agentSpawn",additionalContext:e.context}}}getSettingsPath(){return Tn(Pa(),".kiro","settings","mcp.json")}getConfigDir(e){return Tn(e??process.cwd(),".kiro")}getInstructionFiles(){return["KIRO.md"]}generateHookConfig(e){return{[Me.PRE_TOOL_USE]:[{matcher:td,hooks:[{type:"command",command:ws(Me.PRE_TOOL_USE,e)}]}],[Me.POST_TOOL_USE]:[{matcher:"*",hooks:[{type:"command",command:ws(Me.POST_TOOL_USE,e)}]}],[Me.AGENT_SPAWN]:[{matcher:"*",hooks:[{type:"command",command:ws(Me.AGENT_SPAWN,e)}]}],[Me.USER_PROMPT_SUBMIT]:[{matcher:"*",hooks:[{type:"command",command:ws(Me.USER_PROMPT_SUBMIT,e)}]}]}}readSettings(){try{let e=Es(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();K_(J_(r),{recursive:!0}),G_(r,JSON.stringify(e,null,2),"utf-8")}validateHooks(e){let r=[],n=Tn(Pa(),".kiro","agents","default.json");try{let o=JSON.parse(Es(n,"utf-8")).hooks??{};for(let i of[Me.PRE_TOOL_USE]){let c=(o[i]??[]).some(u=>Ta(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"fail",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured`,...c?{}:{fix:"Run: context-mode upgrade"}})}for(let i of[Me.POST_TOOL_USE]){let c=(o[i]??[]).some(u=>Ta(u,i));r.push({check:`Hook: ${i}`,status:c?"pass":"warn",message:c?`context-mode ${i} hook found`:`context-mode ${i} hook not configured (optional)`})}}catch{r.push({check:"Hook configuration",status:"warn",message:"Could not read ~/.kiro/agents/default.json",fix:"Run: context-mode upgrade"})}return r}checkPluginRegistration(){try{let e=Es(this.getSettingsPath(),"utf-8");return"context-mode"in(JSON.parse(e)?.mcpServers??{})?{check:"MCP registration",status:"pass",message:"context-mode found in mcpServers config"}:{check:"MCP registration",status:"fail",message:"context-mode not found in mcpServers",fix:"Add context-mode to mcpServers in ~/.kiro/settings/mcp.json"}}catch{return{check:"MCP registration",status:"warn",message:"Could not read ~/.kiro/settings/mcp.json"}}}getInstalledVersion(){try{let e=Tn(Pa(),".kiro","extensions","context-mode","package.json");return JSON.parse(Es(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){let r=[],n=Tn(Pa(),".kiro","agents"),s=Tn(n,"default.json");try{K_(n,{recursive:!0});let o={};try{o=JSON.parse(Es(s,"utf-8"))}catch{}let i=o.hooks??{},a=[[Me.PRE_TOOL_USE,td],[Me.POST_TOOL_USE,"*"],[Me.AGENT_SPAWN,"*"],[Me.USER_PROMPT_SUBMIT,"*"]];for(let[c,u]of a){let d=i[c]??[];d.some(l=>Ta(l,c))||(d.push({matcher:u,command:ws(c,e)}),i[c]=d,r.push(`Added ${c} hook to ${s}`))}o.hooks=i,G_(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=Tn(J_(AP(import.meta.url)),"..","..","..","configs","kiro","KIRO.md");try{return Es(e,"utf-8")}catch{return`# context-mode
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 tx={};Le(tx,{ZedAdapter:()=>sd});import{readFileSync as nd,writeFileSync as NP,mkdirSync as DP}from"node:fs";import{resolve as Q_,dirname as ex}from"node:path";import{fileURLToPath as MP}from"node:url";import{homedir as jP}from"node:os";var sd,rx=v(()=>{"use strict";Tt();sd=class extends Se{constructor(){super([".config","zed"])}name="Zed";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Zed does not support hooks")}parsePostToolUseInput(e){throw new Error("Zed does not support hooks")}parsePreCompactInput(e){throw new Error("Zed does not support hooks")}parseSessionStartInput(e){throw new Error("Zed does not support hooks")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return Q_(jP(),".config","zed","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=nd(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();DP(ex(r),{recursive:!0}),NP(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=nd(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=Q_(ex(MP(import.meta.url)),"..","..","..","configs","zed","AGENTS.md");try{return nd(e,"utf-8")}catch{return`# context-mode
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 ox={};Le(ox,{QwenCodeAdapter:()=>od});import{readFileSync as zP,existsSync as LP}from"node:fs";import{resolve as nx,join as FP}from"node:path";import{homedir as sx}from"node:os";var od,ix=v(()=>{"use strict";wl();Gr();od=class extends _s{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 nx(sx(),".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"].join("|"),hooks:[{type:"command",command:Fe(`${e}/hooks/pretooluse.mjs`)}]}],PostToolUse:[{matcher:"run_shell_command|read_file|write_file|edit|glob|grep_search|todo_write|agent|ask_user_question|mcp__",hooks:[{type:"command",command:Fe(`${e}/hooks/posttooluse.mjs`)}]}],SessionStart:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/sessionstart.mjs`)}]}],PreCompact:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/precompact.mjs`)}]}],UserPromptSubmit:[{matcher:"",hooks:[{type:"command",command:Fe(`${e}/hooks/userpromptsubmit.mjs`)}]}]}}readSettings(){try{let e=zP(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let{writeFileSync:r}=Py("node:fs");r(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 h=p.command.match(/"[^"]+"\s+"([^"]+\.mjs)"/),g=p.command.match(/node\s+"?([^"]+\.mjs)"?/),y=h||g;return y?LP(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"].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:Fe(`${e}/hooks/${a}`)}]},d=n[i];if(d&&Array.isArray(d)){let l=d.findIndex(m=>m.hooks?.some(p=>p.command?.includes(a))??!1);l>=0?(d[l]=u,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:nx(FP(sx(),".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 ax={};Le(ax,{OMPAdapter:()=>cd});import{readFileSync as id,writeFileSync as UP,mkdirSync as HP}from"node:fs";import{resolve as ad,dirname as ZP}from"node:path";import{homedir as BP}from"node:os";var cd,cx=v(()=>{"use strict";Tt();cd=class extends Se{constructor(){super([".omp"])}name="OMP";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePostToolUseInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parsePreCompactInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}parseSessionStartInput(e){throw new Error("OMP hooks not wired by this adapter (MCP-only delivery)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getAgentDir(){return process.env.PI_CODING_AGENT_DIR??ad(BP(),".omp","agent")}getSettingsPath(){return ad(this.getAgentDir(),"mcp.json")}getConfigDir(e){return this.getAgentDir()}getInstructionFiles(){return["SYSTEM.md","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();HP(ZP(r),{recursive:!0}),UP(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=id(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=ad(this.getAgentDir(),"extensions","context-mode","package.json");return JSON.parse(id(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
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 ux={};Le(ux,{PiAdapter:()=>pd});import{readFileSync as ud,writeFileSync as qP,mkdirSync as VP}from"node:fs";import{resolve as ld,dirname as WP}from"node:path";import{homedir as dd}from"node:os";var pd,lx=v(()=>{"use strict";Tt();pd=class extends Se{constructor(){super([".pi"])}name="Pi";paradigm="mcp-only";capabilities={preToolUse:!1,postToolUse:!1,preCompact:!1,sessionStart:!1,canModifyArgs:!1,canModifyOutput:!1,canInjectSessionContext:!1};parsePreToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePostToolUseInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parsePreCompactInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}parseSessionStartInput(e){throw new Error("Pi does not support JSON-stdio hooks (wired via extension.ts)")}formatPreToolUseResponse(e){}formatPostToolUseResponse(e){}formatPreCompactResponse(e){}formatSessionStartResponse(e){}getSettingsPath(){return ld(dd(),".pi","settings.json")}getInstructionFiles(){return["AGENTS.md"]}generateHookConfig(e){return{}}readSettings(){try{let e=ud(this.getSettingsPath(),"utf-8");return JSON.parse(e)}catch{return null}}writeSettings(e){let r=this.getSettingsPath();VP(WP(r),{recursive:!0}),qP(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=ld(dd(),".pi","extensions","context-mode","package.json");try{return JSON.parse(ud(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=ld(dd(),".pi","extensions","context-mode","package.json");return JSON.parse(ud(e,"utf-8")).version??"unknown"}catch{return"not installed"}}configureAllHooks(e){return[]}setHookPermissions(e){return[]}updatePluginRegistry(e,r){}getRoutingInstructions(){return`# context-mode
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 fd={};Le(fd,{PLATFORM_ENV_VARS:()=>dx,detectPlatform:()=>gr,getAdapter:()=>Oo,getSessionDirSegments:()=>md});import{existsSync as Pt}from"node:fs";import{resolve as Rt}from"node:path";import{homedir as GP}from"node:os";function md(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 gr(t){if(t?.name){let n=Qy[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 dx)if(s.some(o=>process.env[o]))return{platform:n,confidence:"high",reason:`${s.join(" or ")} env var set`};let r=GP();return Pt(Rt(r,".claude"))?{platform:"claude-code",confidence:"medium",reason:"~/.claude/ directory exists"}:Pt(Rt(r,".gemini"))?{platform:"gemini-cli",confidence:"medium",reason:"~/.gemini/ directory exists"}:Pt(Rt(r,".codex"))?{platform:"codex",confidence:"medium",reason:"~/.codex/ directory exists"}:Pt(Rt(r,".cursor"))?{platform:"cursor",confidence:"medium",reason:"~/.cursor/ directory exists"}:Pt(Rt(r,".kiro"))?{platform:"kiro",confidence:"medium",reason:"~/.kiro/ directory exists"}:Pt(Rt(r,".omp"))?{platform:"omp",confidence:"medium",reason:"~/.omp/ directory exists"}:Pt(Rt(r,".pi"))?{platform:"pi",confidence:"medium",reason:"~/.pi/ directory exists"}:Pt(Rt(r,".qwen"))?{platform:"qwen-code",confidence:"medium",reason:"~/.qwen/ directory exists"}:Pt(Rt(r,".openclaw"))?{platform:"openclaw",confidence:"medium",reason:"~/.openclaw/ directory exists"}:Pt(Rt(r,".config","kilo"))?{platform:"kilo",confidence:"medium",reason:"~/.config/kilo/ directory exists"}:Pt(Rt(r,".config","JetBrains"))?{platform:"jetbrains-copilot",confidence:"medium",reason:"~/.config/JetBrains/ directory exists"}:Pt(Rt(r,".config","opencode"))?{platform:"opencode",confidence:"medium",reason:"~/.config/opencode/ directory exists"}:Pt(Rt(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 Oo(t){let e=t??gr().platform;switch(e){case"claude-code":{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Rl(),Pl));return new r}case"gemini-cli":{let{GeminiCLIAdapter:r}=await Promise.resolve().then(()=>(d_(),l_));return new r}case"kilo":case"opencode":{let{OpenCodeAdapter:r}=await Promise.resolve().then(()=>(h_(),f_));return new r(e)}case"openclaw":{let{OpenClawAdapter:r}=await Promise.resolve().then(()=>(__(),y_));return new r}case"codex":{let{CodexAdapter:r}=await Promise.resolve().then(()=>(w_(),k_));return new r}case"vscode-copilot":{let{VSCodeCopilotAdapter:r}=await Promise.resolve().then(()=>(R_(),P_));return new r}case"jetbrains-copilot":{let{JetBrainsCopilotAdapter:r}=await Promise.resolve().then(()=>(A_(),I_));return new r}case"cursor":{let{CursorAdapter:r}=await Promise.resolve().then(()=>(H_(),U_));return new r}case"antigravity":{let{AntigravityAdapter:r}=await Promise.resolve().then(()=>(q_(),B_));return new r}case"kiro":{let{KiroAdapter:r}=await Promise.resolve().then(()=>(X_(),Y_));return new r}case"zed":{let{ZedAdapter:r}=await Promise.resolve().then(()=>(rx(),tx));return new r}case"qwen-code":{let{QwenCodeAdapter:r}=await Promise.resolve().then(()=>(ix(),ox));return new r}case"omp":{let{OMPAdapter:r}=await Promise.resolve().then(()=>(cx(),ax));return new r}case"pi":{let{PiAdapter:r}=await Promise.resolve().then(()=>(lx(),ux));return new r}default:{let{ClaudeCodeAdapter:r}=await Promise.resolve().then(()=>(Rl(),Pl));return new r}}}var dx,Io=v(()=>{"use strict";e_();dx=[["claude-code",["CLAUDE_PROJECT_DIR","CLAUDE_SESSION_ID"]],["antigravity",["ANTIGRAVITY_CLI_ALIAS"]],["cursor",["CURSOR_TRACE_ID","CURSOR_CLI"]],["kilo",["KILO","KILO_PID"]],["opencode",["OPENCODE","OPENCODE_PID"]],["zed",["ZED_SESSION_ID","ZED_TERM"]],["codex",["CODEX_THREAD_ID","CODEX_CI"]],["gemini-cli",["GEMINI_PROJECT_DIR","GEMINI_CLI"]],["vscode-copilot",["VSCODE_PID","VSCODE_CWD"]],["jetbrains-copilot",["IDEA_INITIAL_DIRECTORY"]],["qwen-code",["QWEN_PROJECT_DIR"]],["omp",["PI_CODING_AGENT_DIR"]],["pi",["PI_PROJECT_DIR"]]]});var ie,hd,M,yr,Ao=v(()=>{(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})})(hd||(hd={}));M=ie.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),yr=t=>{switch(typeof t){case"undefined":return M.undefined;case"string":return M.string;case"number":return Number.isNaN(t)?M.nan:M.number;case"boolean":return M.boolean;case"function":return M.function;case"bigint":return M.bigint;case"symbol":return M.symbol;case"object":return Array.isArray(t)?M.array:t===null?M.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?M.promise:typeof Map<"u"&&t instanceof Map?M.map:typeof Set<"u"&&t instanceof Set?M.set:typeof Date<"u"&&t instanceof Date?M.date:M.object;default:return M.unknown}}});var $,KP,_t,Ra=v(()=>{Ao();$=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"]),KP=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),_t=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()}};_t.create=t=>new _t(t)});var JP,Rr,gd=v(()=>{Ra();Ao();JP=(t,e)=>{let r;switch(t.code){case $.invalid_type:t.received===M.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case $.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,ie.jsonStringifyReplacer)}`;break;case $.unrecognized_keys:r=`Unrecognized key(s) in object: ${ie.joinValues(t.keys,", ")}`;break;case $.invalid_union:r="Invalid input";break;case $.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${ie.joinValues(t.options)}`;break;case $.invalid_enum_value:r=`Invalid enum value. Expected ${ie.joinValues(t.options)}, received '${t.received}'`;break;case $.invalid_arguments:r="Invalid function arguments";break;case $.invalid_return_type:r="Invalid function return type";break;case $.invalid_date:r="Invalid date";break;case $.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 $.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 $.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 $.custom:r="Invalid input";break;case $.invalid_intersection_types:r="Intersection results could not be merged";break;case $.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case $.not_finite:r="Number must be finite";break;default:r=e.defaultError,ie.assertNever(t)}return{message:r}},Rr=JP});function YP(t){px=t}function $s(){return px}var px,Ca=v(()=>{gd();px=Rr});function A(t,e){let r=$s(),n=No({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===Rr?void 0:Rr].filter(s=>!!s)});t.common.issues.push(n)}var No,XP,Ge,W,Pn,nt,Oa,Ia,Yr,Ts,yd=v(()=>{Ca();gd();No=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}},XP=[];Ge=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return W;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let o=await s.key,i=await s.value;n.push({key:o,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:o,value:i}=s;if(o.status==="aborted"||i.status==="aborted")return W;o.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[o.value]=i.value)}return{status:e.value,value:n}}},W=Object.freeze({status:"aborted"}),Pn=t=>({status:"dirty",value:t}),nt=t=>({status:"valid",value:t}),Oa=t=>t.status==="aborted",Ia=t=>t.status==="dirty",Yr=t=>t.status==="valid",Ts=t=>typeof Promise<"u"&&t instanceof Promise});var mx=v(()=>{});var z,fx=v(()=>{(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(z||(z={}))});function X(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 _x(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 hR(t){return new RegExp(`^${_x(t)}$`)}function xx(t){let e=`${yx}T${_x(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 gR(t,e){return!!((e==="v4"||!e)&&cR.test(t)||(e==="v6"||!e)&&lR.test(t))}function yR(t,e){if(!sR.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 _R(t,e){return!!((e==="v4"||!e)&&uR.test(t)||(e==="v6"||!e)&&dR.test(t))}function xR(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 Ps(t){if(t instanceof vt){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=xt.create(Ps(n))}return new vt({...t._def,shape:()=>e})}else return t instanceof Ir?new Ir({...t._def,type:Ps(t.element)}):t instanceof xt?xt.create(Ps(t.unwrap())):t instanceof xr?xr.create(Ps(t.unwrap())):t instanceof _r?_r.create(t.items.map(e=>Ps(e))):t}function xd(t,e){let r=yr(t),n=yr(e);if(t===e)return{valid:!0,data:t};if(r===M.object&&n===M.object){let s=ie.objectKeys(e),o=ie.objectKeys(t).filter(a=>s.indexOf(a)!==-1),i={...t,...e};for(let a of o){let c=xd(t[a],e[a]);if(!c.valid)return{valid:!1};i[a]=c.data}return{valid:!0,data:i}}else if(r===M.array&&n===M.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let o=0;o<t.length;o++){let i=t[o],a=e[o],c=xd(i,a);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===M.date&&n===M.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}function vx(t,e){return new Ln({values:t,typeName:P.ZodEnum,...X(e)})}function gx(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function bx(t,e={},r){return t?Qr.create().superRefine((n,s)=>{let o=t(n);if(o instanceof Promise)return o.then(i=>{if(!i){let a=gx(e,n),c=a.fatal??r??!0;s.addIssue({code:"custom",...a,fatal:c})}});if(!o){let i=gx(e,n),a=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:a})}}):Qr.create()}var Ut,hx,ee,QP,eR,tR,rR,nR,sR,oR,iR,aR,_d,cR,uR,lR,dR,pR,mR,yx,fR,Xr,Rn,Cn,On,In,Rs,An,Nn,Qr,Or,rr,Cs,Ir,vt,Dn,Cr,Aa,Mn,_r,Na,Os,Is,Da,jn,zn,Ln,Fn,en,Ht,xt,xr,Un,Hn,As,vR,Do,Mo,Zn,bR,P,SR,Sx,kx,kR,wR,wx,ER,$R,TR,PR,RR,CR,OR,IR,AR,vd,NR,DR,MR,jR,zR,LR,FR,UR,HR,ZR,BR,qR,VR,WR,GR,KR,JR,YR,XR,QR,eC,tC,rC,nC,Ex=v(()=>{Ra();Ca();fx();yd();Ao();Ut=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}},hx=(t,e)=>{if(Yr(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 _t(t.common.issues);return this._error=r,this._error}}};ee=class{get description(){return this._def.description}_getType(e){return yr(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ge,ctx:{common:e.parent.common,data:e.data,parsedType:yr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(Ts(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:yr(e)},s=this._parseSync({data:e,path:n.path,parent:n});return hx(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:yr(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Yr(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=>Yr(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:yr(e)},s=this._parse({data:e,path:n.path,parent:n}),o=await(Ts(s)?s:Promise.resolve(s));return hx(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:$.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 Ht({schema:this,typeName:P.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 xt.create(this,this._def)}nullable(){return xr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ir.create(this)}promise(){return en.create(this,this._def)}or(e){return Dn.create([this,e],this._def)}and(e){return Mn.create(this,e,this._def)}transform(e){return new Ht({...X(this._def),schema:this,typeName:P.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Un({...X(this._def),innerType:this,defaultValue:r,typeName:P.ZodDefault})}brand(){return new Do({typeName:P.ZodBranded,type:this,...X(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new Hn({...X(this._def),innerType:this,catchValue:r,typeName:P.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Mo.create(this,e)}readonly(){return Zn.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},QP=/^c[^\s-]{8,}$/i,eR=/^[0-9a-z]+$/,tR=/^[0-9A-HJKMNP-TV-Z]{26}$/i,rR=/^[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,nR=/^[a-z0-9_-]{21}$/i,sR=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,oR=/^[-+]?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)?)??$/,iR=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aR="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",cR=/^(?:(?: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])$/,uR=/^(?:(?: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])$/,lR=/^(([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]))$/,dR=/^(([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])$/,pR=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,mR=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,yx="((\\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])))",fR=new RegExp(`^${yx}$`);Xr=class t extends ee{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==M.string){let o=this._getOrReturnCtx(e);return A(o,{code:$.invalid_type,expected:M.string,received:o.parsedType}),W}let n=new Ge,s;for(let o of this._def.checks)if(o.kind==="min")e.data.length<o.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:$.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),A(s,{code:$.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?A(s,{code:$.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&A(s,{code:$.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")iR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"email",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")_d||(_d=new RegExp(aR,"u")),_d.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"emoji",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")rR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"uuid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")nR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"nanoid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")QP.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")eR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid2",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")tR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ulid",code:$.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),A(s,{validation:"url",code:$.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),A(s,{validation:"regex",code:$.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),A(s,{code:$.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),A(s,{code:$.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?e.data.endsWith(o.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?xx(o).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?fR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?hR(o).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:$.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?oR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"duration",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?gR(e.data,o.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ip",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?yR(e.data,o.alg)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"jwt",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?_R(e.data,o.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cidr",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?pR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64",code:$.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?mR.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64url",code:$.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:$.invalid_string,...z.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...z.errToObj(e)})}url(e){return this._addCheck({kind:"url",...z.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...z.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...z.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...z.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...z.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...z.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...z.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...z.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...z.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...z.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...z.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...z.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,...z.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,...z.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...z.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...z.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...z.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...z.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...z.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...z.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...z.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...z.errToObj(r)})}nonempty(e){return this.min(1,z.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}};Xr.create=t=>new Xr({checks:[],typeName:P.ZodString,coerce:t?.coerce??!1,...X(t)});Rn=class t extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==M.number){let o=this._getOrReturnCtx(e);return A(o,{code:$.invalid_type,expected:M.number,received:o.parsedType}),W}let n,s=new Ge;for(let o of this._def.checks)o.kind==="int"?ie.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:$.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),A(n,{code:$.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),A(n,{code:$.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),s.dirty()):o.kind==="multipleOf"?xR(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),A(n,{code:$.not_multiple_of,multipleOf:o.value,message:o.message}),s.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),A(n,{code:$.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,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:z.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:z.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:z.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:z.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)}};Rn.create=t=>new Rn({checks:[],typeName:P.ZodNumber,coerce:t?.coerce||!1,...X(t)});Cn=class t extends ee{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==M.bigint)return this._getInvalidInput(e);let n,s=new Ge;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),A(n,{code:$.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),A(n,{code:$.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),A(n,{code:$.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 A(r,{code:$.invalid_type,expected:M.bigint,received:r.parsedType}),W}gte(e,r){return this.setLimit("min",e,!0,z.toString(r))}gt(e,r){return this.setLimit("min",e,!1,z.toString(r))}lte(e,r){return this.setLimit("max",e,!0,z.toString(r))}lt(e,r){return this.setLimit("max",e,!1,z.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:z.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:z.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:z.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:z.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:z.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:z.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}};Cn.create=t=>new Cn({checks:[],typeName:P.ZodBigInt,coerce:t?.coerce??!1,...X(t)});On=class extends ee{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==M.boolean){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.boolean,received:n.parsedType}),W}return nt(e.data)}};On.create=t=>new On({typeName:P.ZodBoolean,coerce:t?.coerce||!1,...X(t)});In=class t extends ee{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==M.date){let o=this._getOrReturnCtx(e);return A(o,{code:$.invalid_type,expected:M.date,received:o.parsedType}),W}if(Number.isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return A(o,{code:$.invalid_date}),W}let n=new Ge,s;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()<o.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:$.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),A(s,{code:$.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:z.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:z.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}};In.create=t=>new In({checks:[],coerce:t?.coerce||!1,typeName:P.ZodDate,...X(t)});Rs=class extends ee{_parse(e){if(this._getType(e)!==M.symbol){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.symbol,received:n.parsedType}),W}return nt(e.data)}};Rs.create=t=>new Rs({typeName:P.ZodSymbol,...X(t)});An=class extends ee{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.undefined,received:n.parsedType}),W}return nt(e.data)}};An.create=t=>new An({typeName:P.ZodUndefined,...X(t)});Nn=class extends ee{_parse(e){if(this._getType(e)!==M.null){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.null,received:n.parsedType}),W}return nt(e.data)}};Nn.create=t=>new Nn({typeName:P.ZodNull,...X(t)});Qr=class extends ee{constructor(){super(...arguments),this._any=!0}_parse(e){return nt(e.data)}};Qr.create=t=>new Qr({typeName:P.ZodAny,...X(t)});Or=class extends ee{constructor(){super(...arguments),this._unknown=!0}_parse(e){return nt(e.data)}};Or.create=t=>new Or({typeName:P.ZodUnknown,...X(t)});rr=class extends ee{_parse(e){let r=this._getOrReturnCtx(e);return A(r,{code:$.invalid_type,expected:M.never,received:r.parsedType}),W}};rr.create=t=>new rr({typeName:P.ZodNever,...X(t)});Cs=class extends ee{_parse(e){if(this._getType(e)!==M.undefined){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.void,received:n.parsedType}),W}return nt(e.data)}};Cs.create=t=>new Cs({typeName:P.ZodVoid,...X(t)});Ir=class t extends ee{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==M.array)return A(r,{code:$.invalid_type,expected:M.array,received:r.parsedType}),W;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,a=r.data.length<s.exactLength.value;(i||a)&&(A(r,{code:i?$.too_big:$.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&&(A(r,{code:$.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&&(A(r,{code:$.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 Ut(r,i,r.path,a)))).then(i=>Ge.mergeArray(n,i));let o=[...r.data].map((i,a)=>s.type._parseSync(new Ut(r,i,r.path,a)));return Ge.mergeArray(n,o)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:z.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:z.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:z.toString(r)}})}nonempty(e){return this.min(1,e)}};Ir.create=(t,e)=>new Ir({type:t,minLength:null,maxLength:null,exactLength:null,typeName:P.ZodArray,...X(e)});vt=class t extends ee{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=ie.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==M.object){let u=this._getOrReturnCtx(e);return A(u,{code:$.invalid_type,expected:M.object,received:u.parsedType}),W}let{status:n,ctx:s}=this._processInputParams(e),{shape:o,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof rr&&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 Ut(s,l,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof rr){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&&(A(s,{code:$.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 Ut(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=>Ge.mergeObjectSync(n,u)):Ge.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return z.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:z.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:P.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 Ps(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 xt;)o=o._def.innerType;r[n]=o}return new t({...this._def,shape:()=>r})}keyof(){return vx(ie.objectKeys(this.shape))}};vt.create=(t,e)=>new vt({shape:()=>t,unknownKeys:"strip",catchall:rr.create(),typeName:P.ZodObject,...X(e)});vt.strictCreate=(t,e)=>new vt({shape:()=>t,unknownKeys:"strict",catchall:rr.create(),typeName:P.ZodObject,...X(e)});vt.lazycreate=(t,e)=>new vt({shape:t,unknownKeys:"strip",catchall:rr.create(),typeName:P.ZodObject,...X(e)});Dn=class extends ee{_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 _t(a.ctx.common.issues));return A(r,{code:$.invalid_union,unionErrors:i}),W}if(r.common.async)return Promise.all(n.map(async o=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let o,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=i.map(c=>new _t(c));return A(r,{code:$.invalid_union,unionErrors:a}),W}}get options(){return this._def.options}};Dn.create=(t,e)=>new Dn({options:t,typeName:P.ZodUnion,...X(e)});Cr=t=>t instanceof jn?Cr(t.schema):t instanceof Ht?Cr(t.innerType()):t instanceof zn?[t.value]:t instanceof Ln?t.options:t instanceof Fn?ie.objectValues(t.enum):t instanceof Un?Cr(t._def.innerType):t instanceof An?[void 0]:t instanceof Nn?[null]:t instanceof xt?[void 0,...Cr(t.unwrap())]:t instanceof xr?[null,...Cr(t.unwrap())]:t instanceof Do||t instanceof Zn?Cr(t.unwrap()):t instanceof Hn?Cr(t._def.innerType):[],Aa=class t extends ee{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.object)return A(r,{code:$.invalid_type,expected:M.object,received:r.parsedType}),W;let n=this.discriminator,s=r.data[n],o=this.optionsMap.get(s);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(A(r,{code:$.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),W)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let o of r){let i=Cr(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:P.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...X(n)})}};Mn=class extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(o,i)=>{if(Oa(o)||Oa(i))return W;let a=xd(o.value,i.value);return a.valid?((Ia(o)||Ia(i))&&r.dirty(),{status:r.value,value:a.data}):(A(n,{code:$.invalid_intersection_types}),W)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,i])=>s(o,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Mn.create=(t,e,r)=>new Mn({left:t,right:e,typeName:P.ZodIntersection,...X(r)});_r=class t extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.array)return A(n,{code:$.invalid_type,expected:M.array,received:n.parsedType}),W;if(n.data.length<this._def.items.length)return A(n,{code:$.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W;!this._def.rest&&n.data.length>this._def.items.length&&(A(n,{code:$.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 Ut(n,i,n.path,a)):null}).filter(i=>!!i);return n.common.async?Promise.all(o).then(i=>Ge.mergeArray(r,i)):Ge.mergeArray(r,o)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};_r.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new _r({items:t,typeName:P.ZodTuple,rest:null,...X(e)})};Na=class t extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.object)return A(n,{code:$.invalid_type,expected:M.object,received:n.parsedType}),W;let s=[],o=this._def.keyType,i=this._def.valueType;for(let a in n.data)s.push({key:o._parse(new Ut(n,a,n.path,a)),value:i._parse(new Ut(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Ge.mergeObjectAsync(r,s):Ge.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof ee?new t({keyType:e,valueType:r,typeName:P.ZodRecord,...X(n)}):new t({keyType:Xr.create(),valueType:e,typeName:P.ZodRecord,...X(r)})}},Os=class extends ee{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.map)return A(n,{code:$.invalid_type,expected:M.map,received:n.parsedType}),W;let s=this._def.keyType,o=this._def.valueType,i=[...n.data.entries()].map(([a,c],u)=>({key:s._parse(new Ut(n,a,n.path,[u,"key"])),value:o._parse(new Ut(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return W;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Os.create=(t,e,r)=>new Os({valueType:e,keyType:t,typeName:P.ZodMap,...X(r)});Is=class t extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==M.set)return A(n,{code:$.invalid_type,expected:M.set,received:n.parsedType}),W;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(A(n,{code:$.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&&(A(n,{code:$.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let o=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return W;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new Ut(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:z.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:z.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Is.create=(t,e)=>new Is({valueType:t,minSize:null,maxSize:null,typeName:P.ZodSet,...X(e)});Da=class t extends ee{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.function)return A(r,{code:$.invalid_type,expected:M.function,received:r.parsedType}),W;function n(a,c){return No({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,$s(),Rr].filter(u=>!!u),issueData:{code:$.invalid_arguments,argumentsError:c}})}function s(a,c){return No({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,$s(),Rr].filter(u=>!!u),issueData:{code:$.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof en){let a=this;return nt(async function(...c){let u=new _t([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(i,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(s(l,f)),u})})}else{let a=this;return nt(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new _t([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new _t([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:_r.create(e).rest(Or.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||_r.create([]).rest(Or.create()),returns:r||Or.create(),typeName:P.ZodFunction,...X(n)})}},jn=class extends ee{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})}};jn.create=(t,e)=>new jn({getter:t,typeName:P.ZodLazy,...X(e)});zn=class extends ee{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return A(r,{received:r.data,code:$.invalid_literal,expected:this._def.value}),W}return{status:"valid",value:e.data}}get value(){return this._def.value}};zn.create=(t,e)=>new zn({value:t,typeName:P.ZodLiteral,...X(e)});Ln=class t extends ee{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return A(r,{expected:ie.joinValues(n),received:r.parsedType,code:$.invalid_type}),W}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return A(r,{received:r.data,code:$.invalid_enum_value,options:n}),W}return nt(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})}};Ln.create=vx;Fn=class extends ee{_parse(e){let r=ie.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==M.string&&n.parsedType!==M.number){let s=ie.objectValues(r);return A(n,{expected:ie.joinValues(s),received:n.parsedType,code:$.invalid_type}),W}if(this._cache||(this._cache=new Set(ie.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=ie.objectValues(r);return A(n,{received:n.data,code:$.invalid_enum_value,options:s}),W}return nt(e.data)}get enum(){return this._def.values}};Fn.create=(t,e)=>new Fn({values:t,typeName:P.ZodNativeEnum,...X(e)});en=class extends ee{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==M.promise&&r.common.async===!1)return A(r,{code:$.invalid_type,expected:M.promise,received:r.parsedType}),W;let n=r.parsedType===M.promise?r.data:Promise.resolve(r.data);return nt(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};en.create=(t,e)=>new en({type:t,typeName:P.ZodPromise,...X(e)});Ht=class extends ee{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===P.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=>{A(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),s.type==="preprocess"){let i=s.transform(n.data,o);if(n.common.async)return Promise.resolve(i).then(async a=>{if(r.value==="aborted")return W;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?W:c.status==="dirty"?Pn(c.value):r.value==="dirty"?Pn(c.value):c});{if(r.value==="aborted")return W;let a=this._def.schema._parseSync({data:i,path:n.path,parent:n});return a.status==="aborted"?W:a.status==="dirty"?Pn(a.value):r.value==="dirty"?Pn(a.value):a}}if(s.type==="refinement"){let i=a=>{let c=s.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?W:(a.status==="dirty"&&r.dirty(),i(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?W:(a.status==="dirty"&&r.dirty(),i(a.value).then(()=>({status:r.value,value:a.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Yr(i))return W;let a=s.transform(i.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Yr(i)?Promise.resolve(s.transform(i.value,o)).then(a=>({status:r.value,value:a})):W);ie.assertNever(s)}};Ht.create=(t,e,r)=>new Ht({schema:t,typeName:P.ZodEffects,effect:e,...X(r)});Ht.createWithPreprocess=(t,e,r)=>new Ht({schema:e,effect:{type:"preprocess",transform:t},typeName:P.ZodEffects,...X(r)});xt=class extends ee{_parse(e){return this._getType(e)===M.undefined?nt(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xt.create=(t,e)=>new xt({innerType:t,typeName:P.ZodOptional,...X(e)});xr=class extends ee{_parse(e){return this._getType(e)===M.null?nt(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};xr.create=(t,e)=>new xr({innerType:t,typeName:P.ZodNullable,...X(e)});Un=class extends ee{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===M.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Un.create=(t,e)=>new Un({innerType:t,typeName:P.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...X(e)});Hn=class extends ee{_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 Ts(s)?s.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new _t(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Hn.create=(t,e)=>new Hn({innerType:t,typeName:P.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...X(e)});As=class extends ee{_parse(e){if(this._getType(e)!==M.nan){let n=this._getOrReturnCtx(e);return A(n,{code:$.invalid_type,expected:M.nan,received:n.parsedType}),W}return{status:"valid",value:e.data}}};As.create=t=>new As({typeName:P.ZodNaN,...X(t)});vR=Symbol("zod_brand"),Do=class extends ee{_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}},Mo=class t extends ee{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?W:o.status==="dirty"?(r.dirty(),Pn(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?W:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:P.ZodPipeline})}},Zn=class extends ee{_parse(e){let r=this._def.innerType._parse(e),n=s=>(Yr(s)&&(s.value=Object.freeze(s.value)),s);return Ts(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};Zn.create=(t,e)=>new Zn({innerType:t,typeName:P.ZodReadonly,...X(e)});bR={object:vt.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"})(P||(P={}));SR=(t,e={message:`Input not instance of ${t.name}`})=>bx(r=>r instanceof t,e),Sx=Xr.create,kx=Rn.create,kR=As.create,wR=Cn.create,wx=On.create,ER=In.create,$R=Rs.create,TR=An.create,PR=Nn.create,RR=Qr.create,CR=Or.create,OR=rr.create,IR=Cs.create,AR=Ir.create,vd=vt.create,NR=vt.strictCreate,DR=Dn.create,MR=Aa.create,jR=Mn.create,zR=_r.create,LR=Na.create,FR=Os.create,UR=Is.create,HR=Da.create,ZR=jn.create,BR=zn.create,qR=Ln.create,VR=Fn.create,WR=en.create,GR=Ht.create,KR=xt.create,JR=xr.create,YR=Ht.createWithPreprocess,XR=Mo.create,QR=()=>Sx().optional(),eC=()=>kx().optional(),tC=()=>wx().optional(),rC={string:(t=>Xr.create({...t,coerce:!0})),number:(t=>Rn.create({...t,coerce:!0})),boolean:(t=>On.create({...t,coerce:!0})),bigint:(t=>Cn.create({...t,coerce:!0})),date:(t=>In.create({...t,coerce:!0}))},nC=W});var U={};Le(U,{BRAND:()=>vR,DIRTY:()=>Pn,EMPTY_PATH:()=>XP,INVALID:()=>W,NEVER:()=>nC,OK:()=>nt,ParseStatus:()=>Ge,Schema:()=>ee,ZodAny:()=>Qr,ZodArray:()=>Ir,ZodBigInt:()=>Cn,ZodBoolean:()=>On,ZodBranded:()=>Do,ZodCatch:()=>Hn,ZodDate:()=>In,ZodDefault:()=>Un,ZodDiscriminatedUnion:()=>Aa,ZodEffects:()=>Ht,ZodEnum:()=>Ln,ZodError:()=>_t,ZodFirstPartyTypeKind:()=>P,ZodFunction:()=>Da,ZodIntersection:()=>Mn,ZodIssueCode:()=>$,ZodLazy:()=>jn,ZodLiteral:()=>zn,ZodMap:()=>Os,ZodNaN:()=>As,ZodNativeEnum:()=>Fn,ZodNever:()=>rr,ZodNull:()=>Nn,ZodNullable:()=>xr,ZodNumber:()=>Rn,ZodObject:()=>vt,ZodOptional:()=>xt,ZodParsedType:()=>M,ZodPipeline:()=>Mo,ZodPromise:()=>en,ZodReadonly:()=>Zn,ZodRecord:()=>Na,ZodSchema:()=>ee,ZodSet:()=>Is,ZodString:()=>Xr,ZodSymbol:()=>Rs,ZodTransformer:()=>Ht,ZodTuple:()=>_r,ZodType:()=>ee,ZodUndefined:()=>An,ZodUnion:()=>Dn,ZodUnknown:()=>Or,ZodVoid:()=>Cs,addIssueToContext:()=>A,any:()=>RR,array:()=>AR,bigint:()=>wR,boolean:()=>wx,coerce:()=>rC,custom:()=>bx,date:()=>ER,datetimeRegex:()=>xx,defaultErrorMap:()=>Rr,discriminatedUnion:()=>MR,effect:()=>GR,enum:()=>qR,function:()=>HR,getErrorMap:()=>$s,getParsedType:()=>yr,instanceof:()=>SR,intersection:()=>jR,isAborted:()=>Oa,isAsync:()=>Ts,isDirty:()=>Ia,isValid:()=>Yr,late:()=>bR,lazy:()=>ZR,literal:()=>BR,makeIssue:()=>No,map:()=>FR,nan:()=>kR,nativeEnum:()=>VR,never:()=>OR,null:()=>PR,nullable:()=>JR,number:()=>kx,object:()=>vd,objectUtil:()=>hd,oboolean:()=>tC,onumber:()=>eC,optional:()=>KR,ostring:()=>QR,pipeline:()=>XR,preprocess:()=>YR,promise:()=>WR,quotelessJson:()=>KP,record:()=>LR,set:()=>UR,setErrorMap:()=>YP,strictObject:()=>NR,string:()=>Sx,symbol:()=>$R,transformer:()=>GR,tuple:()=>zR,undefined:()=>TR,union:()=>DR,unknown:()=>CR,util:()=>ie,void:()=>IR});var Ma=v(()=>{Ca();yd();mx();Ao();Ex();Ra()});var jo=v(()=>{Ma()});function k(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 Ct(t){return t&&Object.assign(ja,t),ja}var oC,Ar,ja,Ns=v(()=>{oC=Object.freeze({status:"aborted"});Ar=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}},ja={}});var ae={};Le(ae,{BIGINT_FORMAT_RANGES:()=>Tx,Class:()=>Sd,NUMBER_FORMAT_RANGES:()=>Rd,aborted:()=>qn,allowsEval:()=>$d,assert:()=>lC,assertEqual:()=>iC,assertIs:()=>cC,assertNever:()=>uC,assertNotEqual:()=>aC,assignProp:()=>Ed,cached:()=>Fo,captureStackTrace:()=>La,cleanEnum:()=>kC,cleanRegex:()=>Ho,clone:()=>Ot,createTransparentProxy:()=>gC,defineLazy:()=>ke,esc:()=>Bn,escapeRegex:()=>tn,extend:()=>xC,finalizeIssue:()=>nr,floatSafeRemainder:()=>wd,getElementAtPath:()=>dC,getEnumValues:()=>Lo,getLengthableOrigin:()=>Zo,getParsedType:()=>hC,getSizableOrigin:()=>Px,isObject:()=>Ds,isPlainObject:()=>Ms,issue:()=>Cd,joinValues:()=>za,jsonStringifyReplacer:()=>kd,merge:()=>vC,normalizeParams:()=>G,nullish:()=>Uo,numKeys:()=>fC,omit:()=>_C,optionalKeys:()=>Pd,partial:()=>bC,pick:()=>yC,prefixIssues:()=>vr,primitiveTypes:()=>$x,promiseAllObject:()=>pC,propertyKeyTypes:()=>Td,randomString:()=>mC,required:()=>SC,stringifyPrimitive:()=>Fa,unwrapMessage:()=>zo});function iC(t){return t}function aC(t){return t}function cC(t){}function uC(t){throw new Error}function lC(t){}function Lo(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 za(t,e="|"){return t.map(r=>Fa(r)).join(e)}function kd(t,e){return typeof e=="bigint"?e.toString():e}function Fo(t){return{get value(){{let r=t();return Object.defineProperty(this,"value",{value:r}),r}throw new Error("cached value already set")}}}function Uo(t){return t==null}function Ho(t){let e=t.startsWith("^")?1:0,r=t.endsWith("$")?t.length-1:t.length;return t.slice(e,r)}function wd(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,o=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return o%i/10**s}function ke(t,e,r){Object.defineProperty(t,e,{get(){{let s=r();return t[e]=s,s}throw new Error("cached value already set")},set(s){Object.defineProperty(t,e,{value:s})},configurable:!0})}function Ed(t,e,r){Object.defineProperty(t,e,{value:r,writable:!0,enumerable:!0,configurable:!0})}function dC(t,e){return e?e.reduce((r,n)=>r?.[n],t):t}function pC(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 mC(t=10){let e="abcdefghijklmnopqrstuvwxyz",r="";for(let n=0;n<t;n++)r+=e[Math.floor(Math.random()*e.length)];return r}function Bn(t){return JSON.stringify(t)}function Ds(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ms(t){if(Ds(t)===!1)return!1;let e=t.constructor;if(e===void 0)return!0;let r=e.prototype;return!(Ds(r)===!1||Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)}function fC(t){let e=0;for(let r in t)Object.prototype.hasOwnProperty.call(t,r)&&e++;return e}function tn(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ot(t,e,r){let n=new t._zod.constr(e??t._zod.def);return(!e||r?.parent)&&(n._zod.parent=t),n}function G(t){let e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if(e?.message!==void 0){if(e?.error!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function gC(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 Fa(t){return typeof t=="bigint"?t.toString()+"n":typeof t=="string"?`"${t}"`:`${t}`}function Pd(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}function yC(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 Ot(t,{...t._zod.def,shape:r,checks:[]})}function _C(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 Ot(t,{...t._zod.def,shape:r,checks:[]})}function xC(t,e){if(!Ms(e))throw new Error("Invalid input to extend: expected a plain object");let r={...t._zod.def,get shape(){let n={...t._zod.def.shape,...e};return Ed(this,"shape",n),n},checks:[]};return Ot(t,r)}function vC(t,e){return Ot(t,{...t._zod.def,get shape(){let r={...t._zod.def.shape,...e._zod.def.shape};return Ed(this,"shape",r),r},catchall:e._zod.def.catchall,checks:[]})}function bC(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 Ot(e,{...e._zod.def,shape:s,checks:[]})}function SC(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 Ot(e,{...e._zod.def,shape:s,checks:[]})}function qn(t,e=0){for(let r=e;r<t.issues.length;r++)if(t.issues[r]?.continue!==!0)return!0;return!1}function vr(t,e){return e.map(r=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(t),r})}function zo(t){return typeof t=="string"?t:t?.message}function nr(t,e,r){let n={...t,path:t.path??[]};if(!t.message){let s=zo(t.inst?._zod.def?.error?.(t))??zo(e?.error?.(t))??zo(r.customError?.(t))??zo(r.localeError?.(t))??"Invalid input";n.message=s}return delete n.inst,delete n.continue,e?.reportInput||delete n.input,n}function Px(t){return t instanceof Set?"set":t instanceof Map?"map":t instanceof File?"file":"unknown"}function Zo(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Cd(...t){let[e,r,n]=t;return typeof e=="string"?{message:e,code:"custom",input:r,inst:n}:{...e}}function kC(t){return Object.entries(t).filter(([e,r])=>Number.isNaN(Number.parseInt(e,10))).map(e=>e[1])}var La,$d,hC,Td,$x,Rd,Tx,Sd,br=v(()=>{La=Error.captureStackTrace?Error.captureStackTrace:(...t)=>{};$d=Fo(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{let t=Function;return new t(""),!0}catch{return!1}});hC=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}`)}},Td=new Set(["string","number","symbol"]),$x=new Set(["string","number","bigint","boolean","symbol","undefined"]);Rd={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]},Tx={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};Sd=class{constructor(...e){}}});function Od(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 Id(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 Rx,Ua,Bo,Ad=v(()=>{Ns();br();Rx=(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,kd,2)},enumerable:!0}),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},Ua=k("$ZodError",Rx),Bo=k("$ZodError",Rx,{Parent:Error})});var Nd,Dd,Md,jd,zd,Vn,Ld,Wn,Fd=v(()=>{Ns();Ad();br();Nd=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 Ar;if(i.issues.length){let a=new(s?.Err??t)(i.issues.map(c=>nr(c,o,Ct())));throw La(a,s?.callee),a}return i.value},Dd=Nd(Bo),Md=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=>nr(c,o,Ct())));throw La(a,s?.callee),a}return i.value},jd=Md(Bo),zd=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 Ar;return o.issues.length?{success:!1,error:new(t??Ua)(o.issues.map(i=>nr(i,s,Ct())))}:{success:!0,data:o.value}},Vn=zd(Bo),Ld=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=>nr(i,s,Ct())))}:{success:!0,data:o.value}},Wn=Ld(Bo)});function Lx(){return new RegExp(EC,"u")}function Kx(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 Jx(t){return new RegExp(`^${Kx(t)}$`)}function Yx(t){let e=Kx({precision:t.precision}),r=["Z"];t.local&&r.push(""),t.offset&&r.push("([+-]\\d{2}:\\d{2})");let n=`${e}(?:${r.join("|")})`;return new RegExp(`^${Wx}T(?:${n})$`)}var Cx,Ox,Ix,Ax,Nx,Dx,Mx,jx,Ud,zx,EC,Fx,Ux,Hx,Zx,Bx,Hd,qx,Vx,Wx,Gx,Xx,Qx,ev,tv,rv,nv,sv,Za=v(()=>{Cx=/^[cC][^\s-]{8,}$/,Ox=/^[0-9a-z]+$/,Ix=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Ax=/^[0-9a-vA-V]{20}$/,Nx=/^[A-Za-z0-9]{27}$/,Dx=/^[a-zA-Z0-9_-]{21}$/,Mx=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,jx=/^([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})$/,Ud=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)$/,zx=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,EC="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";Fx=/^(?:(?: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])$/,Ux=/^(([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})$/,Hx=/^((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])$/,Zx=/^(([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])$/,Bx=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Hd=/^[A-Za-z0-9_-]*$/,qx=/^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/,Vx=/^\+(?:[0-9]){6,14}[0-9]$/,Wx="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",Gx=new RegExp(`^${Wx}$`);Xx=t=>{let e=t?`[\\s\\S]{${t?.minimum??0},${t?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},Qx=/^\d+$/,ev=/^-?\d+(?:\.\d+)?/i,tv=/true|false/i,rv=/null/i,nv=/^[^A-Z]*$/,sv=/^[^a-z]*$/});var Ke,ov,Zd,Bd,iv,av,cv,uv,lv,qo,dv,pv,mv,fv,hv,gv,yv,Ba=v(()=>{Ns();Za();br();Ke=k("$ZodCheck",(t,e)=>{var r;t._zod??(t._zod={}),t._zod.def=e,(r=t._zod).onattach??(r.onattach=[])}),ov={number:"number",bigint:"bigint",object:"date"},Zd=k("$ZodCheckLessThan",(t,e)=>{Ke.init(t,e);let r=ov[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})}}),Bd=k("$ZodCheckGreaterThan",(t,e)=>{Ke.init(t,e);let r=ov[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})}}),iv=k("$ZodCheckMultipleOf",(t,e)=>{Ke.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):wd(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})}}),av=k("$ZodCheckNumberFormat",(t,e)=>{Ke.init(t,e),e.format=e.format||"float64";let r=e.format?.includes("int"),n=r?"int":"number",[s,o]=Rd[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=Qx)}),t._zod.check=i=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:e.format,code:"invalid_type",input:a,inst:t});return}if(!Number.isSafeInteger(a)){a>0?i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort}):i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:n,continue:!e.abort});return}}a<s&&i.issues.push({origin:"number",input:a,code:"too_small",minimum:s,inclusive:!0,inst:t,continue:!e.abort}),a>o&&i.issues.push({origin:"number",input:a,code:"too_big",maximum:o,inst:t})}}),cv=k("$ZodCheckMaxLength",(t,e)=>{var r;Ke.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Uo(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=Zo(s);n.issues.push({origin:i,code:"too_big",maximum:e.maximum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),uv=k("$ZodCheckMinLength",(t,e)=>{var r;Ke.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Uo(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=Zo(s);n.issues.push({origin:i,code:"too_small",minimum:e.minimum,inclusive:!0,input:s,inst:t,continue:!e.abort})}}),lv=k("$ZodCheckLengthEquals",(t,e)=>{var r;Ke.init(t,e),(r=t._zod.def).when??(r.when=n=>{let s=n.value;return!Uo(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=Zo(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})}}),qo=k("$ZodCheckStringFormat",(t,e)=>{var r,n;Ke.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=()=>{})}),dv=k("$ZodCheckRegex",(t,e)=>{qo.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})}}),pv=k("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=nv),qo.init(t,e)}),mv=k("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=sv),qo.init(t,e)}),fv=k("$ZodCheckIncludes",(t,e)=>{Ke.init(t,e);let r=tn(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})}}),hv=k("$ZodCheckStartsWith",(t,e)=>{Ke.init(t,e);let r=new RegExp(`^${tn(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})}}),gv=k("$ZodCheckEndsWith",(t,e)=>{Ke.init(t,e);let r=new RegExp(`.*${tn(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})}}),yv=k("$ZodCheckOverwrite",(t,e)=>{Ke.init(t,e),t._zod.check=r=>{r.value=e.tx(r.value)}})});var qa,qd=v(()=>{qa=class{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let n=e.split(`
34
+ `).filter(i=>i),s=Math.min(...n.map(i=>i.length-i.trimStart().length)),o=n.map(i=>i.slice(s)).map(i=>" ".repeat(this.indent*2)+i);for(let i of o)this.content.push(i)}compile(){let e=Function,r=this?.args,s=[...(this?.content??[""]).map(o=>` ${o}`)];return new e(...r,s.join(`
35
+ `))}}});var xv,Vd=v(()=>{xv={major:4,minor:0,patch:0}});function Av(t){if(t==="")return!0;if(t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}function $C(t){if(!Hd.test(t))return!1;let e=t.replace(/[-_]/g,n=>n==="-"?"+":"/"),r=e.padEnd(Math.ceil(e.length/4)*4,"=");return Av(r)}function TC(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 vv(t,e,r){t.issues.length&&e.issues.push(...vr(r,t.issues)),e.value[r]=t.value}function Va(t,e,r){t.issues.length&&e.issues.push(...vr(r,t.issues)),e.value[r]=t.value}function bv(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(...vr(r,t.issues)):t.value===void 0?r in n&&(e.value[r]=void 0):e.value[r]=t.value}function Sv(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=>nr(o,n,Ct())))}),e}function Wd(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(Ms(t)&&Ms(e)){let r=Object.keys(e),n=Object.keys(t).filter(o=>r.indexOf(o)!==-1),s={...t,...e};for(let o of n){let i=Wd(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=Wd(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 kv(t,e,r){if(e.issues.length&&t.issues.push(...e.issues),r.issues.length&&t.issues.push(...r.issues),qn(t))return t;let n=Wd(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 wv(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}function Ev(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 $v(t,e,r){return qn(t)?t:e.out._zod.run({value:t.value,issues:t.issues},r)}function Tv(t){return t.value=Object.freeze(t.value),t}function Pv(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(Cd(s))}}var _e,Vo,we,Gd,Kd,Jd,Yd,Xd,Qd,ep,tp,rp,np,sp,Rv,Cv,Ov,Iv,op,ip,ap,cp,up,lp,dp,pp,Wa,mp,fp,hp,gp,yp,_p,Ga,Ka,xp,vp,bp,Sp,kp,wp,Ep,$p,Tp,Pp,Rp,Cp,Op,Ip,Ap,Nv=v(()=>{Ba();Ns();qd();Fd();Za();br();Vd();br();_e=k("$ZodType",(t,e)=>{var r;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=xv;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=qn(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 Ar;if(u||m instanceof Promise)u=(u??Promise.resolve()).then(async()=>{await m,o.issues.length!==l&&(c||(c=qn(o,l)))});else{if(o.issues.length===l)continue;c||(c=qn(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 Ar;return a.then(c=>s(c,n,i))}return s(a,n,i)}}t["~standard"]={validate:s=>{try{let o=Vn(t,s);return o.success?{value:o.data}:{issues:o.error?.issues}}catch{return Wn(t,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),Vo=k("$ZodString",(t,e)=>{_e.init(t,e),t._zod.pattern=[...t?._zod.bag?.patterns??[]].pop()??Xx(t._zod.bag),t._zod.parse=(r,n)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),we=k("$ZodStringFormat",(t,e)=>{qo.init(t,e),Vo.init(t,e)}),Gd=k("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=jx),we.init(t,e)}),Kd=k("$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=Ud(n))}else e.pattern??(e.pattern=Ud());we.init(t,e)}),Jd=k("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=zx),we.init(t,e)}),Yd=k("$ZodURL",(t,e)=>{we.init(t,e),t._zod.check=r=>{try{let n=r.value,s=new URL(n),o=s.href;e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:qx.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})}}}),Xd=k("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=Lx()),we.init(t,e)}),Qd=k("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=Dx),we.init(t,e)}),ep=k("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=Cx),we.init(t,e)}),tp=k("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=Ox),we.init(t,e)}),rp=k("$ZodULID",(t,e)=>{e.pattern??(e.pattern=Ix),we.init(t,e)}),np=k("$ZodXID",(t,e)=>{e.pattern??(e.pattern=Ax),we.init(t,e)}),sp=k("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=Nx),we.init(t,e)}),Rv=k("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=Yx(e)),we.init(t,e)}),Cv=k("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=Gx),we.init(t,e)}),Ov=k("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=Jx(e)),we.init(t,e)}),Iv=k("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=Mx),we.init(t,e)}),op=k("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=Fx),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv4"})}),ip=k("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=Ux),we.init(t,e),t._zod.onattach.push(r=>{let n=r._zod.bag;n.format="ipv6"}),t._zod.check=r=>{try{new URL(`http://[${r.value}]`)}catch{r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:t,continue:!e.abort})}}}),ap=k("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=Hx),we.init(t,e)}),cp=k("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=Zx),we.init(t,e),t._zod.check=r=>{let[n,s]=r.value.split("/");try{if(!s)throw new Error;let o=Number(s);if(`${o}`!==s)throw new Error;if(o<0||o>128)throw new Error;new URL(`http://[${n}]`)}catch{r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:t,continue:!e.abort})}}});up=k("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=Bx),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64"}),t._zod.check=r=>{Av(r.value)||r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:t,continue:!e.abort})}});lp=k("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=Hd),we.init(t,e),t._zod.onattach.push(r=>{r._zod.bag.contentEncoding="base64url"}),t._zod.check=r=>{$C(r.value)||r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:t,continue:!e.abort})}}),dp=k("$ZodE164",(t,e)=>{e.pattern??(e.pattern=Vx),we.init(t,e)});pp=k("$ZodJWT",(t,e)=>{we.init(t,e),t._zod.check=r=>{TC(r.value,e.alg)||r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:t,continue:!e.abort})}}),Wa=k("$ZodNumber",(t,e)=>{_e.init(t,e),t._zod.pattern=t._zod.bag.pattern??ev,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}}),mp=k("$ZodNumber",(t,e)=>{av.init(t,e),Wa.init(t,e)}),fp=k("$ZodBoolean",(t,e)=>{_e.init(t,e),t._zod.pattern=tv,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}}),hp=k("$ZodNull",(t,e)=>{_e.init(t,e),t._zod.pattern=rv,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}}),gp=k("$ZodUnknown",(t,e)=>{_e.init(t,e),t._zod.parse=r=>r}),yp=k("$ZodNever",(t,e)=>{_e.init(t,e),t._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:t}),r)});_p=k("$ZodArray",(t,e)=>{_e.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=>vv(u,r,i))):vv(c,r,i)}return o.length?Promise.all(o).then(()=>r):r}});Ga=k("$ZodObject",(t,e)=>{_e.init(t,e);let r=Fo(()=>{let l=Object.keys(e.shape);for(let f of l)if(!(e.shape[f]instanceof _e))throw new Error(`Invalid element at key "${f}": expected a Zod schema`);let m=Pd(e.shape);return{shape:e.shape,keys:l,keySet:new Set(l),numKeys:l.length,optionalKeys:new Set(m)}});ke(t._zod,"propValues",()=>{let l=e.shape,m={};for(let f in l){let p=l[f]._zod;if(p.values){m[f]??(m[f]=new Set);for(let h of p.values)m[f].add(h)}}return m});let n=l=>{let m=new qa(["shape","payload","ctx"]),f=r.value,p=_=>{let x=Bn(_);return`shape[${x}]._zod.run({ value: input[${x}], issues: [] }, ctx)`};m.write("const input = payload.value;");let h=Object.create(null),g=0;for(let _ of f.keys)h[_]=`key_${g++}`;m.write("const newResult = {}");for(let _ of f.keys)if(f.optionalKeys.has(_)){let x=h[_];m.write(`const ${x} = ${p(_)};`);let S=Bn(_);m.write(`
22
36
  if (${x}.issues.length) {
23
- if (input[${k}] === undefined) {
24
- if (${k} in input) {
25
- newResult[${k}] = undefined;
37
+ if (input[${S}] === undefined) {
38
+ if (${S} in input) {
39
+ newResult[${S}] = undefined;
26
40
  }
27
41
  } else {
28
42
  payload.issues = payload.issues.concat(
29
43
  ${x}.issues.map((iss) => ({
30
44
  ...iss,
31
- path: iss.path ? [${k}, ...iss.path] : [${k}],
45
+ path: iss.path ? [${S}, ...iss.path] : [${S}],
32
46
  }))
33
47
  );
34
48
  }
35
49
  } else if (${x}.value === undefined) {
36
- if (${k} in input) newResult[${k}] = undefined;
50
+ if (${S} in input) newResult[${S}] = undefined;
37
51
  } else {
38
- newResult[${k}] = ${x}.value;
52
+ newResult[${S}] = ${x}.value;
39
53
  }
40
- `)}else{let x=h[_];p.write(`const ${x} = ${m(_)};`),p.write(`
54
+ `)}else{let x=h[_];m.write(`const ${x} = ${p(_)};`),m.write(`
41
55
  if (${x}.issues.length) payload.issues = payload.issues.concat(${x}.issues.map(iss => ({
42
56
  ...iss,
43
- path: iss.path ? [${Nn(_)}, ...iss.path] : [${Nn(_)}]
44
- })));`),p.write(`newResult[${Nn(_)}] = ${x}.value`)}p.write("payload.value = newResult;"),p.write("return payload;");let y=p.compile();return(_,x)=>y(d,_,x)},o,s=ko,i=!_a.jitless,c=i&&jl.value,u=e.catchall,l;t._zod.parse=(d,p)=>{l??(l=r.value);let f=d.value;if(!s(f))return d.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),d;let m=[];if(i&&c&&p?.async===!1&&p.jitless!==!0)o||(o=n(e.shape)),d=o(d,p);else{d.value={};let x=l.shape;for(let k of l.keys){let E=x[k],H=E._zod.run({value:f[k],issues:[]},p),z=E._zod.optin==="optional"&&E._zod.optout==="optional";H instanceof Promise?m.push(H.then(K=>z?gx(K,d,k,f):Ea(K,d,k))):z?gx(H,d,k,f):Ea(H,d,k)}}if(!u)return m.length?Promise.all(m).then(()=>d):d;let h=[],g=l.keySet,y=u._zod,_=y.def.type;for(let x of Object.keys(f)){if(g.has(x))continue;if(_==="never"){h.push(x);continue}let k=y.run({value:f[x],issues:[]},p);k instanceof Promise?m.push(k.then(E=>Ea(E,d,x))):Ea(k,d,x)}return h.length&&d.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),m.length?Promise.all(m).then(()=>d):d}});Ra=S("$ZodUnion",(t,e)=>{ge.init(t,e),be(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),be(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),be(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),be(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=>Os(n.source)).join("|")})$`)}}),t._zod.parse=(r,n)=>{let o=!1,s=[];for(let i of e.options){let a=i._zod.run({value:r.value,issues:[]},n);if(a instanceof Promise)s.push(a),o=!0;else{if(a.issues.length===0)return a;s.push(a)}}return o?Promise.all(s).then(i=>_x(i,r,t,n)):_x(s,r,t,n)}}),Rd=S("$ZodDiscriminatedUnion",(t,e)=>{Ra.init(t,e);let r=t._zod.parse;be(t._zod,"propValues",()=>{let o={};for(let s of e.options){let i=s._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(s)}"`);for(let[a,c]of Object.entries(i)){o[a]||(o[a]=new Set);for(let u of c)o[a].add(u)}}return o});let n=Rs(()=>{let o=e.options,s=new Map;for(let i of o){let a=i._zod.propValues[e.discriminator];if(!a||a.size===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(i)}"`);for(let c of a){if(s.has(c))throw new Error(`Duplicate discriminator value "${String(c)}"`);s.set(c,i)}}return s});t._zod.parse=(o,s)=>{let i=o.value;if(!ko(i))return o.issues.push({code:"invalid_type",expected:"object",input:i,inst:t}),o;let a=n.value.get(i?.[e.discriminator]);return a?a._zod.run(o,s):e.unionFallback?r(o,s):(o.issues.push({code:"invalid_union",errors:[],note:"No matching discriminator",input:i,path:[e.discriminator],inst:t}),o)}}),Cd=S("$ZodIntersection",(t,e)=>{ge.init(t,e),t._zod.parse=(r,n)=>{let o=r.value,s=e.left._zod.run({value:o,issues:[]},n),i=e.right._zod.run({value:o,issues:[]},n);return s instanceof Promise||i instanceof Promise?Promise.all([s,i]).then(([c,u])=>yx(r,c,u)):yx(r,s,i)}});Od=S("$ZodRecord",(t,e)=>{ge.init(t,e),t._zod.parse=(r,n)=>{let o=r.value;if(!wo(o))return r.issues.push({expected:"record",code:"invalid_type",input:o,inst:t}),r;let s=[];if(e.keyType._zod.values){let i=e.keyType._zod.values;r.value={};for(let c of i)if(typeof c=="string"||typeof c=="number"||typeof c=="symbol"){let u=e.valueType._zod.run({value:o[c],issues:[]},n);u instanceof Promise?s.push(u.then(l=>{l.issues.length&&r.issues.push(...ur(c,l.issues)),r.value[c]=l.value})):(u.issues.length&&r.issues.push(...ur(c,u.issues)),r.value[c]=u.value)}let a;for(let c in o)i.has(c)||(a=a??[],a.push(c));a&&a.length>0&&r.issues.push({code:"unrecognized_keys",input:o,inst:t,keys:a})}else{r.value={};for(let i of Reflect.ownKeys(o)){if(i==="__proto__")continue;let a=e.keyType._zod.run({value:i,issues:[]},n);if(a instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(a.issues.length){r.issues.push({origin:"record",code:"invalid_key",issues:a.issues.map(u=>Kt(u,n,vt())),input:i,path:[i],inst:t}),r.value[a.value]=a.value;continue}let c=e.valueType._zod.run({value:o[i],issues:[]},n);c instanceof Promise?s.push(c.then(u=>{u.issues.length&&r.issues.push(...ur(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...ur(i,c.issues)),r.value[a.value]=c.value)}}return s.length?Promise.all(s).then(()=>r):r}}),Id=S("$ZodEnum",(t,e)=>{ge.init(t,e);let r=Ps(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Dl.has(typeof n)).map(n=>typeof n=="string"?Gr(n):n.toString()).join("|")})$`),t._zod.parse=(n,o)=>{let s=n.value;return t._zod.values.has(s)||n.issues.push({code:"invalid_value",values:r,input:s,inst:t}),n}}),Ad=S("$ZodLiteral",(t,e)=>{ge.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?Gr(r):r?r.toString():String(r)).join("|")})$`),t._zod.parse=(r,n)=>{let o=r.value;return t._zod.values.has(o)||r.issues.push({code:"invalid_value",values:e.values,input:o,inst:t}),r}}),Nd=S("$ZodTransform",(t,e)=>{ge.init(t,e),t._zod.parse=(r,n)=>{let o=e.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then(i=>(r.value=i,r));if(o instanceof Promise)throw new Rr;return r.value=o,r}}),zd=S("$ZodOptional",(t,e)=>{ge.init(t,e),t._zod.optin="optional",t._zod.optout="optional",be(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),be(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Os(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)}),jd=S("$ZodNullable",(t,e)=>{ge.init(t,e),be(t._zod,"optin",()=>e.innerType._zod.optin),be(t._zod,"optout",()=>e.innerType._zod.optout),be(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Os(r.source)}|null)$`):void 0}),be(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)}),Dd=S("$ZodDefault",(t,e)=>{ge.init(t,e),t._zod.optin="optional",be(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>xx(s,e)):xx(o,e)}});Md=S("$ZodPrefault",(t,e)=>{ge.init(t,e),t._zod.optin="optional",be(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))}),Ld=S("$ZodNonOptional",(t,e)=>{ge.init(t,e),be(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>vx(s,t)):vx(o,t)}});Fd=S("$ZodCatch",(t,e)=>{ge.init(t,e),t._zod.optin="optional",be(t._zod,"optout",()=>e.innerType._zod.optout),be(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(s=>(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(i=>Kt(i,n,vt()))},input:r.value}),r.issues=[]),r)):(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(s=>Kt(s,n,vt()))},input:r.value}),r.issues=[]),r)}}),Ud=S("$ZodPipe",(t,e)=>{ge.init(t,e),be(t._zod,"values",()=>e.in._zod.values),be(t._zod,"optin",()=>e.in._zod.optin),be(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let o=e.in._zod.run(r,n);return o instanceof Promise?o.then(s=>bx(s,e,n)):bx(o,e,n)}});Zd=S("$ZodReadonly",(t,e)=>{ge.init(t,e),be(t._zod,"propValues",()=>e.innerType._zod.propValues),be(t._zod,"values",()=>e.innerType._zod.values),be(t._zod,"optin",()=>e.innerType._zod.optin),be(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let o=e.innerType._zod.run(r,n);return o instanceof Promise?o.then(Sx):Sx(o)}});Hd=S("$ZodCustom",(t,e)=>{Ge.init(t,e),ge.init(t,e),t._zod.parse=(r,n)=>r,t._zod.check=r=>{let n=r.value,o=e.fn(n);if(o instanceof Promise)return o.then(s=>kx(s,r,n,t));kx(o,r,n,t)}})});function Cx(){return{localeError:jP()}}var zP,jP,Ox=v(()=>{lr();zP=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},jP=()=>{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 ${zP(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${va(n.values[0])}`:`Invalid option: expected one of ${ya(n.values,"|")}`;case"too_big":{let o=n.inclusive?"<=":"<",s=e(n.origin);return s?`Too big: expected ${n.origin??"value"} to have ${o}${n.maximum.toString()} ${s.unit??"elements"}`:`Too big: expected ${n.origin??"value"} to be ${o}${n.maximum.toString()}`}case"too_small":{let o=n.inclusive?">=":">",s=e(n.origin);return s?`Too small: expected ${n.origin} to have ${o}${n.minimum.toString()} ${s.unit}`:`Too small: expected ${n.origin} to be ${o}${n.minimum.toString()}`}case"invalid_format":{let o=n;return o.format==="starts_with"?`Invalid string: must start with "${o.prefix}"`:o.format==="ends_with"?`Invalid string: must end with "${o.suffix}"`:o.format==="includes"?`Invalid string: must include "${o.includes}"`:o.format==="regex"?`Invalid string: must match pattern ${o.pattern}`:`Invalid ${r[o.format]??n.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${n.divisor}`;case"unrecognized_keys":return`Unrecognized key${n.keys.length>1?"s":""}: ${ya(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 Ca=v(()=>{});function Ix(){return new js}var js,Kr,Bd=v(()=>{js=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)}};Kr=Ix()});function Vd(t,e){return new t({type:"string",...B(e)})}function Wd(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...B(e)})}function Oa(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...B(e)})}function Gd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...B(e)})}function Kd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...B(e)})}function Jd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...B(e)})}function Yd(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...B(e)})}function Xd(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...B(e)})}function Qd(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...B(e)})}function ep(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...B(e)})}function tp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...B(e)})}function rp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...B(e)})}function np(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...B(e)})}function op(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...B(e)})}function sp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...B(e)})}function ip(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...B(e)})}function ap(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...B(e)})}function cp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...B(e)})}function up(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...B(e)})}function lp(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...B(e)})}function dp(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...B(e)})}function pp(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...B(e)})}function mp(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...B(e)})}function Ax(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...B(e)})}function Nx(t,e){return new t({type:"string",format:"date",check:"string_format",...B(e)})}function zx(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...B(e)})}function jx(t,e){return new t({type:"string",format:"duration",check:"string_format",...B(e)})}function fp(t,e){return new t({type:"number",checks:[],...B(e)})}function hp(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...B(e)})}function gp(t,e){return new t({type:"boolean",...B(e)})}function _p(t,e){return new t({type:"null",...B(e)})}function yp(t){return new t({type:"unknown"})}function xp(t,e){return new t({type:"never",...B(e)})}function Ia(t,e){return new Ql({check:"less_than",...B(e),value:t,inclusive:!1})}function Ds(t,e){return new Ql({check:"less_than",...B(e),value:t,inclusive:!0})}function Aa(t,e){return new ed({check:"greater_than",...B(e),value:t,inclusive:!1})}function Ms(t,e){return new ed({check:"greater_than",...B(e),value:t,inclusive:!0})}function Na(t,e){return new tx({check:"multiple_of",...B(e),value:t})}function za(t,e){return new nx({check:"max_length",...B(e),maximum:t})}function $o(t,e){return new ox({check:"min_length",...B(e),minimum:t})}function ja(t,e){return new sx({check:"length_equals",...B(e),length:t})}function vp(t,e){return new ix({check:"string_format",format:"regex",...B(e),pattern:t})}function bp(t){return new ax({check:"string_format",format:"lowercase",...B(t)})}function Sp(t){return new cx({check:"string_format",format:"uppercase",...B(t)})}function kp(t,e){return new ux({check:"string_format",format:"includes",...B(e),includes:t})}function wp(t,e){return new lx({check:"string_format",format:"starts_with",...B(e),prefix:t})}function $p(t,e){return new dx({check:"string_format",format:"ends_with",...B(e),suffix:t})}function Mn(t){return new px({check:"overwrite",tx:t})}function Ep(t){return Mn(e=>e.normalize(t))}function Tp(){return Mn(t=>t.trim())}function Pp(){return Mn(t=>t.toLowerCase())}function Rp(){return Mn(t=>t.toUpperCase())}function Dx(t,e,r){return new t({type:"array",element:e,...B(r)})}function Cp(t,e,r){let n=B(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function Op(t,e,r){return new t({type:"custom",check:"custom",fn:e,...B(r)})}var Mx=v(()=>{wa();lr()});var Lx=v(()=>{});function Ip(t,e){if(t instanceof js){let n=new Da(e),o={};for(let a of t._idmap.entries()){let[c,u]=a;n.process(u)}let s={},i={registry:t,uri:e?.uri,defs:o};for(let a of t._idmap.entries()){let[c,u]=a;s[c]=n.emit(u,{...e,external:i})}if(Object.keys(o).length>0){let a=n.target==="draft-2020-12"?"$defs":"definitions";s.__shared={[a]:o}}return{schemas:s}}let r=new Da(e);return r.process(t),r.emit(t,e)}function He(t,e){let r=e??{seen:new Set};if(r.seen.has(t))return!1;r.seen.add(t);let o=t._zod.def;switch(o.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return He(o.element,r);case"object":{for(let s in o.shape)if(He(o.shape[s],r))return!0;return!1}case"union":{for(let s of o.options)if(He(s,r))return!0;return!1}case"intersection":return He(o.left,r)||He(o.right,r);case"tuple":{for(let s of o.items)if(He(s,r))return!0;return!!(o.rest&&He(o.rest,r))}case"record":return He(o.keyType,r)||He(o.valueType,r);case"map":return He(o.keyType,r)||He(o.valueType,r);case"set":return He(o.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return He(o.innerType,r);case"lazy":return He(o.getter(),r);case"default":return He(o.innerType,r);case"prefault":return He(o.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return He(o.in,r)||He(o.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${o.type}`)}var Da,Fx=v(()=>{Bd();lr();Da=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??Kr,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,r.schemaPath.includes(e)&&(i.cycle=r.path),i.schema;let a={schema:{},count:1,cycle:void 0,path:r.path};this.seen.set(e,a);let c=e._zod.toJSONSchema?.();if(c)a.schema=c;else{let d={...r,schemaPath:[...r.schemaPath,e],path:r.path},p=e._zod.parent;if(p)a.ref=p,this.process(p,d),this.seen.get(p).isParent=!0;else{let f=a.schema;switch(o.type){case"string":{let m=f;m.type="string";let{minimum:h,maximum:g,format:y,patterns:_,contentEncoding:x}=e._zod.bag;if(typeof h=="number"&&(m.minLength=h),typeof g=="number"&&(m.maxLength=g),y&&(m.format=s[y]??y,m.format===""&&delete m.format),x&&(m.contentEncoding=x),_&&_.size>0){let k=[..._];k.length===1?m.pattern=k[0].source:k.length>1&&(a.schema.allOf=[...k.map(E=>({...this.target==="draft-7"?{type:"string"}:{},pattern:E.source}))])}break}case"number":{let m=f,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:x,exclusiveMinimum:k}=e._zod.bag;typeof y=="string"&&y.includes("int")?m.type="integer":m.type="number",typeof k=="number"&&(m.exclusiveMinimum=k),typeof h=="number"&&(m.minimum=h,typeof k=="number"&&(k>=h?delete m.minimum:delete m.exclusiveMinimum)),typeof x=="number"&&(m.exclusiveMaximum=x),typeof g=="number"&&(m.maximum=g,typeof x=="number"&&(x<=g?delete m.maximum:delete m.exclusiveMaximum)),typeof _=="number"&&(m.multipleOf=_);break}case"boolean":{let m=f;m.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let m=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(m.minItems=h),typeof g=="number"&&(m.maxItems=g),m.type="array",m.items=this.process(o.element,{...d,path:[...d.path,"items"]});break}case"object":{let m=f;m.type="object",m.properties={};let h=o.shape;for(let _ in h)m.properties[_]=this.process(h[_],{...d,path:[...d.path,"properties",_]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(_=>{let x=o.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.optout===void 0}));y.size>0&&(m.required=Array.from(y)),o.catchall?._zod.def.type==="never"?m.additionalProperties=!1:o.catchall?o.catchall&&(m.additionalProperties=this.process(o.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(m.additionalProperties=!1);break}case"union":{let m=f;m.anyOf=o.options.map((h,g)=>this.process(h,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{let m=f,h=this.process(o.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(o.right,{...d,path:[...d.path,"allOf",1]}),y=x=>"allOf"in x&&Object.keys(x).length===1,_=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];m.allOf=_;break}case"tuple":{let m=f;m.type="array";let h=o.items.map((_,x)=>this.process(_,{...d,path:[...d.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?m.prefixItems=h:m.items=h,o.rest){let _=this.process(o.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?m.items=_:m.additionalItems=_}o.rest&&(m.items=this.process(o.rest,{...d,path:[...d.path,"items"]}));let{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(m.minItems=g),typeof y=="number"&&(m.maxItems=y);break}case"record":{let m=f;m.type="object",m.propertyNames=this.process(o.keyType,{...d,path:[...d.path,"propertyNames"]}),m.additionalProperties=this.process(o.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{let m=f,h=Ps(o.entries);h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),m.enum=h;break}case"literal":{let m=f,h=[];for(let g of o.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];m.type=g===null?"null":typeof g,m.const=g}else h.every(g=>typeof g=="number")&&(m.type="number"),h.every(g=>typeof g=="string")&&(m.type="string"),h.every(g=>typeof g=="boolean")&&(m.type="string"),h.every(g=>g===null)&&(m.type="null"),m.enum=h;break}case"file":{let m=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(m,h)):m.anyOf=_.map(x=>({...h,contentMediaType:x})):Object.assign(m,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let m=this.process(o.innerType,d);f.anyOf=[m,{type:"null"}];break}case"nonoptional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"success":{let m=f;m.type="boolean";break}case"default":{this.process(o.innerType,d),a.ref=o.innerType,f.default=JSON.parse(JSON.stringify(o.defaultValue));break}case"prefault":{this.process(o.innerType,d),a.ref=o.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(o.defaultValue)));break}case"catch":{this.process(o.innerType,d),a.ref=o.innerType;let m;try{m=o.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=m;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let m=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");m.type="string",m.pattern=h.source;break}case"pipe":{let m=this.io==="input"?o.in._zod.def.type==="transform"?o.out:o.in:o.out;this.process(m,d),a.ref=m;break}case"readonly":{this.process(o.innerType,d),a.ref=o.innerType,f.readOnly=!0;break}case"promise":{this.process(o.innerType,d),a.ref=o.innerType;break}case"optional":{this.process(o.innerType,d),a.ref=o.innerType;break}case"lazy":{let m=e._zod.innerType;this.process(m,d),a.ref=m;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}default:}}}let u=this.metadataRegistry.get(e);return u&&Object.assign(a.schema,u),this.io==="input"&&He(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},o=this.seen.get(e);if(!o)throw new Error("Unprocessed schema. This is a bug in Zod.");let s=l=>{let d=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(l[0])?.id,g=n.external.uri??(_=>_);if(h)return{ref:g(h)};let y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===o)return{ref:"#"};let f=`#/${d}/`,m=l[1].schema.id??`__schema${this.counter++}`;return{defId:m,ref:f+m}},i=l=>{if(l[1].schema.$ref)return;let d=l[1],{ref:p,defId:f}=s(l);d.def={...d.schema},f&&(d.defId=f);let m=d.schema;for(let h in m)delete m[h];m.$ref=p};if(n.cycles==="throw")for(let l of this.seen.entries()){let d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
57
+ path: iss.path ? [${Bn(_)}, ...iss.path] : [${Bn(_)}]
58
+ })));`),m.write(`newResult[${Bn(_)}] = ${x}.value`)}m.write("payload.value = newResult;"),m.write("return payload;");let y=m.compile();return(_,x)=>y(l,_,x)},s,o=Ds,i=!ja.jitless,c=i&&$d.value,u=e.catchall,d;t._zod.parse=(l,m)=>{d??(d=r.value);let f=l.value;if(!o(f))return l.issues.push({expected:"object",code:"invalid_type",input:f,inst:t}),l;let p=[];if(i&&c&&m?.async===!1&&m.jitless!==!0)s||(s=n(e.shape)),l=s(l,m);else{l.value={};let x=d.shape;for(let S of d.keys){let w=x[S],I=w._zod.run({value:f[S],issues:[]},m),O=w._zod.optin==="optional"&&w._zod.optout==="optional";I instanceof Promise?p.push(I.then(C=>O?bv(C,l,S,f):Va(C,l,S))):O?bv(I,l,S,f):Va(I,l,S)}}if(!u)return p.length?Promise.all(p).then(()=>l):l;let h=[],g=d.keySet,y=u._zod,_=y.def.type;for(let x of Object.keys(f)){if(g.has(x))continue;if(_==="never"){h.push(x);continue}let S=y.run({value:f[x],issues:[]},m);S instanceof Promise?p.push(S.then(w=>Va(w,l,x))):Va(S,l,x)}return h.length&&l.issues.push({code:"unrecognized_keys",keys:h,input:f,inst:t}),p.length?Promise.all(p).then(()=>l):l}});Ka=k("$ZodUnion",(t,e)=>{_e.init(t,e),ke(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),ke(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),ke(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),ke(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){let r=e.options.map(n=>n._zod.pattern);return new RegExp(`^(${r.map(n=>Ho(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=>Sv(i,r,t,n)):Sv(o,r,t,n)}}),xp=k("$ZodDiscriminatedUnion",(t,e)=>{Ka.init(t,e);let r=t._zod.parse;ke(t._zod,"propValues",()=>{let s={};for(let o of e.options){let i=o._zod.propValues;if(!i||Object.keys(i).length===0)throw new Error(`Invalid discriminated union option at index "${e.options.indexOf(o)}"`);for(let[a,c]of Object.entries(i)){s[a]||(s[a]=new Set);for(let u of c)s[a].add(u)}}return s});let n=Fo(()=>{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(!Ds(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)}}),vp=k("$ZodIntersection",(t,e)=>{_e.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])=>kv(r,c,u)):kv(r,o,i)}});bp=k("$ZodRecord",(t,e)=>{_e.init(t,e),t._zod.parse=(r,n)=>{let s=r.value;if(!Ms(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(...vr(c,d.issues)),r.value[c]=d.value})):(u.issues.length&&r.issues.push(...vr(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=>nr(u,n,Ct())),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(...vr(i,u.issues)),r.value[a.value]=u.value})):(c.issues.length&&r.issues.push(...vr(i,c.issues)),r.value[a.value]=c.value)}}return o.length?Promise.all(o).then(()=>r):r}}),Sp=k("$ZodEnum",(t,e)=>{_e.init(t,e);let r=Lo(e.entries);t._zod.values=new Set(r),t._zod.pattern=new RegExp(`^(${r.filter(n=>Td.has(typeof n)).map(n=>typeof n=="string"?tn(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}}),kp=k("$ZodLiteral",(t,e)=>{_e.init(t,e),t._zod.values=new Set(e.values),t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?tn(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}}),wp=k("$ZodTransform",(t,e)=>{_e.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 Ar;return r.value=s,r}}),Ep=k("$ZodOptional",(t,e)=>{_e.init(t,e),t._zod.optin="optional",t._zod.optout="optional",ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ho(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)}),$p=k("$ZodNullable",(t,e)=>{_e.init(t,e),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"pattern",()=>{let r=e.innerType._zod.pattern;return r?new RegExp(`^(${Ho(r.source)}|null)$`):void 0}),ke(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(r,n)=>r.value===null?r:e.innerType._zod.run(r,n)}),Tp=k("$ZodDefault",(t,e)=>{_e.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{if(r.value===void 0)return r.value=e.defaultValue,r;let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>wv(o,e)):wv(s,e)}});Pp=k("$ZodPrefault",(t,e)=>{_e.init(t,e),t._zod.optin="optional",ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>(r.value===void 0&&(r.value=e.defaultValue),e.innerType._zod.run(r,n))}),Rp=k("$ZodNonOptional",(t,e)=>{_e.init(t,e),ke(t._zod,"values",()=>{let r=e.innerType._zod.values;return r?new Set([...r].filter(n=>n!==void 0)):void 0}),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>Ev(o,t)):Ev(s,t)}});Cp=k("$ZodCatch",(t,e)=>{_e.init(t,e),t._zod.optin="optional",ke(t._zod,"optout",()=>e.innerType._zod.optout),ke(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(o=>(r.value=o.value,o.issues.length&&(r.value=e.catchValue({...r,error:{issues:o.issues.map(i=>nr(i,n,Ct()))},input:r.value}),r.issues=[]),r)):(r.value=s.value,s.issues.length&&(r.value=e.catchValue({...r,error:{issues:s.issues.map(o=>nr(o,n,Ct()))},input:r.value}),r.issues=[]),r)}}),Op=k("$ZodPipe",(t,e)=>{_e.init(t,e),ke(t._zod,"values",()=>e.in._zod.values),ke(t._zod,"optin",()=>e.in._zod.optin),ke(t._zod,"optout",()=>e.out._zod.optout),t._zod.parse=(r,n)=>{let s=e.in._zod.run(r,n);return s instanceof Promise?s.then(o=>$v(o,e,n)):$v(s,e,n)}});Ip=k("$ZodReadonly",(t,e)=>{_e.init(t,e),ke(t._zod,"propValues",()=>e.innerType._zod.propValues),ke(t._zod,"values",()=>e.innerType._zod.values),ke(t._zod,"optin",()=>e.innerType._zod.optin),ke(t._zod,"optout",()=>e.innerType._zod.optout),t._zod.parse=(r,n)=>{let s=e.innerType._zod.run(r,n);return s instanceof Promise?s.then(Tv):Tv(s)}});Ap=k("$ZodCustom",(t,e)=>{Ke.init(t,e),_e.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=>Pv(o,r,n,t));Pv(s,r,n,t)}})});function Dv(){return{localeError:RC()}}var PC,RC,Mv=v(()=>{br();PC=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},RC=()=>{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 ${PC(n.input)}`;case"invalid_value":return n.values.length===1?`Invalid input: expected ${Fa(n.values[0])}`:`Invalid option: expected one of ${za(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":""}: ${za(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 Ja=v(()=>{});function jv(){return new Wo}var Wo,rn,Dp=v(()=>{Wo=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)}};rn=jv()});function Mp(t,e){return new t({type:"string",...G(e)})}function jp(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...G(e)})}function Ya(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...G(e)})}function zp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...G(e)})}function Lp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...G(e)})}function Fp(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...G(e)})}function Up(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...G(e)})}function Hp(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...G(e)})}function Zp(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...G(e)})}function Bp(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...G(e)})}function qp(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...G(e)})}function Vp(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...G(e)})}function Wp(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...G(e)})}function Gp(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...G(e)})}function Kp(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...G(e)})}function Jp(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...G(e)})}function Yp(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...G(e)})}function Xp(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...G(e)})}function Qp(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...G(e)})}function em(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...G(e)})}function tm(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...G(e)})}function rm(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...G(e)})}function nm(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...G(e)})}function zv(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...G(e)})}function Lv(t,e){return new t({type:"string",format:"date",check:"string_format",...G(e)})}function Fv(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...G(e)})}function Uv(t,e){return new t({type:"string",format:"duration",check:"string_format",...G(e)})}function sm(t,e){return new t({type:"number",checks:[],...G(e)})}function om(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...G(e)})}function im(t,e){return new t({type:"boolean",...G(e)})}function am(t,e){return new t({type:"null",...G(e)})}function cm(t){return new t({type:"unknown"})}function um(t,e){return new t({type:"never",...G(e)})}function Xa(t,e){return new Zd({check:"less_than",...G(e),value:t,inclusive:!1})}function Go(t,e){return new Zd({check:"less_than",...G(e),value:t,inclusive:!0})}function Qa(t,e){return new Bd({check:"greater_than",...G(e),value:t,inclusive:!1})}function Ko(t,e){return new Bd({check:"greater_than",...G(e),value:t,inclusive:!0})}function ec(t,e){return new iv({check:"multiple_of",...G(e),value:t})}function tc(t,e){return new cv({check:"max_length",...G(e),maximum:t})}function js(t,e){return new uv({check:"min_length",...G(e),minimum:t})}function rc(t,e){return new lv({check:"length_equals",...G(e),length:t})}function lm(t,e){return new dv({check:"string_format",format:"regex",...G(e),pattern:t})}function dm(t){return new pv({check:"string_format",format:"lowercase",...G(t)})}function pm(t){return new mv({check:"string_format",format:"uppercase",...G(t)})}function mm(t,e){return new fv({check:"string_format",format:"includes",...G(e),includes:t})}function fm(t,e){return new hv({check:"string_format",format:"starts_with",...G(e),prefix:t})}function hm(t,e){return new gv({check:"string_format",format:"ends_with",...G(e),suffix:t})}function Gn(t){return new yv({check:"overwrite",tx:t})}function gm(t){return Gn(e=>e.normalize(t))}function ym(){return Gn(t=>t.trim())}function _m(){return Gn(t=>t.toLowerCase())}function xm(){return Gn(t=>t.toUpperCase())}function Hv(t,e,r){return new t({type:"array",element:e,...G(r)})}function vm(t,e,r){let n=G(r);return n.abort??(n.abort=!0),new t({type:"custom",check:"custom",fn:e,...n})}function bm(t,e,r){return new t({type:"custom",check:"custom",fn:e,...G(r)})}var Zv=v(()=>{Ba();br()});var Bv=v(()=>{});function Sm(t,e){if(t instanceof Wo){let n=new nc(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 nc(e);return r.process(t),r.emit(t,e)}function Be(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 Be(s.element,r);case"object":{for(let o in s.shape)if(Be(s.shape[o],r))return!0;return!1}case"union":{for(let o of s.options)if(Be(o,r))return!0;return!1}case"intersection":return Be(s.left,r)||Be(s.right,r);case"tuple":{for(let o of s.items)if(Be(o,r))return!0;return!!(s.rest&&Be(s.rest,r))}case"record":return Be(s.keyType,r)||Be(s.valueType,r);case"map":return Be(s.keyType,r)||Be(s.valueType,r);case"set":return Be(s.valueType,r);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return Be(s.innerType,r);case"lazy":return Be(s.getter(),r);case"default":return Be(s.innerType,r);case"prefault":return Be(s.innerType,r);case"custom":return!1;case"transform":return!0;case"pipe":return Be(s.in,r)||Be(s.out,r);case"success":return!1;case"catch":return!1;default:}throw new Error(`Unknown schema type: ${s.type}`)}var nc,qv=v(()=>{Dp();br();nc=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??rn,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 f=a.schema;switch(s.type){case"string":{let p=f;p.type="string";let{minimum:h,maximum:g,format:y,patterns:_,contentEncoding:x}=e._zod.bag;if(typeof h=="number"&&(p.minLength=h),typeof g=="number"&&(p.maxLength=g),y&&(p.format=o[y]??y,p.format===""&&delete p.format),x&&(p.contentEncoding=x),_&&_.size>0){let S=[..._];S.length===1?p.pattern=S[0].source:S.length>1&&(a.schema.allOf=[...S.map(w=>({...this.target==="draft-7"?{type:"string"}:{},pattern:w.source}))])}break}case"number":{let p=f,{minimum:h,maximum:g,format:y,multipleOf:_,exclusiveMaximum:x,exclusiveMinimum:S}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof S=="number"&&(p.exclusiveMinimum=S),typeof h=="number"&&(p.minimum=h,typeof S=="number"&&(S>=h?delete p.minimum:delete p.exclusiveMinimum)),typeof x=="number"&&(p.exclusiveMaximum=x),typeof g=="number"&&(p.maximum=g,typeof x=="number"&&(x<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{let p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{let p=f,{minimum:h,maximum:g}=e._zod.bag;typeof h=="number"&&(p.minItems=h),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...l,path:[...l.path,"items"]});break}case"object":{let p=f;p.type="object",p.properties={};let h=s.shape;for(let _ in h)p.properties[_]=this.process(h[_],{...l,path:[...l.path,"properties",_]});let g=new Set(Object.keys(h)),y=new Set([...g].filter(_=>{let x=s.shape[_]._zod;return this.io==="input"?x.optin===void 0:x.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=f;p.anyOf=s.options.map((h,g)=>this.process(h,{...l,path:[...l.path,"anyOf",g]}));break}case"intersection":{let p=f,h=this.process(s.left,{...l,path:[...l.path,"allOf",0]}),g=this.process(s.right,{...l,path:[...l.path,"allOf",1]}),y=x=>"allOf"in x&&Object.keys(x).length===1,_=[...y(h)?h.allOf:[h],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{let p=f;p.type="array";let h=s.items.map((_,x)=>this.process(_,{...l,path:[...l.path,"prefixItems",x]}));if(this.target==="draft-2020-12"?p.prefixItems=h:p.items=h,s.rest){let _=this.process(s.rest,{...l,path:[...l.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}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=f;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=f,h=Lo(s.entries);h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),p.enum=h;break}case"literal":{let p=f,h=[];for(let g of s.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");h.push(Number(g))}else h.push(g);if(h.length!==0)if(h.length===1){let g=h[0];p.type=g===null?"null":typeof g,p.const=g}else h.every(g=>typeof g=="number")&&(p.type="number"),h.every(g=>typeof g=="string")&&(p.type="string"),h.every(g=>typeof g=="boolean")&&(p.type="string"),h.every(g=>g===null)&&(p.type="null"),p.enum=h;break}case"file":{let p=f,h={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(h.minLength=g),y!==void 0&&(h.maxLength=y),_?_.length===1?(h.contentMediaType=_[0],Object.assign(p,h)):p.anyOf=_.map(x=>({...h,contentMediaType:x})):Object.assign(p,h);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{let p=this.process(s.innerType,l);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"success":{let p=f;p.type="boolean";break}case"default":{this.process(s.innerType,l),a.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,l),a.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,l),a.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{let p=f,h=e._zod.pattern;if(!h)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=h.source;break}case"pipe":{let p=this.io==="input"?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,f.readOnly=!0;break}case"promise":{this.process(s.innerType,l),a.ref=s.innerType;break}case"optional":{this.process(s.innerType,l),a.ref=s.innerType;break}case"lazy":{let 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"&&Be(e)&&(delete a.schema.examples,delete a.schema.default),this.io==="input"&&a.schema._prefault&&((n=a.schema).default??(n.default=a.schema._prefault)),delete a.schema._prefault,this.seen.get(e).schema}emit(e,r){let n={cycles:r?.cycles??"ref",reused:r?.reused??"inline",external:r?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");let o=d=>{let l=this.target==="draft-2020-12"?"$defs":"definitions";if(n.external){let h=n.external.registry.get(d[0])?.id,g=n.external.uri??(_=>_);if(h)return{ref:g(h)};let y=d[1].defId??d[1].schema.id??`schema${this.counter++}`;return d[1].defId=y,{defId:y,ref:`${g("__shared")}#/${l}/${y}`}}if(d[1]===s)return{ref:"#"};let f=`#/${l}/`,p=d[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=d=>{if(d[1].schema.$ref)return;let l=d[1],{ref:m,defId:f}=o(d);l.def={...l.schema},f&&(l.defId=f);let p=l.schema;for(let h in p)delete p[h];p.$ref=m};if(n.cycles==="throw")for(let d of this.seen.entries()){let l=d[1];if(l.cycle)throw new Error(`Cycle detected: #/${l.cycle?.join("/")}/<root>
45
59
 
46
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let l of this.seen.entries()){let d=l[1];if(e===l[0]){i(l);continue}if(n.external){let f=n.external.registry.get(l[0])?.id;if(e!==l[0]&&f){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&n.reused==="ref"){i(l);continue}}let a=(l,d)=>{let p=this.seen.get(l),f=p.def??p.schema,m={...f};if(p.ref===null)return;let h=p.ref;if(p.ref=null,h){a(h,d);let g=this.seen.get(h).schema;g.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,m))}p.isParent||this.override({zodSchema:l,jsonSchema:f,path:p.path??[]})};for(let l of[...this.seen.entries()].reverse())a(l[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let l=n.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(l)}Object.assign(c,o.def);let u=n.external?.defs??{};for(let l of this.seen.entries()){let d=l[1];d.def&&d.defId&&(u[d.defId]=d.def)}n.external||Object.keys(u).length>0&&(this.target==="draft-2020-12"?c.$defs=u:c.definitions=u);try{return JSON.parse(JSON.stringify(c))}catch{throw new Error("Error converting schema to JSON.")}}}});var Ux=v(()=>{});var it=v(()=>{So();Jl();Hl();Rx();wa();rd();lr();ka();Ca();Bd();td();Lx();Mx();Fx();Ux()});var Ap=v(()=>{it()});function Np(t,e){let r={type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},...oe.normalizeParams(e)};return new yR(r)}var _R,yR,Zx=v(()=>{it();it();Ap();_R=S("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");ge.init(t,e),t.def=e,t.parse=(r,n)=>Bl(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>jn(t,r,n),t.parseAsync=async(r,n)=>Wl(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Dn(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)=>bt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),yR=S("ZodMiniObject",(t,e)=>{Pa.init(t,e),_R.init(t,e),oe.defineLazy(t,"shape",()=>e.shape)})});var Hx=v(()=>{});var qx=v(()=>{});var Bx=v(()=>{});var Vx=v(()=>{it();Ap();Zx();Hx();it();Ca();qx();Bx()});var Wx=v(()=>{Vx()});var zp=v(()=>{Wx()});function zt(t){return!!t._zod}function Fn(t){let e=Object.values(t);if(e.length===0)return Np({});let r=e.every(zt),n=e.every(o=>!zt(o));if(r)return Np(t);if(n)return Cl(t);throw new Error("Mixed Zod versions detected in object shape.")}function Jr(t,e){return zt(t)?jn(t,e):t.safeParse(e)}async function Ma(t,e){return zt(t)?await Dn(t,e):await t.safeParseAsync(e)}function Yr(t){if(!t)return;let e;if(zt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function Eo(t){if(t){if(typeof t=="object"){let e=t,r=t;if(!e._def&&!r._zod){let n=Object.values(t);if(n.length>0&&n.every(o=>typeof o=="object"&&o!==null&&(o._def!==void 0||o._zod!==void 0||typeof o.parse=="function")))return Fn(t)}}if(zt(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 La(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 Kx(t){return t.description}function Jx(t){if(zt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function Fa(t){if(zt(t)){let s=t._zod?.def;if(s){if(s.value!==void 0)return s.value;if(Array.isArray(s.values)&&s.values.length>0)return s.values[0]}}let r=t._def;if(r){if(r.value!==void 0)return r.value;if(Array.isArray(r.values)&&r.values.length>0)return r.values[0]}let n=t.value;if(n!==void 0)return n}var Ls=v(()=>{Es();zp()});var jp=v(()=>{it()});var Fs={};Ze(Fs,{ZodISODate:()=>Xx,ZodISODateTime:()=>Yx,ZodISODuration:()=>ev,ZodISOTime:()=>Qx,date:()=>Mp,datetime:()=>Dp,duration:()=>Fp,time:()=>Lp});function Dp(t){return Ax(Yx,t)}function Mp(t){return Nx(Xx,t)}function Lp(t){return zx(Qx,t)}function Fp(t){return jx(ev,t)}var Yx,Xx,Qx,ev,Up=v(()=>{it();Zp();Yx=S("ZodISODateTime",(t,e)=>{wx.init(t,e),Ce.init(t,e)});Xx=S("ZodISODate",(t,e)=>{$x.init(t,e),Ce.init(t,e)});Qx=S("ZodISOTime",(t,e)=>{Ex.init(t,e),Ce.init(t,e)});ev=S("ZodISODuration",(t,e)=>{Tx.init(t,e),Ce.init(t,e)})});var tv,wZ,Us,Hp=v(()=>{it();it();tv=(t,e)=>{ba.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Zl(t,r)},flatten:{value:r=>Ul(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},wZ=S("ZodError",tv),Us=S("ZodError",tv,{Parent:Error})});var rv,nv,ov,sv,qp=v(()=>{it();Hp();rv=ql(Us),nv=Vl(Us),ov=Gl(Us),sv=Kl(Us)});function b(t){return Vd(PR,t)}function me(t){return fp(lv,t)}function av(t){return hp(VR,t)}function Be(t){return gp(WR,t)}function dv(t){return _p(GR,t)}function Oe(){return yp(KR)}function YR(t){return xp(JR,t)}function se(t,e){return Dx(XR,t,e)}function A(t,e){let r={type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},...oe.normalizeParams(e)};return new pv(r)}function at(t,e){return new pv({type:"object",get shape(){return oe.assignProp(this,"shape",{...t}),this.shape},catchall:Oe(),...oe.normalizeParams(e)})}function $e(t,e){return new mv({type:"union",options:t,...oe.normalizeParams(e)})}function Wp(t,e,r){return new QR({type:"union",options:e,discriminator:t,...oe.normalizeParams(r)})}function Za(t,e){return new eC({type:"intersection",left:t,right:e})}function ke(t,e,r){return new tC({type:"record",keyType:t,valueType:e,...oe.normalizeParams(r)})}function ht(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Bp({type:"enum",entries:r,...oe.normalizeParams(e)})}function L(t,e){return new rC({type:"literal",values:Array.isArray(t)?t:[t],...oe.normalizeParams(e)})}function fv(t){return new nC({type:"transform",transform:t})}function Ie(t){return new hv({type:"optional",innerType:t})}function cv(t){return new oC({type:"nullable",innerType:t})}function iC(t,e){return new sC({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function cC(t,e){return new aC({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function uC(t,e){return new gv({type:"nonoptional",innerType:t,...oe.normalizeParams(e)})}function dC(t,e){return new lC({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Vp(t,e){return new pC({type:"pipe",in:t,out:e})}function fC(t){return new mC({type:"readonly",innerType:t})}function hC(t){let e=new Ge({check:"custom"});return e._zod.check=t,e}function yv(t,e){return Cp(_v,t??(()=>!0),e)}function gC(t,e={}){return Op(_v,t,e)}function _C(t){let e=hC(r=>(r.addIssue=n=>{if(typeof n=="string")r.issues.push(oe.issue(n,r.value,e._zod.def));else{let o=n;o.fatal&&(o.continue=!1),o.code??(o.code="custom"),o.input??(o.input=r.value),o.inst??(o.inst=e),o.continue??(o.continue=!e._zod.def.abort),r.issues.push(oe.issue(o))}},t(r.value,r)));return e}function Gp(t,e){return Vp(fv(t),e)}var ze,uv,PR,Ce,RR,iv,Ua,CR,OR,IR,AR,NR,zR,jR,DR,MR,LR,FR,UR,ZR,HR,qR,BR,lv,VR,WR,GR,KR,JR,XR,pv,mv,QR,eC,tC,Bp,rC,nC,hv,oC,sC,aC,gv,lC,pC,mC,_v,Zp=v(()=>{it();it();jp();Up();qp();ze=S("ZodType",(t,e)=>(ge.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)=>bt(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>rv(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>ov(t,r,n),t.parseAsync=async(r,n)=>nv(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>sv(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(gC(r,n)),t.superRefine=r=>t.check(_C(r)),t.overwrite=r=>t.check(Mn(r)),t.optional=()=>Ie(t),t.nullable=()=>cv(t),t.nullish=()=>Ie(cv(t)),t.nonoptional=r=>uC(t,r),t.array=()=>se(t),t.or=r=>$e([t,r]),t.and=r=>Za(t,r),t.transform=r=>Vp(t,fv(r)),t.default=r=>iC(t,r),t.prefault=r=>cC(t,r),t.catch=r=>dC(t,r),t.pipe=r=>Vp(t,r),t.readonly=()=>fC(t),t.describe=r=>{let n=t.clone();return Kr.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return Kr.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return Kr.get(t);let n=t.clone();return Kr.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),uv=S("_ZodString",(t,e)=>{zs.init(t,e),ze.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(vp(...n)),t.includes=(...n)=>t.check(kp(...n)),t.startsWith=(...n)=>t.check(wp(...n)),t.endsWith=(...n)=>t.check($p(...n)),t.min=(...n)=>t.check($o(...n)),t.max=(...n)=>t.check(za(...n)),t.length=(...n)=>t.check(ja(...n)),t.nonempty=(...n)=>t.check($o(1,...n)),t.lowercase=n=>t.check(bp(n)),t.uppercase=n=>t.check(Sp(n)),t.trim=()=>t.check(Tp()),t.normalize=(...n)=>t.check(Ep(...n)),t.toLowerCase=()=>t.check(Pp()),t.toUpperCase=()=>t.check(Rp())}),PR=S("ZodString",(t,e)=>{zs.init(t,e),uv.init(t,e),t.email=r=>t.check(Wd(RR,r)),t.url=r=>t.check(Xd(CR,r)),t.jwt=r=>t.check(mp(BR,r)),t.emoji=r=>t.check(Qd(OR,r)),t.guid=r=>t.check(Oa(iv,r)),t.uuid=r=>t.check(Gd(Ua,r)),t.uuidv4=r=>t.check(Kd(Ua,r)),t.uuidv6=r=>t.check(Jd(Ua,r)),t.uuidv7=r=>t.check(Yd(Ua,r)),t.nanoid=r=>t.check(ep(IR,r)),t.guid=r=>t.check(Oa(iv,r)),t.cuid=r=>t.check(tp(AR,r)),t.cuid2=r=>t.check(rp(NR,r)),t.ulid=r=>t.check(np(zR,r)),t.base64=r=>t.check(lp(ZR,r)),t.base64url=r=>t.check(dp(HR,r)),t.xid=r=>t.check(op(jR,r)),t.ksuid=r=>t.check(sp(DR,r)),t.ipv4=r=>t.check(ip(MR,r)),t.ipv6=r=>t.check(ap(LR,r)),t.cidrv4=r=>t.check(cp(FR,r)),t.cidrv6=r=>t.check(up(UR,r)),t.e164=r=>t.check(pp(qR,r)),t.datetime=r=>t.check(Dp(r)),t.date=r=>t.check(Mp(r)),t.time=r=>t.check(Lp(r)),t.duration=r=>t.check(Fp(r))});Ce=S("ZodStringFormat",(t,e)=>{Se.init(t,e),uv.init(t,e)}),RR=S("ZodEmail",(t,e)=>{id.init(t,e),Ce.init(t,e)}),iv=S("ZodGUID",(t,e)=>{od.init(t,e),Ce.init(t,e)}),Ua=S("ZodUUID",(t,e)=>{sd.init(t,e),Ce.init(t,e)}),CR=S("ZodURL",(t,e)=>{ad.init(t,e),Ce.init(t,e)}),OR=S("ZodEmoji",(t,e)=>{cd.init(t,e),Ce.init(t,e)}),IR=S("ZodNanoID",(t,e)=>{ud.init(t,e),Ce.init(t,e)}),AR=S("ZodCUID",(t,e)=>{ld.init(t,e),Ce.init(t,e)}),NR=S("ZodCUID2",(t,e)=>{dd.init(t,e),Ce.init(t,e)}),zR=S("ZodULID",(t,e)=>{pd.init(t,e),Ce.init(t,e)}),jR=S("ZodXID",(t,e)=>{md.init(t,e),Ce.init(t,e)}),DR=S("ZodKSUID",(t,e)=>{fd.init(t,e),Ce.init(t,e)}),MR=S("ZodIPv4",(t,e)=>{hd.init(t,e),Ce.init(t,e)}),LR=S("ZodIPv6",(t,e)=>{gd.init(t,e),Ce.init(t,e)}),FR=S("ZodCIDRv4",(t,e)=>{_d.init(t,e),Ce.init(t,e)}),UR=S("ZodCIDRv6",(t,e)=>{yd.init(t,e),Ce.init(t,e)}),ZR=S("ZodBase64",(t,e)=>{xd.init(t,e),Ce.init(t,e)}),HR=S("ZodBase64URL",(t,e)=>{vd.init(t,e),Ce.init(t,e)}),qR=S("ZodE164",(t,e)=>{bd.init(t,e),Ce.init(t,e)}),BR=S("ZodJWT",(t,e)=>{Sd.init(t,e),Ce.init(t,e)}),lv=S("ZodNumber",(t,e)=>{Ta.init(t,e),ze.init(t,e),t.gt=(n,o)=>t.check(Aa(n,o)),t.gte=(n,o)=>t.check(Ms(n,o)),t.min=(n,o)=>t.check(Ms(n,o)),t.lt=(n,o)=>t.check(Ia(n,o)),t.lte=(n,o)=>t.check(Ds(n,o)),t.max=(n,o)=>t.check(Ds(n,o)),t.int=n=>t.check(av(n)),t.safe=n=>t.check(av(n)),t.positive=n=>t.check(Aa(0,n)),t.nonnegative=n=>t.check(Ms(0,n)),t.negative=n=>t.check(Ia(0,n)),t.nonpositive=n=>t.check(Ds(0,n)),t.multipleOf=(n,o)=>t.check(Na(n,o)),t.step=(n,o)=>t.check(Na(n,o)),t.finite=()=>t;let r=t._zod.bag;t.minValue=Math.max(r.minimum??Number.NEGATIVE_INFINITY,r.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(r.maximum??Number.POSITIVE_INFINITY,r.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(r.format??"").includes("int")||Number.isSafeInteger(r.multipleOf??.5),t.isFinite=!0,t.format=r.format??null});VR=S("ZodNumberFormat",(t,e)=>{kd.init(t,e),lv.init(t,e)});WR=S("ZodBoolean",(t,e)=>{wd.init(t,e),ze.init(t,e)});GR=S("ZodNull",(t,e)=>{$d.init(t,e),ze.init(t,e)});KR=S("ZodUnknown",(t,e)=>{Ed.init(t,e),ze.init(t,e)});JR=S("ZodNever",(t,e)=>{Td.init(t,e),ze.init(t,e)});XR=S("ZodArray",(t,e)=>{Pd.init(t,e),ze.init(t,e),t.element=e.element,t.min=(r,n)=>t.check($o(r,n)),t.nonempty=r=>t.check($o(1,r)),t.max=(r,n)=>t.check(za(r,n)),t.length=(r,n)=>t.check(ja(r,n)),t.unwrap=()=>t.element});pv=S("ZodObject",(t,e)=>{Pa.init(t,e),ze.init(t,e),oe.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>ht(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Oe()}),t.loose=()=>t.clone({...t._zod.def,catchall:Oe()}),t.strict=()=>t.clone({...t._zod.def,catchall:YR()}),t.strip=()=>t.clone({...t._zod.def,catchall:void 0}),t.extend=r=>oe.extend(t,r),t.merge=r=>oe.merge(t,r),t.pick=r=>oe.pick(t,r),t.omit=r=>oe.omit(t,r),t.partial=(...r)=>oe.partial(hv,t,r[0]),t.required=(...r)=>oe.required(gv,t,r[0])});mv=S("ZodUnion",(t,e)=>{Ra.init(t,e),ze.init(t,e),t.options=e.options});QR=S("ZodDiscriminatedUnion",(t,e)=>{mv.init(t,e),Rd.init(t,e)});eC=S("ZodIntersection",(t,e)=>{Cd.init(t,e),ze.init(t,e)});tC=S("ZodRecord",(t,e)=>{Od.init(t,e),ze.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Bp=S("ZodEnum",(t,e)=>{Id.init(t,e),ze.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Bp({...e,checks:[],...oe.normalizeParams(o),entries:s})},t.exclude=(n,o)=>{let s={...e.entries};for(let i of n)if(r.has(i))delete s[i];else throw new Error(`Key ${i} not found in enum`);return new Bp({...e,checks:[],...oe.normalizeParams(o),entries:s})}});rC=S("ZodLiteral",(t,e)=>{Ad.init(t,e),ze.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]}})});nC=S("ZodTransform",(t,e)=>{Nd.init(t,e),ze.init(t,e),t._zod.parse=(r,n)=>{r.addIssue=s=>{if(typeof s=="string")r.issues.push(oe.issue(s,r.value,e));else{let i=s;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=t),i.continue??(i.continue=!0),r.issues.push(oe.issue(i))}};let o=e.transform(r.value,r);return o instanceof Promise?o.then(s=>(r.value=s,r)):(r.value=o,r)}});hv=S("ZodOptional",(t,e)=>{zd.init(t,e),ze.init(t,e),t.unwrap=()=>t._zod.def.innerType});oC=S("ZodNullable",(t,e)=>{jd.init(t,e),ze.init(t,e),t.unwrap=()=>t._zod.def.innerType});sC=S("ZodDefault",(t,e)=>{Dd.init(t,e),ze.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});aC=S("ZodPrefault",(t,e)=>{Md.init(t,e),ze.init(t,e),t.unwrap=()=>t._zod.def.innerType});gv=S("ZodNonOptional",(t,e)=>{Ld.init(t,e),ze.init(t,e),t.unwrap=()=>t._zod.def.innerType});lC=S("ZodCatch",(t,e)=>{Fd.init(t,e),ze.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});pC=S("ZodPipe",(t,e)=>{Ud.init(t,e),ze.init(t,e),t.in=e.in,t.out=e.out});mC=S("ZodReadonly",(t,e)=>{Zd.init(t,e),ze.init(t,e)});_v=S("ZodCustom",(t,e)=>{Hd.init(t,e),ze.init(t,e)})});var xv=v(()=>{});var vv=v(()=>{});var bv=v(()=>{it();Zp();jp();Hp();qp();xv();it();Ox();Ca();Up();vv();vt(Cx())});var Sv=v(()=>{bv()});var kv=v(()=>{Sv()});function Fv(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Uv(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Jp,wv,Xr,qa,qe,$v,Ev,FZ,vC,bC,Yp,St,Zs,Tv,Ke,jt,Dt,Je,Ba,Pv,Xp,Rv,Cv,Qp,Hs,Z,em,Ov,Iv,UZ,Va,SC,Wa,kC,qs,To,Av,wC,$C,EC,TC,PC,RC,tm,CC,OC,rm,Ga,IC,AC,Ka,NC,Bs,Vs,zC,Ws,Po,jC,Gs,Ja,Ya,Xa,ZZ,Qa,ec,tc,Nv,zv,jv,nm,Dv,Ks,Ro,Mv,DC,Co,MC,Oo,LC,om,FC,rc,UC,ZC,HC,qC,BC,VC,WC,GC,KC,JC,Io,YC,XC,nc,sm,im,am,QC,eO,tO,cm,rO,nO,oO,sO,iO,Lv,oc,aO,sc,HZ,cO,Ao,uO,qZ,Js,lO,um,dO,pO,mO,fO,hO,gO,_O,Ha,yO,xO,vO,Ys,lm,bO,SO,kO,wO,$O,EO,TO,PO,RO,CO,OO,IO,AO,NO,zO,jO,DO,MO,No,LO,FO,UO,ic,ZO,HO,qO,dm,BO,BZ,VZ,WZ,GZ,KZ,JZ,D,Kp,Un=v(()=>{kv();Jp="2025-11-25",wv=[Jp,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],Xr="io.modelcontextprotocol/related-task",qa="2.0",qe=yv(t=>t!==null&&(typeof t=="object"||typeof t=="function")),$v=$e([b(),me().int()]),Ev=b(),FZ=at({ttl:me().optional(),pollInterval:me().optional()}),vC=A({ttl:me().optional()}),bC=A({taskId:b()}),Yp=at({progressToken:$v.optional(),[Xr]:bC.optional()}),St=A({_meta:Yp.optional()}),Zs=St.extend({task:vC.optional()}),Tv=t=>Zs.safeParse(t).success,Ke=A({method:b(),params:St.loose().optional()}),jt=A({_meta:Yp.optional()}),Dt=A({method:b(),params:jt.loose().optional()}),Je=at({_meta:Yp.optional()}),Ba=$e([b(),me().int()]),Pv=A({jsonrpc:L(qa),id:Ba,...Ke.shape}).strict(),Xp=t=>Pv.safeParse(t).success,Rv=A({jsonrpc:L(qa),...Dt.shape}).strict(),Cv=t=>Rv.safeParse(t).success,Qp=A({jsonrpc:L(qa),id:Ba,result:Je}).strict(),Hs=t=>Qp.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"})(Z||(Z={}));em=A({jsonrpc:L(qa),id:Ba.optional(),error:A({code:me().int(),message:b(),data:Oe().optional()})}).strict(),Ov=t=>em.safeParse(t).success,Iv=$e([Pv,Rv,Qp,em]),UZ=$e([Qp,em]),Va=Je.strict(),SC=jt.extend({requestId:Ba.optional(),reason:b().optional()}),Wa=Dt.extend({method:L("notifications/cancelled"),params:SC}),kC=A({src:b(),mimeType:b().optional(),sizes:se(b()).optional(),theme:ht(["light","dark"]).optional()}),qs=A({icons:se(kC).optional()}),To=A({name:b(),title:b().optional()}),Av=To.extend({...To.shape,...qs.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),wC=Za(A({applyDefaults:Be().optional()}),ke(b(),Oe())),$C=Gp(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,Za(A({form:wC.optional(),url:qe.optional()}),ke(b(),Oe()).optional())),EC=at({list:qe.optional(),cancel:qe.optional(),requests:at({sampling:at({createMessage:qe.optional()}).optional(),elicitation:at({create:qe.optional()}).optional()}).optional()}),TC=at({list:qe.optional(),cancel:qe.optional(),requests:at({tools:at({call:qe.optional()}).optional()}).optional()}),PC=A({experimental:ke(b(),qe).optional(),sampling:A({context:qe.optional(),tools:qe.optional()}).optional(),elicitation:$C.optional(),roots:A({listChanged:Be().optional()}).optional(),tasks:EC.optional(),extensions:ke(b(),qe).optional()}),RC=St.extend({protocolVersion:b(),capabilities:PC,clientInfo:Av}),tm=Ke.extend({method:L("initialize"),params:RC}),CC=A({experimental:ke(b(),qe).optional(),logging:qe.optional(),completions:qe.optional(),prompts:A({listChanged:Be().optional()}).optional(),resources:A({subscribe:Be().optional(),listChanged:Be().optional()}).optional(),tools:A({listChanged:Be().optional()}).optional(),tasks:TC.optional(),extensions:ke(b(),qe).optional()}),OC=Je.extend({protocolVersion:b(),capabilities:CC,serverInfo:Av,instructions:b().optional()}),rm=Dt.extend({method:L("notifications/initialized"),params:jt.optional()}),Ga=Ke.extend({method:L("ping"),params:St.optional()}),IC=A({progress:me(),total:Ie(me()),message:Ie(b())}),AC=A({...jt.shape,...IC.shape,progressToken:$v}),Ka=Dt.extend({method:L("notifications/progress"),params:AC}),NC=St.extend({cursor:Ev.optional()}),Bs=Ke.extend({params:NC.optional()}),Vs=Je.extend({nextCursor:Ev.optional()}),zC=ht(["working","input_required","completed","failed","cancelled"]),Ws=A({taskId:b(),status:zC,ttl:$e([me(),dv()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:Ie(me()),statusMessage:Ie(b())}),Po=Je.extend({task:Ws}),jC=jt.merge(Ws),Gs=Dt.extend({method:L("notifications/tasks/status"),params:jC}),Ja=Ke.extend({method:L("tasks/get"),params:St.extend({taskId:b()})}),Ya=Je.merge(Ws),Xa=Ke.extend({method:L("tasks/result"),params:St.extend({taskId:b()})}),ZZ=Je.loose(),Qa=Bs.extend({method:L("tasks/list")}),ec=Vs.extend({tasks:se(Ws)}),tc=Ke.extend({method:L("tasks/cancel"),params:St.extend({taskId:b()})}),Nv=Je.merge(Ws),zv=A({uri:b(),mimeType:Ie(b()),_meta:ke(b(),Oe()).optional()}),jv=zv.extend({text:b()}),nm=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Dv=zv.extend({blob:nm}),Ks=ht(["user","assistant"]),Ro=A({audience:se(Ks).optional(),priority:me().min(0).max(1).optional(),lastModified:Fs.datetime({offset:!0}).optional()}),Mv=A({...To.shape,...qs.shape,uri:b(),description:Ie(b()),mimeType:Ie(b()),size:Ie(me()),annotations:Ro.optional(),_meta:Ie(at({}))}),DC=A({...To.shape,...qs.shape,uriTemplate:b(),description:Ie(b()),mimeType:Ie(b()),annotations:Ro.optional(),_meta:Ie(at({}))}),Co=Bs.extend({method:L("resources/list")}),MC=Vs.extend({resources:se(Mv)}),Oo=Bs.extend({method:L("resources/templates/list")}),LC=Vs.extend({resourceTemplates:se(DC)}),om=St.extend({uri:b()}),FC=om,rc=Ke.extend({method:L("resources/read"),params:FC}),UC=Je.extend({contents:se($e([jv,Dv]))}),ZC=Dt.extend({method:L("notifications/resources/list_changed"),params:jt.optional()}),HC=om,qC=Ke.extend({method:L("resources/subscribe"),params:HC}),BC=om,VC=Ke.extend({method:L("resources/unsubscribe"),params:BC}),WC=jt.extend({uri:b()}),GC=Dt.extend({method:L("notifications/resources/updated"),params:WC}),KC=A({name:b(),description:Ie(b()),required:Ie(Be())}),JC=A({...To.shape,...qs.shape,description:Ie(b()),arguments:Ie(se(KC)),_meta:Ie(at({}))}),Io=Bs.extend({method:L("prompts/list")}),YC=Vs.extend({prompts:se(JC)}),XC=St.extend({name:b(),arguments:ke(b(),b()).optional()}),nc=Ke.extend({method:L("prompts/get"),params:XC}),sm=A({type:L("text"),text:b(),annotations:Ro.optional(),_meta:ke(b(),Oe()).optional()}),im=A({type:L("image"),data:nm,mimeType:b(),annotations:Ro.optional(),_meta:ke(b(),Oe()).optional()}),am=A({type:L("audio"),data:nm,mimeType:b(),annotations:Ro.optional(),_meta:ke(b(),Oe()).optional()}),QC=A({type:L("tool_use"),name:b(),id:b(),input:ke(b(),Oe()),_meta:ke(b(),Oe()).optional()}),eO=A({type:L("resource"),resource:$e([jv,Dv]),annotations:Ro.optional(),_meta:ke(b(),Oe()).optional()}),tO=Mv.extend({type:L("resource_link")}),cm=$e([sm,im,am,tO,eO]),rO=A({role:Ks,content:cm}),nO=Je.extend({description:b().optional(),messages:se(rO)}),oO=Dt.extend({method:L("notifications/prompts/list_changed"),params:jt.optional()}),sO=A({title:b().optional(),readOnlyHint:Be().optional(),destructiveHint:Be().optional(),idempotentHint:Be().optional(),openWorldHint:Be().optional()}),iO=A({taskSupport:ht(["required","optional","forbidden"]).optional()}),Lv=A({...To.shape,...qs.shape,description:b().optional(),inputSchema:A({type:L("object"),properties:ke(b(),qe).optional(),required:se(b()).optional()}).catchall(Oe()),outputSchema:A({type:L("object"),properties:ke(b(),qe).optional(),required:se(b()).optional()}).catchall(Oe()).optional(),annotations:sO.optional(),execution:iO.optional(),_meta:ke(b(),Oe()).optional()}),oc=Bs.extend({method:L("tools/list")}),aO=Vs.extend({tools:se(Lv)}),sc=Je.extend({content:se(cm).default([]),structuredContent:ke(b(),Oe()).optional(),isError:Be().optional()}),HZ=sc.or(Je.extend({toolResult:Oe()})),cO=Zs.extend({name:b(),arguments:ke(b(),Oe()).optional()}),Ao=Ke.extend({method:L("tools/call"),params:cO}),uO=Dt.extend({method:L("notifications/tools/list_changed"),params:jt.optional()}),qZ=A({autoRefresh:Be().default(!0),debounceMs:me().int().nonnegative().default(300)}),Js=ht(["debug","info","notice","warning","error","critical","alert","emergency"]),lO=St.extend({level:Js}),um=Ke.extend({method:L("logging/setLevel"),params:lO}),dO=jt.extend({level:Js,logger:b().optional(),data:Oe()}),pO=Dt.extend({method:L("notifications/message"),params:dO}),mO=A({name:b().optional()}),fO=A({hints:se(mO).optional(),costPriority:me().min(0).max(1).optional(),speedPriority:me().min(0).max(1).optional(),intelligencePriority:me().min(0).max(1).optional()}),hO=A({mode:ht(["auto","required","none"]).optional()}),gO=A({type:L("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:se(cm).default([]),structuredContent:A({}).loose().optional(),isError:Be().optional(),_meta:ke(b(),Oe()).optional()}),_O=Wp("type",[sm,im,am]),Ha=Wp("type",[sm,im,am,QC,gO]),yO=A({role:Ks,content:$e([Ha,se(Ha)]),_meta:ke(b(),Oe()).optional()}),xO=Zs.extend({messages:se(yO),modelPreferences:fO.optional(),systemPrompt:b().optional(),includeContext:ht(["none","thisServer","allServers"]).optional(),temperature:me().optional(),maxTokens:me().int(),stopSequences:se(b()).optional(),metadata:qe.optional(),tools:se(Lv).optional(),toolChoice:hO.optional()}),vO=Ke.extend({method:L("sampling/createMessage"),params:xO}),Ys=Je.extend({model:b(),stopReason:Ie(ht(["endTurn","stopSequence","maxTokens"]).or(b())),role:Ks,content:_O}),lm=Je.extend({model:b(),stopReason:Ie(ht(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:Ks,content:$e([Ha,se(Ha)])}),bO=A({type:L("boolean"),title:b().optional(),description:b().optional(),default:Be().optional()}),SO=A({type:L("string"),title:b().optional(),description:b().optional(),minLength:me().optional(),maxLength:me().optional(),format:ht(["email","uri","date","date-time"]).optional(),default:b().optional()}),kO=A({type:ht(["number","integer"]),title:b().optional(),description:b().optional(),minimum:me().optional(),maximum:me().optional(),default:me().optional()}),wO=A({type:L("string"),title:b().optional(),description:b().optional(),enum:se(b()),default:b().optional()}),$O=A({type:L("string"),title:b().optional(),description:b().optional(),oneOf:se(A({const:b(),title:b()})),default:b().optional()}),EO=A({type:L("string"),title:b().optional(),description:b().optional(),enum:se(b()),enumNames:se(b()).optional(),default:b().optional()}),TO=$e([wO,$O]),PO=A({type:L("array"),title:b().optional(),description:b().optional(),minItems:me().optional(),maxItems:me().optional(),items:A({type:L("string"),enum:se(b())}),default:se(b()).optional()}),RO=A({type:L("array"),title:b().optional(),description:b().optional(),minItems:me().optional(),maxItems:me().optional(),items:A({anyOf:se(A({const:b(),title:b()}))}),default:se(b()).optional()}),CO=$e([PO,RO]),OO=$e([EO,TO,CO]),IO=$e([OO,bO,SO,kO]),AO=Zs.extend({mode:L("form").optional(),message:b(),requestedSchema:A({type:L("object"),properties:ke(b(),IO),required:se(b()).optional()})}),NO=Zs.extend({mode:L("url"),message:b(),elicitationId:b(),url:b().url()}),zO=$e([AO,NO]),jO=Ke.extend({method:L("elicitation/create"),params:zO}),DO=jt.extend({elicitationId:b()}),MO=Dt.extend({method:L("notifications/elicitation/complete"),params:DO}),No=Je.extend({action:ht(["accept","decline","cancel"]),content:Gp(t=>t===null?void 0:t,ke(b(),$e([b(),me(),Be(),se(b())])).optional())}),LO=A({type:L("ref/resource"),uri:b()}),FO=A({type:L("ref/prompt"),name:b()}),UO=St.extend({ref:$e([FO,LO]),argument:A({name:b(),value:b()}),context:A({arguments:ke(b(),b()).optional()}).optional()}),ic=Ke.extend({method:L("completion/complete"),params:UO});ZO=Je.extend({completion:at({values:se(b()).max(100),total:Ie(me().int()),hasMore:Ie(Be())})}),HO=A({uri:b().startsWith("file://"),name:b().optional(),_meta:ke(b(),Oe()).optional()}),qO=Ke.extend({method:L("roots/list"),params:St.optional()}),dm=Je.extend({roots:se(HO)}),BO=Dt.extend({method:L("notifications/roots/list_changed"),params:jt.optional()}),BZ=$e([Ga,tm,ic,um,nc,Io,Co,Oo,rc,qC,VC,Ao,oc,Ja,Xa,Qa,tc]),VZ=$e([Wa,Ka,rm,BO,Gs]),WZ=$e([Va,Ys,lm,No,dm,Ya,ec,Po]),GZ=$e([Ga,vO,jO,qO,Ja,Xa,Qa,tc]),KZ=$e([Wa,Ka,pO,GC,ZC,uO,oO,Gs,MO]),JZ=$e([Va,OC,ZO,nO,YC,MC,LC,UC,sc,aO,Ya,ec,Po]),D=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===Z.UrlElicitationRequired&&n){let o=n;if(o.elicitations)return new Kp(o.elicitations,r)}return new t(e,r,n)}},Kp=class extends D{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(Z.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function Qr(t){return t==="completed"||t==="failed"||t==="cancelled"}var Zv=v(()=>{});var qv,Hv,Bv,ac=v(()=>{qv=Symbol("Let zodToJsonSchema decide on which parser to use"),Hv={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"},Bv=t=>typeof t=="string"?{...Hv,name:t}:{...Hv,...t}});var Vv,pm=v(()=>{ac();Vv=t=>{let e=Bv(t),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([n,o])=>[o._def,{def:o._def,path:[...e.basePath,e.definitionPath,n],jsonSchema:void 0}]))}}});function mm(t,e,r,n){n?.errorMessages&&r&&(t.errorMessage={...t.errorMessage,[e]:r})}function ie(t,e,r,n,o){t[e]=r,mm(t,e,n,o)}var en=v(()=>{});var cc,uc=v(()=>{cc=(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 Ae(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?cc(e,t.currentPath):e.join("/")}}var Mt=v(()=>{uc()});function Wv(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==T.ZodAny&&(r.items=V(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ie(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ie(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ie(r,"minItems",t.exactLength.value,t.exactLength.message,e),ie(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var fm=v(()=>{Es();en();Ue()});function Gv(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?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}var hm=v(()=>{en()});function Kv(){return{type:"boolean"}}var gm=v(()=>{});function lc(t,e){return V(t.type._def,e)}var dc=v(()=>{Ue()});var Jv,_m=v(()=>{Ue();Jv=(t,e)=>V(t.innerType._def,e)});function ym(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((o,s)=>ym(t,e,o))};switch(n){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return VO(t,e)}}var VO,xm=v(()=>{en();VO=(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":ie(r,"minimum",n.value,n.message,e);break;case"max":ie(r,"maximum",n.value,n.message,e);break}return r}});function Yv(t,e){return{...V(t.innerType._def,e),default:t.defaultValue()}}var vm=v(()=>{Ue()});function Xv(t,e){return e.effectStrategy==="input"?V(t.schema._def,e):Ae(e)}var bm=v(()=>{Ue();Mt()});function Qv(t){return{type:"string",enum:Array.from(t.values)}}var Sm=v(()=>{});function eb(t,e){let r=[V(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),V(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s),n=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,o=[];return r.forEach(s=>{if(WO(s))o.push(...s.allOf),s.unevaluatedProperties===void 0&&(n=void 0);else{let i=s;if("additionalProperties"in s&&s.additionalProperties===!1){let{additionalProperties:a,...c}=s;i=c}else n=void 0;o.push(i)}}),o.length?{allOf:o,...n}:void 0}var WO,km=v(()=>{Ue();WO=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function tb(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 wm=v(()=>{});function pc(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ie(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":Yt(r,"email",n.message,e);break;case"format:idn-email":Yt(r,"idn-email",n.message,e);break;case"pattern:zod":ct(r,Jt.email,n.message,e);break}break;case"url":Yt(r,"uri",n.message,e);break;case"uuid":Yt(r,"uuid",n.message,e);break;case"regex":ct(r,n.regex,n.message,e);break;case"cuid":ct(r,Jt.cuid,n.message,e);break;case"cuid2":ct(r,Jt.cuid2,n.message,e);break;case"startsWith":ct(r,RegExp(`^${Em(n.value,e)}`),n.message,e);break;case"endsWith":ct(r,RegExp(`${Em(n.value,e)}$`),n.message,e);break;case"datetime":Yt(r,"date-time",n.message,e);break;case"date":Yt(r,"date",n.message,e);break;case"time":Yt(r,"time",n.message,e);break;case"duration":Yt(r,"duration",n.message,e);break;case"length":ie(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ie(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{ct(r,RegExp(Em(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&Yt(r,"ipv4",n.message,e),n.version!=="v4"&&Yt(r,"ipv6",n.message,e);break}case"base64url":ct(r,Jt.base64url,n.message,e);break;case"jwt":ct(r,Jt.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&ct(r,Jt.ipv4Cidr,n.message,e),n.version!=="v4"&&ct(r,Jt.ipv6Cidr,n.message,e);break}case"emoji":ct(r,Jt.emoji(),n.message,e);break;case"ulid":{ct(r,Jt.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Yt(r,"binary",n.message,e);break}case"contentEncoding:base64":{ie(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{ct(r,Jt.base64,n.message,e);break}}break}case"nanoid":ct(r,Jt.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Em(t,e){return e.patternStrategy==="escape"?KO(t):t}function KO(t){let e="";for(let r=0;r<t.length;r++)GO.has(t[r])||(e+="\\"),e+=t[r];return e}function Yt(t,e,r,n){t.format||t.anyOf?.some(o=>o.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&n.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...r&&n.errorMessages&&{errorMessage:{format:r}}})):ie(t,"format",e,r,n)}function ct(t,e,r,n){t.pattern||t.allOf?.some(o=>o.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&n.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:rb(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ie(t,"pattern",rb(e,n),r,n)}function rb(t,e){if(!e.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},n=r.i?t.source.toLowerCase():t.source,o="",s=!1,i=!1,a=!1;for(let c=0;c<n.length;c++){if(s){o+=n[c],s=!1;continue}if(r.i){if(i){if(n[c].match(/[a-z]/)){a?(o+=n[c],o+=`${n[c-2]}-${n[c]}`.toUpperCase(),a=!1):n[c+1]==="-"&&n[c+2]?.match(/[a-z]/)?(o+=n[c],a=!0):o+=`${n[c]}${n[c].toUpperCase()}`;continue}}else if(n[c].match(/[a-z]/)){o+=`[${n[c]}${n[c].toUpperCase()}]`;continue}}if(r.m){if(n[c]==="^"){o+=`(^|(?<=[\r
47
- ]))`;continue}else if(n[c]==="$"){o+=`($|(?=[\r
48
- ]))`;continue}}if(r.s&&n[c]==="."){o+=i?`${n[c]}\r
60
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let d of this.seen.entries()){let l=d[1];if(e===d[0]){i(d);continue}if(n.external){let f=n.external.registry.get(d[0])?.id;if(e!==d[0]&&f){i(d);continue}}if(this.metadataRegistry.get(d[0])?.id){i(d);continue}if(l.cycle){i(d);continue}if(l.count>1&&n.reused==="ref"){i(d);continue}}let a=(d,l)=>{let m=this.seen.get(d),f=m.def??m.schema,p={...f};if(m.ref===null)return;let h=m.ref;if(m.ref=null,h){a(h,l);let g=this.seen.get(h).schema;g.$ref&&l.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}m.isParent||this.override({zodSchema:d,jsonSchema:f,path:m.path??[]})};for(let d of[...this.seen.entries()].reverse())a(d[0],{target:this.target});let c={};if(this.target==="draft-2020-12"?c.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?c.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),n.external?.uri){let d=n.external.registry.get(e)?.id;if(!d)throw new Error("Schema is missing an `id` property");c.$id=n.external.uri(d)}Object.assign(c,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 Vv=v(()=>{});var lt=v(()=>{Ns();Fd();Ad();Nv();Ba();Vd();br();Za();Ja();Dp();qd();Bv();Zv();qv();Vv()});var km=v(()=>{lt()});function wm(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new dO(r)}var lO,dO,Wv=v(()=>{lt();lt();km();lO=k("ZodMiniType",(t,e)=>{if(!t._zod)throw new Error("Uninitialized schema in ZodMiniType.");_e.init(t,e),t.def=e,t.parse=(r,n)=>Dd(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>Vn(t,r,n),t.parseAsync=async(r,n)=>jd(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>Wn(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)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t))}),dO=k("ZodMiniObject",(t,e)=>{Ga.init(t,e),lO.init(t,e),ae.defineLazy(t,"shape",()=>e.shape)})});var Gv=v(()=>{});var Kv=v(()=>{});var Jv=v(()=>{});var Yv=v(()=>{lt();km();Wv();Gv();lt();Ja();Kv();Jv()});var Xv=v(()=>{Yv()});var Em=v(()=>{Xv()});function Zt(t){return!!t._zod}function Jn(t){let e=Object.values(t);if(e.length===0)return wm({});let r=e.every(Zt),n=e.every(s=>!Zt(s));if(r)return wm(t);if(n)return vd(t);throw new Error("Mixed Zod versions detected in object shape.")}function nn(t,e){return Zt(t)?Vn(t,e):t.safeParse(e)}async function sc(t,e){return Zt(t)?await Wn(t,e):await t.safeParseAsync(e)}function sn(t){if(!t)return;let e;if(Zt(t)?e=t._zod?.def?.shape:e=t.shape,!!e){if(typeof e=="function")try{return e()}catch{return}return e}}function zs(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 Jn(t)}}if(Zt(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 oc(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 eb(t){return t.description}function tb(t){if(Zt(t))return t._zod?.def?.type==="optional";let e=t;return typeof t.isOptional=="function"?t.isOptional():e._def?.typeName==="ZodOptional"}function ic(t){if(Zt(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 Jo=v(()=>{jo();Em()});var $m=v(()=>{lt()});var Yo={};Le(Yo,{ZodISODate:()=>nb,ZodISODateTime:()=>rb,ZodISODuration:()=>ob,ZodISOTime:()=>sb,date:()=>Pm,datetime:()=>Tm,duration:()=>Cm,time:()=>Rm});function Tm(t){return zv(rb,t)}function Pm(t){return Lv(nb,t)}function Rm(t){return Fv(sb,t)}function Cm(t){return Uv(ob,t)}var rb,nb,sb,ob,Om=v(()=>{lt();Im();rb=k("ZodISODateTime",(t,e)=>{Rv.init(t,e),Oe.init(t,e)});nb=k("ZodISODate",(t,e)=>{Cv.init(t,e),Oe.init(t,e)});sb=k("ZodISOTime",(t,e)=>{Ov.init(t,e),Oe.init(t,e)});ob=k("ZodISODuration",(t,e)=>{Iv.init(t,e),Oe.init(t,e)})});var ib,JB,Xo,Am=v(()=>{lt();lt();ib=(t,e)=>{Ua.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:r=>Id(t,r)},flatten:{value:r=>Od(t,r)},addIssue:{value:r=>t.issues.push(r)},addIssues:{value:r=>t.issues.push(...r)},isEmpty:{get(){return t.issues.length===0}}})},JB=k("ZodError",ib),Xo=k("ZodError",ib,{Parent:Error})});var ab,cb,ub,lb,Nm=v(()=>{lt();Am();ab=Nd(Xo),cb=Md(Xo),ub=zd(Xo),lb=Ld(Xo)});function b(t){return Mp(bO,t)}function he(t){return sm(hb,t)}function pb(t){return om(LO,t)}function Ve(t){return im(FO,t)}function gb(t){return am(UO,t)}function Ie(){return cm(HO)}function BO(t){return um(ZO,t)}function ce(t,e){return Hv(qO,t,e)}function j(t,e){let r={type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},...ae.normalizeParams(e)};return new yb(r)}function dt(t,e){return new yb({type:"object",get shape(){return ae.assignProp(this,"shape",{...t}),this.shape},catchall:Ie(),...ae.normalizeParams(e)})}function Te(t,e){return new _b({type:"union",options:t,...ae.normalizeParams(e)})}function jm(t,e,r){return new VO({type:"union",options:e,discriminator:t,...ae.normalizeParams(r)})}function cc(t,e){return new WO({type:"intersection",left:t,right:e})}function Ee(t,e,r){return new GO({type:"record",keyType:t,valueType:e,...ae.normalizeParams(r)})}function bt(t,e){let r=Array.isArray(t)?Object.fromEntries(t.map(n=>[n,n])):t;return new Dm({type:"enum",entries:r,...ae.normalizeParams(e)})}function H(t,e){return new KO({type:"literal",values:Array.isArray(t)?t:[t],...ae.normalizeParams(e)})}function xb(t){return new JO({type:"transform",transform:t})}function Ae(t){return new vb({type:"optional",innerType:t})}function mb(t){return new YO({type:"nullable",innerType:t})}function QO(t,e){return new XO({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function tI(t,e){return new eI({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():e}})}function rI(t,e){return new bb({type:"nonoptional",innerType:t,...ae.normalizeParams(e)})}function sI(t,e){return new nI({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}function Mm(t,e){return new oI({type:"pipe",in:t,out:e})}function aI(t){return new iI({type:"readonly",innerType:t})}function cI(t){let e=new Ke({check:"custom"});return e._zod.check=t,e}function kb(t,e){return vm(Sb,t??(()=>!0),e)}function uI(t,e={}){return bm(Sb,t,e)}function lI(t){let e=cI(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 zm(t,e){return Mm(xb(t),e)}var je,fb,bO,Oe,SO,db,ac,kO,wO,EO,$O,TO,PO,RO,CO,OO,IO,AO,NO,DO,MO,jO,zO,hb,LO,FO,UO,HO,ZO,qO,yb,_b,VO,WO,GO,Dm,KO,JO,vb,YO,XO,eI,bb,nI,oI,iI,Sb,Im=v(()=>{lt();lt();$m();Om();Nm();je=k("ZodType",(t,e)=>(_e.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)=>Ot(t,r,n),t.brand=()=>t,t.register=((r,n)=>(r.add(t,n),t)),t.parse=(r,n)=>ab(t,r,n,{callee:t.parse}),t.safeParse=(r,n)=>ub(t,r,n),t.parseAsync=async(r,n)=>cb(t,r,n,{callee:t.parseAsync}),t.safeParseAsync=async(r,n)=>lb(t,r,n),t.spa=t.safeParseAsync,t.refine=(r,n)=>t.check(uI(r,n)),t.superRefine=r=>t.check(lI(r)),t.overwrite=r=>t.check(Gn(r)),t.optional=()=>Ae(t),t.nullable=()=>mb(t),t.nullish=()=>Ae(mb(t)),t.nonoptional=r=>rI(t,r),t.array=()=>ce(t),t.or=r=>Te([t,r]),t.and=r=>cc(t,r),t.transform=r=>Mm(t,xb(r)),t.default=r=>QO(t,r),t.prefault=r=>tI(t,r),t.catch=r=>sI(t,r),t.pipe=r=>Mm(t,r),t.readonly=()=>aI(t),t.describe=r=>{let n=t.clone();return rn.add(n,{description:r}),n},Object.defineProperty(t,"description",{get(){return rn.get(t)?.description},configurable:!0}),t.meta=(...r)=>{if(r.length===0)return rn.get(t);let n=t.clone();return rn.add(n,r[0]),n},t.isOptional=()=>t.safeParse(void 0).success,t.isNullable=()=>t.safeParse(null).success,t)),fb=k("_ZodString",(t,e)=>{Vo.init(t,e),je.init(t,e);let r=t._zod.bag;t.format=r.format??null,t.minLength=r.minimum??null,t.maxLength=r.maximum??null,t.regex=(...n)=>t.check(lm(...n)),t.includes=(...n)=>t.check(mm(...n)),t.startsWith=(...n)=>t.check(fm(...n)),t.endsWith=(...n)=>t.check(hm(...n)),t.min=(...n)=>t.check(js(...n)),t.max=(...n)=>t.check(tc(...n)),t.length=(...n)=>t.check(rc(...n)),t.nonempty=(...n)=>t.check(js(1,...n)),t.lowercase=n=>t.check(dm(n)),t.uppercase=n=>t.check(pm(n)),t.trim=()=>t.check(ym()),t.normalize=(...n)=>t.check(gm(...n)),t.toLowerCase=()=>t.check(_m()),t.toUpperCase=()=>t.check(xm())}),bO=k("ZodString",(t,e)=>{Vo.init(t,e),fb.init(t,e),t.email=r=>t.check(jp(SO,r)),t.url=r=>t.check(Hp(kO,r)),t.jwt=r=>t.check(nm(zO,r)),t.emoji=r=>t.check(Zp(wO,r)),t.guid=r=>t.check(Ya(db,r)),t.uuid=r=>t.check(zp(ac,r)),t.uuidv4=r=>t.check(Lp(ac,r)),t.uuidv6=r=>t.check(Fp(ac,r)),t.uuidv7=r=>t.check(Up(ac,r)),t.nanoid=r=>t.check(Bp(EO,r)),t.guid=r=>t.check(Ya(db,r)),t.cuid=r=>t.check(qp($O,r)),t.cuid2=r=>t.check(Vp(TO,r)),t.ulid=r=>t.check(Wp(PO,r)),t.base64=r=>t.check(em(DO,r)),t.base64url=r=>t.check(tm(MO,r)),t.xid=r=>t.check(Gp(RO,r)),t.ksuid=r=>t.check(Kp(CO,r)),t.ipv4=r=>t.check(Jp(OO,r)),t.ipv6=r=>t.check(Yp(IO,r)),t.cidrv4=r=>t.check(Xp(AO,r)),t.cidrv6=r=>t.check(Qp(NO,r)),t.e164=r=>t.check(rm(jO,r)),t.datetime=r=>t.check(Tm(r)),t.date=r=>t.check(Pm(r)),t.time=r=>t.check(Rm(r)),t.duration=r=>t.check(Cm(r))});Oe=k("ZodStringFormat",(t,e)=>{we.init(t,e),fb.init(t,e)}),SO=k("ZodEmail",(t,e)=>{Jd.init(t,e),Oe.init(t,e)}),db=k("ZodGUID",(t,e)=>{Gd.init(t,e),Oe.init(t,e)}),ac=k("ZodUUID",(t,e)=>{Kd.init(t,e),Oe.init(t,e)}),kO=k("ZodURL",(t,e)=>{Yd.init(t,e),Oe.init(t,e)}),wO=k("ZodEmoji",(t,e)=>{Xd.init(t,e),Oe.init(t,e)}),EO=k("ZodNanoID",(t,e)=>{Qd.init(t,e),Oe.init(t,e)}),$O=k("ZodCUID",(t,e)=>{ep.init(t,e),Oe.init(t,e)}),TO=k("ZodCUID2",(t,e)=>{tp.init(t,e),Oe.init(t,e)}),PO=k("ZodULID",(t,e)=>{rp.init(t,e),Oe.init(t,e)}),RO=k("ZodXID",(t,e)=>{np.init(t,e),Oe.init(t,e)}),CO=k("ZodKSUID",(t,e)=>{sp.init(t,e),Oe.init(t,e)}),OO=k("ZodIPv4",(t,e)=>{op.init(t,e),Oe.init(t,e)}),IO=k("ZodIPv6",(t,e)=>{ip.init(t,e),Oe.init(t,e)}),AO=k("ZodCIDRv4",(t,e)=>{ap.init(t,e),Oe.init(t,e)}),NO=k("ZodCIDRv6",(t,e)=>{cp.init(t,e),Oe.init(t,e)}),DO=k("ZodBase64",(t,e)=>{up.init(t,e),Oe.init(t,e)}),MO=k("ZodBase64URL",(t,e)=>{lp.init(t,e),Oe.init(t,e)}),jO=k("ZodE164",(t,e)=>{dp.init(t,e),Oe.init(t,e)}),zO=k("ZodJWT",(t,e)=>{pp.init(t,e),Oe.init(t,e)}),hb=k("ZodNumber",(t,e)=>{Wa.init(t,e),je.init(t,e),t.gt=(n,s)=>t.check(Qa(n,s)),t.gte=(n,s)=>t.check(Ko(n,s)),t.min=(n,s)=>t.check(Ko(n,s)),t.lt=(n,s)=>t.check(Xa(n,s)),t.lte=(n,s)=>t.check(Go(n,s)),t.max=(n,s)=>t.check(Go(n,s)),t.int=n=>t.check(pb(n)),t.safe=n=>t.check(pb(n)),t.positive=n=>t.check(Qa(0,n)),t.nonnegative=n=>t.check(Ko(0,n)),t.negative=n=>t.check(Xa(0,n)),t.nonpositive=n=>t.check(Go(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});LO=k("ZodNumberFormat",(t,e)=>{mp.init(t,e),hb.init(t,e)});FO=k("ZodBoolean",(t,e)=>{fp.init(t,e),je.init(t,e)});UO=k("ZodNull",(t,e)=>{hp.init(t,e),je.init(t,e)});HO=k("ZodUnknown",(t,e)=>{gp.init(t,e),je.init(t,e)});ZO=k("ZodNever",(t,e)=>{yp.init(t,e),je.init(t,e)});qO=k("ZodArray",(t,e)=>{_p.init(t,e),je.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(tc(r,n)),t.length=(r,n)=>t.check(rc(r,n)),t.unwrap=()=>t.element});yb=k("ZodObject",(t,e)=>{Ga.init(t,e),je.init(t,e),ae.defineLazy(t,"shape",()=>e.shape),t.keyof=()=>bt(Object.keys(t._zod.def.shape)),t.catchall=r=>t.clone({...t._zod.def,catchall:r}),t.passthrough=()=>t.clone({...t._zod.def,catchall:Ie()}),t.loose=()=>t.clone({...t._zod.def,catchall:Ie()}),t.strict=()=>t.clone({...t._zod.def,catchall:BO()}),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(vb,t,r[0]),t.required=(...r)=>ae.required(bb,t,r[0])});_b=k("ZodUnion",(t,e)=>{Ka.init(t,e),je.init(t,e),t.options=e.options});VO=k("ZodDiscriminatedUnion",(t,e)=>{_b.init(t,e),xp.init(t,e)});WO=k("ZodIntersection",(t,e)=>{vp.init(t,e),je.init(t,e)});GO=k("ZodRecord",(t,e)=>{bp.init(t,e),je.init(t,e),t.keyType=e.keyType,t.valueType=e.valueType});Dm=k("ZodEnum",(t,e)=>{Sp.init(t,e),je.init(t,e),t.enum=e.entries,t.options=Object.values(e.entries);let r=new Set(Object.keys(e.entries));t.extract=(n,s)=>{let o={};for(let i of n)if(r.has(i))o[i]=e.entries[i];else throw new Error(`Key ${i} not found in enum`);return new Dm({...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 Dm({...e,checks:[],...ae.normalizeParams(s),entries:o})}});KO=k("ZodLiteral",(t,e)=>{kp.init(t,e),je.init(t,e),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});JO=k("ZodTransform",(t,e)=>{wp.init(t,e),je.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)}});vb=k("ZodOptional",(t,e)=>{Ep.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});YO=k("ZodNullable",(t,e)=>{$p.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});XO=k("ZodDefault",(t,e)=>{Tp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});eI=k("ZodPrefault",(t,e)=>{Pp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});bb=k("ZodNonOptional",(t,e)=>{Rp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType});nI=k("ZodCatch",(t,e)=>{Cp.init(t,e),je.init(t,e),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});oI=k("ZodPipe",(t,e)=>{Op.init(t,e),je.init(t,e),t.in=e.in,t.out=e.out});iI=k("ZodReadonly",(t,e)=>{Ip.init(t,e),je.init(t,e)});Sb=k("ZodCustom",(t,e)=>{Ap.init(t,e),je.init(t,e)})});var wb=v(()=>{});var Eb=v(()=>{});var $b=v(()=>{lt();Im();$m();Am();Nm();wb();lt();Mv();Ja();Om();Eb();Ct(Dv())});var Tb=v(()=>{$b()});var Pb=v(()=>{Tb()});function qb(t){if(t.params.ref.type!=="ref/prompt")throw new TypeError(`Expected CompleteRequestPrompt, but got ${t.params.ref.type}`)}function Vb(t){if(t.params.ref.type!=="ref/resource")throw new TypeError(`Expected CompleteRequestResourceTemplate, but got ${t.params.ref.type}`)}var Fm,Rb,on,lc,qe,Cb,Ob,pq,mI,fI,Um,It,Qo,Ib,Je,Bt,qt,Ye,dc,Ab,Hm,Nb,Db,Zm,ei,q,Bm,Mb,jb,mq,pc,hI,mc,gI,ti,Ls,zb,yI,_I,xI,vI,bI,SI,qm,kI,wI,Vm,fc,EI,$I,hc,TI,ri,ni,PI,si,Fs,RI,oi,gc,yc,_c,fq,xc,vc,bc,Lb,Fb,Ub,Wm,Hb,ii,Us,Zb,CI,Hs,OI,Zs,II,Gm,AI,Sc,NI,DI,MI,jI,zI,LI,FI,UI,HI,ZI,Bs,BI,qI,kc,Km,Jm,Ym,VI,WI,GI,Xm,KI,JI,YI,XI,QI,Bb,wc,eA,Ec,hq,tA,qs,rA,gq,ai,nA,Qm,sA,oA,iA,aA,cA,uA,lA,uc,dA,pA,mA,ci,ef,fA,hA,gA,yA,_A,xA,vA,bA,SA,kA,wA,EA,$A,TA,PA,RA,CA,OA,Vs,IA,AA,NA,$c,DA,MA,jA,tf,zA,yq,_q,xq,vq,bq,Sq,L,Lm,Yn=v(()=>{Pb();Fm="2025-11-25",Rb=[Fm,"2025-06-18","2025-03-26","2024-11-05","2024-10-07"],on="io.modelcontextprotocol/related-task",lc="2.0",qe=kb(t=>t!==null&&(typeof t=="object"||typeof t=="function")),Cb=Te([b(),he().int()]),Ob=b(),pq=dt({ttl:he().optional(),pollInterval:he().optional()}),mI=j({ttl:he().optional()}),fI=j({taskId:b()}),Um=dt({progressToken:Cb.optional(),[on]:fI.optional()}),It=j({_meta:Um.optional()}),Qo=It.extend({task:mI.optional()}),Ib=t=>Qo.safeParse(t).success,Je=j({method:b(),params:It.loose().optional()}),Bt=j({_meta:Um.optional()}),qt=j({method:b(),params:Bt.loose().optional()}),Ye=dt({_meta:Um.optional()}),dc=Te([b(),he().int()]),Ab=j({jsonrpc:H(lc),id:dc,...Je.shape}).strict(),Hm=t=>Ab.safeParse(t).success,Nb=j({jsonrpc:H(lc),...qt.shape}).strict(),Db=t=>Nb.safeParse(t).success,Zm=j({jsonrpc:H(lc),id:dc,result:Ye}).strict(),ei=t=>Zm.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"})(q||(q={}));Bm=j({jsonrpc:H(lc),id:dc.optional(),error:j({code:he().int(),message:b(),data:Ie().optional()})}).strict(),Mb=t=>Bm.safeParse(t).success,jb=Te([Ab,Nb,Zm,Bm]),mq=Te([Zm,Bm]),pc=Ye.strict(),hI=Bt.extend({requestId:dc.optional(),reason:b().optional()}),mc=qt.extend({method:H("notifications/cancelled"),params:hI}),gI=j({src:b(),mimeType:b().optional(),sizes:ce(b()).optional(),theme:bt(["light","dark"]).optional()}),ti=j({icons:ce(gI).optional()}),Ls=j({name:b(),title:b().optional()}),zb=Ls.extend({...Ls.shape,...ti.shape,version:b(),websiteUrl:b().optional(),description:b().optional()}),yI=cc(j({applyDefaults:Ve().optional()}),Ee(b(),Ie())),_I=zm(t=>t&&typeof t=="object"&&!Array.isArray(t)&&Object.keys(t).length===0?{form:{}}:t,cc(j({form:yI.optional(),url:qe.optional()}),Ee(b(),Ie()).optional())),xI=dt({list:qe.optional(),cancel:qe.optional(),requests:dt({sampling:dt({createMessage:qe.optional()}).optional(),elicitation:dt({create:qe.optional()}).optional()}).optional()}),vI=dt({list:qe.optional(),cancel:qe.optional(),requests:dt({tools:dt({call:qe.optional()}).optional()}).optional()}),bI=j({experimental:Ee(b(),qe).optional(),sampling:j({context:qe.optional(),tools:qe.optional()}).optional(),elicitation:_I.optional(),roots:j({listChanged:Ve().optional()}).optional(),tasks:xI.optional(),extensions:Ee(b(),qe).optional()}),SI=It.extend({protocolVersion:b(),capabilities:bI,clientInfo:zb}),qm=Je.extend({method:H("initialize"),params:SI}),kI=j({experimental:Ee(b(),qe).optional(),logging:qe.optional(),completions:qe.optional(),prompts:j({listChanged:Ve().optional()}).optional(),resources:j({subscribe:Ve().optional(),listChanged:Ve().optional()}).optional(),tools:j({listChanged:Ve().optional()}).optional(),tasks:vI.optional(),extensions:Ee(b(),qe).optional()}),wI=Ye.extend({protocolVersion:b(),capabilities:kI,serverInfo:zb,instructions:b().optional()}),Vm=qt.extend({method:H("notifications/initialized"),params:Bt.optional()}),fc=Je.extend({method:H("ping"),params:It.optional()}),EI=j({progress:he(),total:Ae(he()),message:Ae(b())}),$I=j({...Bt.shape,...EI.shape,progressToken:Cb}),hc=qt.extend({method:H("notifications/progress"),params:$I}),TI=It.extend({cursor:Ob.optional()}),ri=Je.extend({params:TI.optional()}),ni=Ye.extend({nextCursor:Ob.optional()}),PI=bt(["working","input_required","completed","failed","cancelled"]),si=j({taskId:b(),status:PI,ttl:Te([he(),gb()]),createdAt:b(),lastUpdatedAt:b(),pollInterval:Ae(he()),statusMessage:Ae(b())}),Fs=Ye.extend({task:si}),RI=Bt.merge(si),oi=qt.extend({method:H("notifications/tasks/status"),params:RI}),gc=Je.extend({method:H("tasks/get"),params:It.extend({taskId:b()})}),yc=Ye.merge(si),_c=Je.extend({method:H("tasks/result"),params:It.extend({taskId:b()})}),fq=Ye.loose(),xc=ri.extend({method:H("tasks/list")}),vc=ni.extend({tasks:ce(si)}),bc=Je.extend({method:H("tasks/cancel"),params:It.extend({taskId:b()})}),Lb=Ye.merge(si),Fb=j({uri:b(),mimeType:Ae(b()),_meta:Ee(b(),Ie()).optional()}),Ub=Fb.extend({text:b()}),Wm=b().refine(t=>{try{return atob(t),!0}catch{return!1}},{message:"Invalid Base64 string"}),Hb=Fb.extend({blob:Wm}),ii=bt(["user","assistant"]),Us=j({audience:ce(ii).optional(),priority:he().min(0).max(1).optional(),lastModified:Yo.datetime({offset:!0}).optional()}),Zb=j({...Ls.shape,...ti.shape,uri:b(),description:Ae(b()),mimeType:Ae(b()),size:Ae(he()),annotations:Us.optional(),_meta:Ae(dt({}))}),CI=j({...Ls.shape,...ti.shape,uriTemplate:b(),description:Ae(b()),mimeType:Ae(b()),annotations:Us.optional(),_meta:Ae(dt({}))}),Hs=ri.extend({method:H("resources/list")}),OI=ni.extend({resources:ce(Zb)}),Zs=ri.extend({method:H("resources/templates/list")}),II=ni.extend({resourceTemplates:ce(CI)}),Gm=It.extend({uri:b()}),AI=Gm,Sc=Je.extend({method:H("resources/read"),params:AI}),NI=Ye.extend({contents:ce(Te([Ub,Hb]))}),DI=qt.extend({method:H("notifications/resources/list_changed"),params:Bt.optional()}),MI=Gm,jI=Je.extend({method:H("resources/subscribe"),params:MI}),zI=Gm,LI=Je.extend({method:H("resources/unsubscribe"),params:zI}),FI=Bt.extend({uri:b()}),UI=qt.extend({method:H("notifications/resources/updated"),params:FI}),HI=j({name:b(),description:Ae(b()),required:Ae(Ve())}),ZI=j({...Ls.shape,...ti.shape,description:Ae(b()),arguments:Ae(ce(HI)),_meta:Ae(dt({}))}),Bs=ri.extend({method:H("prompts/list")}),BI=ni.extend({prompts:ce(ZI)}),qI=It.extend({name:b(),arguments:Ee(b(),b()).optional()}),kc=Je.extend({method:H("prompts/get"),params:qI}),Km=j({type:H("text"),text:b(),annotations:Us.optional(),_meta:Ee(b(),Ie()).optional()}),Jm=j({type:H("image"),data:Wm,mimeType:b(),annotations:Us.optional(),_meta:Ee(b(),Ie()).optional()}),Ym=j({type:H("audio"),data:Wm,mimeType:b(),annotations:Us.optional(),_meta:Ee(b(),Ie()).optional()}),VI=j({type:H("tool_use"),name:b(),id:b(),input:Ee(b(),Ie()),_meta:Ee(b(),Ie()).optional()}),WI=j({type:H("resource"),resource:Te([Ub,Hb]),annotations:Us.optional(),_meta:Ee(b(),Ie()).optional()}),GI=Zb.extend({type:H("resource_link")}),Xm=Te([Km,Jm,Ym,GI,WI]),KI=j({role:ii,content:Xm}),JI=Ye.extend({description:b().optional(),messages:ce(KI)}),YI=qt.extend({method:H("notifications/prompts/list_changed"),params:Bt.optional()}),XI=j({title:b().optional(),readOnlyHint:Ve().optional(),destructiveHint:Ve().optional(),idempotentHint:Ve().optional(),openWorldHint:Ve().optional()}),QI=j({taskSupport:bt(["required","optional","forbidden"]).optional()}),Bb=j({...Ls.shape,...ti.shape,description:b().optional(),inputSchema:j({type:H("object"),properties:Ee(b(),qe).optional(),required:ce(b()).optional()}).catchall(Ie()),outputSchema:j({type:H("object"),properties:Ee(b(),qe).optional(),required:ce(b()).optional()}).catchall(Ie()).optional(),annotations:XI.optional(),execution:QI.optional(),_meta:Ee(b(),Ie()).optional()}),wc=ri.extend({method:H("tools/list")}),eA=ni.extend({tools:ce(Bb)}),Ec=Ye.extend({content:ce(Xm).default([]),structuredContent:Ee(b(),Ie()).optional(),isError:Ve().optional()}),hq=Ec.or(Ye.extend({toolResult:Ie()})),tA=Qo.extend({name:b(),arguments:Ee(b(),Ie()).optional()}),qs=Je.extend({method:H("tools/call"),params:tA}),rA=qt.extend({method:H("notifications/tools/list_changed"),params:Bt.optional()}),gq=j({autoRefresh:Ve().default(!0),debounceMs:he().int().nonnegative().default(300)}),ai=bt(["debug","info","notice","warning","error","critical","alert","emergency"]),nA=It.extend({level:ai}),Qm=Je.extend({method:H("logging/setLevel"),params:nA}),sA=Bt.extend({level:ai,logger:b().optional(),data:Ie()}),oA=qt.extend({method:H("notifications/message"),params:sA}),iA=j({name:b().optional()}),aA=j({hints:ce(iA).optional(),costPriority:he().min(0).max(1).optional(),speedPriority:he().min(0).max(1).optional(),intelligencePriority:he().min(0).max(1).optional()}),cA=j({mode:bt(["auto","required","none"]).optional()}),uA=j({type:H("tool_result"),toolUseId:b().describe("The unique identifier for the corresponding tool call."),content:ce(Xm).default([]),structuredContent:j({}).loose().optional(),isError:Ve().optional(),_meta:Ee(b(),Ie()).optional()}),lA=jm("type",[Km,Jm,Ym]),uc=jm("type",[Km,Jm,Ym,VI,uA]),dA=j({role:ii,content:Te([uc,ce(uc)]),_meta:Ee(b(),Ie()).optional()}),pA=Qo.extend({messages:ce(dA),modelPreferences:aA.optional(),systemPrompt:b().optional(),includeContext:bt(["none","thisServer","allServers"]).optional(),temperature:he().optional(),maxTokens:he().int(),stopSequences:ce(b()).optional(),metadata:qe.optional(),tools:ce(Bb).optional(),toolChoice:cA.optional()}),mA=Je.extend({method:H("sampling/createMessage"),params:pA}),ci=Ye.extend({model:b(),stopReason:Ae(bt(["endTurn","stopSequence","maxTokens"]).or(b())),role:ii,content:lA}),ef=Ye.extend({model:b(),stopReason:Ae(bt(["endTurn","stopSequence","maxTokens","toolUse"]).or(b())),role:ii,content:Te([uc,ce(uc)])}),fA=j({type:H("boolean"),title:b().optional(),description:b().optional(),default:Ve().optional()}),hA=j({type:H("string"),title:b().optional(),description:b().optional(),minLength:he().optional(),maxLength:he().optional(),format:bt(["email","uri","date","date-time"]).optional(),default:b().optional()}),gA=j({type:bt(["number","integer"]),title:b().optional(),description:b().optional(),minimum:he().optional(),maximum:he().optional(),default:he().optional()}),yA=j({type:H("string"),title:b().optional(),description:b().optional(),enum:ce(b()),default:b().optional()}),_A=j({type:H("string"),title:b().optional(),description:b().optional(),oneOf:ce(j({const:b(),title:b()})),default:b().optional()}),xA=j({type:H("string"),title:b().optional(),description:b().optional(),enum:ce(b()),enumNames:ce(b()).optional(),default:b().optional()}),vA=Te([yA,_A]),bA=j({type:H("array"),title:b().optional(),description:b().optional(),minItems:he().optional(),maxItems:he().optional(),items:j({type:H("string"),enum:ce(b())}),default:ce(b()).optional()}),SA=j({type:H("array"),title:b().optional(),description:b().optional(),minItems:he().optional(),maxItems:he().optional(),items:j({anyOf:ce(j({const:b(),title:b()}))}),default:ce(b()).optional()}),kA=Te([bA,SA]),wA=Te([xA,vA,kA]),EA=Te([wA,fA,hA,gA]),$A=Qo.extend({mode:H("form").optional(),message:b(),requestedSchema:j({type:H("object"),properties:Ee(b(),EA),required:ce(b()).optional()})}),TA=Qo.extend({mode:H("url"),message:b(),elicitationId:b(),url:b().url()}),PA=Te([$A,TA]),RA=Je.extend({method:H("elicitation/create"),params:PA}),CA=Bt.extend({elicitationId:b()}),OA=qt.extend({method:H("notifications/elicitation/complete"),params:CA}),Vs=Ye.extend({action:bt(["accept","decline","cancel"]),content:zm(t=>t===null?void 0:t,Ee(b(),Te([b(),he(),Ve(),ce(b())])).optional())}),IA=j({type:H("ref/resource"),uri:b()}),AA=j({type:H("ref/prompt"),name:b()}),NA=It.extend({ref:Te([AA,IA]),argument:j({name:b(),value:b()}),context:j({arguments:Ee(b(),b()).optional()}).optional()}),$c=Je.extend({method:H("completion/complete"),params:NA});DA=Ye.extend({completion:dt({values:ce(b()).max(100),total:Ae(he().int()),hasMore:Ae(Ve())})}),MA=j({uri:b().startsWith("file://"),name:b().optional(),_meta:Ee(b(),Ie()).optional()}),jA=Je.extend({method:H("roots/list"),params:It.optional()}),tf=Ye.extend({roots:ce(MA)}),zA=qt.extend({method:H("notifications/roots/list_changed"),params:Bt.optional()}),yq=Te([fc,qm,$c,Qm,kc,Bs,Hs,Zs,Sc,jI,LI,qs,wc,gc,_c,xc,bc]),_q=Te([mc,hc,Vm,zA,oi]),xq=Te([pc,ci,ef,Vs,tf,yc,vc,Fs]),vq=Te([fc,mA,RA,jA,gc,_c,xc,bc]),bq=Te([mc,hc,oA,UI,DI,rA,YI,oi,OA]),Sq=Te([pc,wI,DA,JI,BI,OI,II,NI,Ec,eA,yc,vc,Fs]),L=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===q.UrlElicitationRequired&&n){let s=n;if(s.elicitations)return new Lm(s.elicitations,r)}return new t(e,r,n)}},Lm=class extends L{constructor(e,r=`URL elicitation${e.length>1?"s":""} required`){super(q.UrlElicitationRequired,r,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}}});function an(t){return t==="completed"||t==="failed"||t==="cancelled"}var Wb=v(()=>{});var Kb,Gb,Jb,Tc=v(()=>{Kb=Symbol("Let zodToJsonSchema decide on which parser to use"),Gb={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"},Jb=t=>typeof t=="string"?{...Gb,name:t}:{...Gb,...t}});var Yb,rf=v(()=>{Tc();Yb=t=>{let e=Jb(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 ue(t,e,r,n,s){t[e]=r,nf(t,e,n,s)}var cn=v(()=>{});var Pc,Rc=v(()=>{Pc=(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 Ne(t){if(t.target!=="openAi")return{};let e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?Pc(e,t.currentPath):e.join("/")}}var Vt=v(()=>{Rc()});function Xb(t,e){let r={type:"array"};return t.type?._def&&t.type?._def?.typeName!==P.ZodAny&&(r.items=J(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ue(r,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ue(r,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ue(r,"minItems",t.exactLength.value,t.exactLength.message,e),ue(r,"maxItems",t.exactLength.value,t.exactLength.message,e)),r}var sf=v(()=>{jo();cn();He()});function Qb(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?ue(r,"minimum",n.value,n.message,e):ue(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ue(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(r,"maximum",n.value,n.message,e):ue(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ue(r,"maximum",n.value,n.message,e));break;case"multipleOf":ue(r,"multipleOf",n.value,n.message,e);break}return r}var of=v(()=>{cn()});function eS(){return{type:"boolean"}}var af=v(()=>{});function Cc(t,e){return J(t.type._def,e)}var Oc=v(()=>{He()});var tS,cf=v(()=>{He();tS=(t,e)=>J(t.innerType._def,e)});function uf(t,e,r){let n=r??e.dateStrategy;if(Array.isArray(n))return{anyOf:n.map((s,o)=>uf(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 LA(t,e)}}var LA,lf=v(()=>{cn();LA=(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":ue(r,"minimum",n.value,n.message,e);break;case"max":ue(r,"maximum",n.value,n.message,e);break}return r}});function rS(t,e){return{...J(t.innerType._def,e),default:t.defaultValue()}}var df=v(()=>{He()});function nS(t,e){return e.effectStrategy==="input"?J(t.schema._def,e):Ne(e)}var pf=v(()=>{He();Vt()});function sS(t){return{type:"string",enum:Array.from(t.values)}}var mf=v(()=>{});function oS(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(FA(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 FA,ff=v(()=>{He();FA=t=>"type"in t&&t.type==="string"?!1:"allOf"in t});function iS(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 hf=v(()=>{});function Ic(t,e){let r={type:"string"};if(t.checks)for(let n of t.checks)switch(n.kind){case"min":ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e);break;case"max":ue(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":or(r,"email",n.message,e);break;case"format:idn-email":or(r,"idn-email",n.message,e);break;case"pattern:zod":pt(r,sr.email,n.message,e);break}break;case"url":or(r,"uri",n.message,e);break;case"uuid":or(r,"uuid",n.message,e);break;case"regex":pt(r,n.regex,n.message,e);break;case"cuid":pt(r,sr.cuid,n.message,e);break;case"cuid2":pt(r,sr.cuid2,n.message,e);break;case"startsWith":pt(r,RegExp(`^${yf(n.value,e)}`),n.message,e);break;case"endsWith":pt(r,RegExp(`${yf(n.value,e)}$`),n.message,e);break;case"datetime":or(r,"date-time",n.message,e);break;case"date":or(r,"date",n.message,e);break;case"time":or(r,"time",n.message,e);break;case"duration":or(r,"duration",n.message,e);break;case"length":ue(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,n.value):n.value,n.message,e),ue(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,n.value):n.value,n.message,e);break;case"includes":{pt(r,RegExp(yf(n.value,e)),n.message,e);break}case"ip":{n.version!=="v6"&&or(r,"ipv4",n.message,e),n.version!=="v4"&&or(r,"ipv6",n.message,e);break}case"base64url":pt(r,sr.base64url,n.message,e);break;case"jwt":pt(r,sr.jwt,n.message,e);break;case"cidr":{n.version!=="v6"&&pt(r,sr.ipv4Cidr,n.message,e),n.version!=="v4"&&pt(r,sr.ipv6Cidr,n.message,e);break}case"emoji":pt(r,sr.emoji(),n.message,e);break;case"ulid":{pt(r,sr.ulid,n.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{or(r,"binary",n.message,e);break}case"contentEncoding:base64":{ue(r,"contentEncoding","base64",n.message,e);break}case"pattern:zod":{pt(r,sr.base64,n.message,e);break}}break}case"nanoid":pt(r,sr.nanoid,n.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function yf(t,e){return e.patternStrategy==="escape"?HA(t):t}function HA(t){let e="";for(let r=0;r<t.length;r++)UA.has(t[r])||(e+="\\"),e+=t[r];return e}function or(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}}})):ue(t,"format",e,r,n)}function pt(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:aS(e,n),...r&&n.errorMessages&&{errorMessage:{pattern:r}}})):ue(t,"pattern",aS(e,n),r,n)}function aS(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
+ ]))`;continue}else if(n[c]==="$"){s+=`($|(?=[\r
62
+ ]))`;continue}}if(r.s&&n[c]==="."){s+=i?`${n[c]}\r
49
63
  `:`[${n[c]}\r
50
- ]`;continue}o+=n[c],n[c]==="\\"?s=!0:i&&n[c]==="]"?i=!1:!i&&n[c]==="["&&(i=!0)}try{new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return o}var $m,Jt,GO,mc=v(()=>{en();Jt={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:()=>($m===void 0&&($m=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),$m),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-_]*$/};GO=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function fc(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===T.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((n,o)=>({...n,[o]:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",o]})??Ae(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===T.ZodString&&t.keyType._def.checks?.length){let{type:n,...o}=pc(t.keyType._def,e);return{...r,propertyNames:o}}else{if(t.keyType?._def.typeName===T.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===T.ZodBranded&&t.keyType._def.type._def.typeName===T.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...o}=lc(t.keyType._def,e);return{...r,propertyNames:o}}}return r}var hc=v(()=>{Es();Ue();mc();dc();Mt()});function nb(t,e){if(e.mapStrategy==="record")return fc(t,e);let r=V(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ae(e),n=V(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ae(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var Tm=v(()=>{Ue();hc();Mt()});function ob(t){let e=t.values,n=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),o=Array.from(new Set(n.map(s=>typeof s)));return{type:o.length===1?o[0]==="string"?"string":"number":["string","number"],enum:n}}var Pm=v(()=>{});function sb(t){return t.target==="openAi"?void 0:{not:Ae({...t,currentPath:[...t.currentPath,"not"]})}}var Rm=v(()=>{Mt()});function ib(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Cm=v(()=>{});function cb(t,e){if(e.target==="openApi3")return ab(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in Xs&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((o,s)=>{let i=Xs[s._def.typeName];return i&&!o.includes(i)?[...o,i]:o},[]);return{type:n.length>1?n:n[0]}}else if(r.every(n=>n._def.typeName==="ZodLiteral"&&!n.description)){let n=r.reduce((o,s)=>{let i=typeof s._def.value;switch(i){case"string":case"number":case"boolean":return[...o,i];case"bigint":return[...o,"integer"];case"object":if(s._def.value===null)return[...o,"null"];default:return o}},[]);if(n.length===r.length){let o=n.filter((s,i,a)=>a.indexOf(s)===i);return{type:o.length>1?o:o[0],enum:r.reduce((s,i)=>s.includes(i._def.value)?s:[...s,i._def.value],[])}}}else if(r.every(n=>n._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((n,o)=>[...n,...o._def.values.filter(s=>!n.includes(s))],[])};return ab(t,e)}var Xs,ab,gc=v(()=>{Ue();Xs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};ab=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((n,o)=>V(n._def,{...e,currentPath:[...e.currentPath,"anyOf",`${o}`]})).filter(n=>!!n&&(!e.strictUnions||typeof n=="object"&&Object.keys(n).length>0));return r.length?{anyOf:r}:void 0}});function ub(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:Xs[t.innerType._def.typeName],nullable:!0}:{type:[Xs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=V(t.innerType._def,{...e,currentPath:[...e.currentPath]});return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let r=V(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}var Om=v(()=>{Ue();gc()});function lb(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",mm(r,"type",n.message,e);break;case"min":e.target==="jsonSchema7"?n.inclusive?ie(r,"minimum",n.value,n.message,e):ie(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ie(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ie(r,"maximum",n.value,n.message,e):ie(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ie(r,"maximum",n.value,n.message,e));break;case"multipleOf":ie(r,"multipleOf",n.value,n.message,e);break}return r}var Im=v(()=>{en()});function db(t,e){let r=e.target==="openAi",n={type:"object",properties:{}},o=[],s=t.shape();for(let a in s){let c=s[a];if(c===void 0||c._def===void 0)continue;let u=YO(c);u&&r&&(c._def.typeName==="ZodOptional"&&(c=c._def.innerType),c.isNullable()||(c=c.nullable()),u=!1);let l=V(c._def,{...e,currentPath:[...e.currentPath,"properties",a],propertyPath:[...e.currentPath,"properties",a]});l!==void 0&&(n.properties[a]=l,u||o.push(a))}o.length&&(n.required=o);let i=JO(t,e);return i!==void 0&&(n.additionalProperties=i),n}function JO(t,e){if(t.catchall._def.typeName!=="ZodNever")return V(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 YO(t){try{return t.isOptional()}catch{return!0}}var Am=v(()=>{Ue()});var pb,Nm=v(()=>{Ue();Mt();pb=(t,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return V(t.innerType._def,e);let r=V(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:Ae(e)},r]}:Ae(e)}});var mb,zm=v(()=>{Ue();mb=(t,e)=>{if(e.pipeStrategy==="input")return V(t.in._def,e);if(e.pipeStrategy==="output")return V(t.out._def,e);let r=V(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=V(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,n].filter(o=>o!==void 0)}}});function fb(t,e){return V(t.type._def,e)}var jm=v(()=>{Ue()});function hb(t,e){let n={type:"array",uniqueItems:!0,items:V(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ie(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ie(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Dm=v(()=>{en();Ue()});function gb(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,n)=>V(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[]),additionalItems:V(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,n)=>V(r._def,{...e,currentPath:[...e.currentPath,"items",`${n}`]})).reduce((r,n)=>n===void 0?r:[...r,n],[])}}var Mm=v(()=>{Ue()});function _b(t){return{not:Ae(t)}}var Lm=v(()=>{Mt()});function yb(t){return Ae(t)}var Fm=v(()=>{Mt()});var xb,Um=v(()=>{Ue();xb=(t,e)=>V(t.innerType._def,e)});var vb,Zm=v(()=>{Es();Mt();fm();hm();gm();dc();_m();xm();vm();bm();Sm();km();wm();Tm();Pm();Rm();Cm();Om();Im();Am();Nm();zm();jm();hc();Dm();mc();Mm();Lm();gc();Fm();Um();vb=(t,e,r)=>{switch(e){case T.ZodString:return pc(t,r);case T.ZodNumber:return lb(t,r);case T.ZodObject:return db(t,r);case T.ZodBigInt:return Gv(t,r);case T.ZodBoolean:return Kv();case T.ZodDate:return ym(t,r);case T.ZodUndefined:return _b(r);case T.ZodNull:return ib(r);case T.ZodArray:return Wv(t,r);case T.ZodUnion:case T.ZodDiscriminatedUnion:return cb(t,r);case T.ZodIntersection:return eb(t,r);case T.ZodTuple:return gb(t,r);case T.ZodRecord:return fc(t,r);case T.ZodLiteral:return tb(t,r);case T.ZodEnum:return Qv(t);case T.ZodNativeEnum:return ob(t);case T.ZodNullable:return ub(t,r);case T.ZodOptional:return pb(t,r);case T.ZodMap:return nb(t,r);case T.ZodSet:return hb(t,r);case T.ZodLazy:return()=>t.getter()._def;case T.ZodPromise:return fb(t,r);case T.ZodNaN:case T.ZodNever:return sb(r);case T.ZodEffects:return Xv(t,r);case T.ZodAny:return Ae(r);case T.ZodUnknown:return yb(r);case T.ZodDefault:return Yv(t,r);case T.ZodBranded:return lc(t,r);case T.ZodReadonly:return xb(t,r);case T.ZodCatch:return Jv(t,r);case T.ZodPipeline:return mb(t,r);case T.ZodFunction:case T.ZodVoid:case T.ZodSymbol:return;default:return(n=>{})(e)}}});function V(t,e,r=!1){let n=e.seen.get(t);if(e.override){let a=e.override?.(t,e,n,r);if(a!==qv)return a}if(n&&!r){let a=XO(n,e);if(a!==void 0)return a}let o={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,o);let s=vb(t,t.typeName,e),i=typeof s=="function"?V(s(),e):s;if(i&&QO(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return o.jsonSchema=i,a}return o.jsonSchema=i,i}var XO,QO,Ue=v(()=>{ac();Zm();uc();Mt();XO=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:cc(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`),Ae(e)):e.$refStrategy==="seen"?Ae(e):void 0}},QO=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var bb=v(()=>{});var Hm,qm=v(()=>{Ue();pm();Mt();Hm=(t,e)=>{let r=Vv(e),n=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((c,[u,l])=>({...c,[u]:V(l._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??Ae(r)}),{}):void 0,o=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=V(t._def,o===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,o]},!1)??Ae(r),i=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;i!==void 0&&(s.title=i),r.flags.hasReferencedOpenAiAnyType&&(n||(n={}),n[r.openAiAnyTypeName]||(n[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let a=o===void 0?n?{...s,[r.definitionPath]:n}:s:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,o].join("/"),[r.definitionPath]:{...n,[o]:s}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a}});var Sb=v(()=>{ac();pm();en();uc();Ue();bb();Mt();fm();hm();gm();dc();_m();xm();vm();bm();Sm();km();wm();Tm();Pm();Rm();Cm();Om();Im();Am();Nm();zm();jm();Um();hc();Dm();mc();Mm();Lm();gc();Fm();Zm();qm();qm()});function eI(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Bm(t,e){return zt(t)?Ip(t,{target:eI(e?.target),io:e?.pipeStrategy??"input"}):Hm(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function Vm(t){let r=Yr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fa(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function Wm(t,e){let r=Jr(t,e);if(!r.success)throw r.error;return r.data}var Gm=v(()=>{zp();Ls();Sb()});function kb(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function wb(t,e){let r={...t};for(let n in e){let o=n,s=e[o];if(s===void 0)continue;let i=r[o];kb(i)&&kb(s)?r[o]={...i,...s}:r[o]=s}return r}var tI,_c,$b=v(()=>{Ls();Un();Zv();Gm();tI=6e4,_c=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(Wa,r=>{this._oncancel(r)}),this.setNotificationHandler(Ka,r=>{this._onprogress(r)}),this.setRequestHandler(Ga,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Ja,async(r,n)=>{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new D(Z.InvalidParams,"Failed to retrieve task: Task not found");return{...o}}),this.setRequestHandler(Xa,async(r,n)=>{let o=async()=>{let s=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(s,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,l=this._requestResolvers.get(u);if(l)if(this._requestResolvers.delete(u),a.type==="response")l(c);else{let d=c,p=new D(d.error.code,d.error.message,d.error.data);l(p)}else{let d=a.type==="response"?"Response":"Error";this._onerror(new Error(`${d} handler missing for request ${u}`))}continue}await this._transport?.send(a.message,{relatedRequestId:n.requestId})}}let i=await this._taskStore.getTask(s,n.sessionId);if(!i)throw new D(Z.InvalidParams,`Task not found: ${s}`);if(!Qr(i.status))return await this._waitForTaskUpdate(s,n.signal),await o();if(Qr(i.status)){let a=await this._taskStore.getTaskResult(s,n.sessionId);return this._clearTaskQueue(s),{...a,_meta:{...a._meta,[Xr]:{taskId:s}}}}return await o()};return await o()}),this.setRequestHandler(Qa,async(r,n)=>{try{let{tasks:o,nextCursor:s}=await this._taskStore.listTasks(r.params?.cursor,n.sessionId);return{tasks:o,nextCursor:s,_meta:{}}}catch(o){throw new D(Z.InvalidParams,`Failed to list tasks: ${o instanceof Error?o.message:String(o)}`)}}),this.setRequestHandler(tc,async(r,n)=>{try{let o=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!o)throw new D(Z.InvalidParams,`Task not found: ${r.params.taskId}`);if(Qr(o.status))throw new D(Z.InvalidParams,`Cannot cancel task in terminal status: ${o.status}`);await this._taskStore.updateTaskStatus(r.params.taskId,"cancelled","Client cancelled task execution.",n.sessionId),this._clearTaskQueue(r.params.taskId);let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new D(Z.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...s}}catch(o){throw o instanceof D?o:new D(Z.InvalidRequest,`Failed to cancel task: ${o instanceof Error?o.message:String(o)}`)}}))}async _oncancel(e){if(!e.params.requestId)return;this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,r,n,o,s=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(o,r),startTime:Date.now(),timeout:r,maxTotalTimeout:n,resetTimeoutOnProgress:s,onTimeout:o})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let n=Date.now()-r.startTime;if(r.maxTotalTimeout&&n>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),D.fromError(Z.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:n});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){if(this._transport)throw new Error("Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.");this._transport=e;let r=this.transport?.onclose;this._transport.onclose=()=>{r?.(),this._onclose()};let n=this.transport?.onerror;this._transport.onerror=s=>{n?.(s),this._onerror(s)};let o=this._transport?.onmessage;this._transport.onmessage=(s,i)=>{o?.(s,i),Hs(s)||Ov(s)?this._onresponse(s):Xp(s)?this._onrequest(s,i):Cv(s)?this._onnotification(s):this._onerror(new Error(`Unknown message type: ${JSON.stringify(s)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let n of this._timeoutInfo.values())clearTimeout(n.timeoutId);this._timeoutInfo.clear();for(let n of this._requestHandlerAbortControllers.values())n.abort();this._requestHandlerAbortControllers.clear();let r=D.fromError(Z.ConnectionClosed,"Connection closed");this._transport=void 0,this.onclose?.();for(let n of e.values())n(r)}_onerror(e){this.onerror?.(e)}_onnotification(e){let r=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;r!==void 0&&Promise.resolve().then(()=>r(e)).catch(n=>this._onerror(new Error(`Uncaught error in notification handler: ${n}`)))}_onrequest(e,r){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,o=this._transport,s=e.params?._meta?.[Xr]?.taskId;if(n===void 0){let l={jsonrpc:"2.0",id:e.id,error:{code:Z.MethodNotFound,message:"Method not found"}};s&&this._taskMessageQueue?this._enqueueTaskMessage(s,{type:"error",message:l,timestamp:Date.now()},o?.sessionId).catch(d=>this._onerror(new Error(`Failed to enqueue error response: ${d}`))):o?.send(l).catch(d=>this._onerror(new Error(`Failed to send an error response: ${d}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let a=Tv(e.params)?e.params.task:void 0,c=this._taskStore?this.requestTaskStore(e,o?.sessionId):void 0,u={signal:i.signal,sessionId:o?.sessionId,_meta:e.params?._meta,sendNotification:async l=>{if(i.signal.aborted)return;let d={relatedRequestId:e.id};s&&(d.relatedTask={taskId:s}),await this.notification(l,d)},sendRequest:async(l,d,p)=>{if(i.signal.aborted)throw new D(Z.ConnectionClosed,"Request was cancelled");let f={...p,relatedRequestId:e.id};s&&!f.relatedTask&&(f.relatedTask={taskId:s});let m=f.relatedTask?.taskId??s;return m&&c&&await c.updateTaskStatus(m,"input_required"),await this.request(l,d,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId:s,taskStore:c,taskRequestedTtl:a?.ttl,closeSSEStream:r?.closeSSEStream,closeStandaloneSSEStream:r?.closeStandaloneSSEStream};Promise.resolve().then(()=>{a&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,u)).then(async l=>{if(i.signal.aborted)return;let d={result:l,jsonrpc:"2.0",id:e.id};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"response",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)},async l=>{if(i.signal.aborted)return;let d={jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(l.code)?l.code:Z.InternalError,message:l.message??"Internal error",...l.data!==void 0&&{data:l.data}}};s&&this._taskMessageQueue?await this._enqueueTaskMessage(s,{type:"error",message:d,timestamp:Date.now()},o?.sessionId):await o?.send(d)}).catch(l=>this._onerror(new Error(`Failed to send response: ${l}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===i&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...n}=e.params,o=Number(r),s=this._progressHandlers.get(o);if(!s){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let i=this._responseHandlers.get(o),a=this._timeoutInfo.get(o);if(a&&i&&a.resetTimeoutOnProgress)try{this._resetTimeout(o)}catch(c){this._responseHandlers.delete(o),this._progressHandlers.delete(o),this._cleanupTimeout(o),i(c);return}s(n)}_onresponse(e){let r=Number(e.id),n=this._requestResolvers.get(r);if(n){if(this._requestResolvers.delete(r),Hs(e))n(e);else{let i=new D(e.error.code,e.error.message,e.error.data);n(i)}return}let o=this._responseHandlers.get(r);if(o===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(r),this._cleanupTimeout(r);let s=!1;if(Hs(e)&&e.result&&typeof e.result=="object"){let i=e.result;if(i.task&&typeof i.task=="object"){let a=i.task;typeof a.taskId=="string"&&(s=!0,this._taskProgressTokens.set(a.taskId,r))}}if(s||this._progressHandlers.delete(r),Hs(e))o(e);else{let i=D.fromError(e.error.code,e.error.message,e.error.data);o(i)}}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,r,n){let{task:o}=n??{};if(!o){try{yield{type:"result",result:await this.request(e,r,n)}}catch(i){yield{type:"error",error:i instanceof D?i:new D(Z.InternalError,String(i))}}return}let s;try{let i=await this.request(e,Po,n);if(i.task)s=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new D(Z.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:s},n);if(yield{type:"taskStatus",task:a},Qr(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)}:a.status==="failed"?yield{type:"error",error:new D(Z.InternalError,`Task ${s} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new D(Z.InternalError,`Task ${s} was cancelled`)});return}if(a.status==="input_required"){yield{type:"result",result:await this.getTaskResult({taskId:s},r,n)};return}let c=a.pollInterval??this._options?.defaultTaskPollInterval??1e3;await new Promise(u=>setTimeout(u,c)),n?.signal?.throwIfAborted()}}catch(i){yield{type:"error",error:i instanceof D?i:new D(Z.InternalError,String(i))}}}request(e,r,n){let{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i,task:a,relatedTask:c}=n??{};return new Promise((u,l)=>{let d=_=>{l(_)};if(!this._transport){d(new Error("Not connected"));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),a&&this.assertTaskCapability(e.method)}catch(_){d(_);return}n?.signal?.throwIfAborted();let p=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:p};n?.onprogress&&(this._progressHandlers.set(p,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:p}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Xr]:c}});let m=_=>{this._responseHandlers.delete(p),this._progressHandlers.delete(p),this._cleanupTimeout(p),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:p,reason:String(_)}},{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(k=>this._onerror(new Error(`Failed to send cancellation: ${k}`)));let x=_ instanceof D?_:new D(Z.RequestTimeout,String(_));l(x)};this._responseHandlers.set(p,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return l(_);try{let x=Jr(r,_.result);x.success?u(x.data):l(x.error)}catch(x){l(x)}}}),n?.signal?.addEventListener("abort",()=>{m(n?.signal?.reason)});let h=n?.timeout??tI,g=()=>m(D.fromError(Z.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(p,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=x=>{let k=this._responseHandlers.get(p);k?k(x):this._onerror(new Error(`Response handler missing for side-channeled request ${p}`))};this._requestResolvers.set(p,_),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(p),l(x)})}else this._transport.send(f,{relatedRequestId:o,resumptionToken:s,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(p),l(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},Ya,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},ec,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Nv,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||{},[Xr]: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||{},[Xr]: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||{},[Xr]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=Vm(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(o,s)=>{let i=Wm(e,o);return Promise.resolve(r(i,s))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){let n=Vm(e);this._notificationHandlers.set(n,o=>{let s=Wm(e,o);return Promise.resolve(r(s))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let r=this._taskProgressTokens.get(e);r!==void 0&&(this._progressHandlers.delete(r),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,r,n){if(!this._taskStore||!this._taskMessageQueue)throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");let o=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,r,n,o)}async _clearTaskQueue(e,r){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,r);for(let o of n)if(o.type==="request"&&Xp(o.message)){let s=o.message.id,i=this._requestResolvers.get(s);i?(i(new D(Z.InternalError,"Task cancelled or completed")),this._requestResolvers.delete(s)):this._onerror(new Error(`Resolver missing for request ${s} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,r){let n=this._options?.defaultTaskPollInterval??1e3;try{let o=await this._taskStore?.getTask(e);o?.pollInterval&&(n=o.pollInterval)}catch{}return new Promise((o,s)=>{if(r.aborted){s(new D(Z.InvalidRequest,"Request cancelled"));return}let i=setTimeout(o,n);r.addEventListener("abort",()=>{clearTimeout(i),s(new D(Z.InvalidRequest,"Request cancelled"))},{once:!0})})}requestTaskStore(e,r){let n=this._taskStore;if(!n)throw new Error("No task store configured");return{createTask:async o=>{if(!e)throw new Error("No request provided");return await n.createTask(o,e.id,{method:e.method,params:e.params},r)},getTask:async o=>{let s=await n.getTask(o,r);if(!s)throw new D(Z.InvalidParams,"Failed to retrieve task: Task not found");return s},storeTaskResult:async(o,s,i)=>{await n.storeTaskResult(o,s,i,r);let a=await n.getTask(o,r);if(a){let c=Gs.parse({method:"notifications/tasks/status",params:a});await this.notification(c),Qr(a.status)&&this._cleanupTaskProgressHandler(o)}},getTaskResult:o=>n.getTaskResult(o,r),updateTaskStatus:async(o,s,i)=>{let a=await n.getTask(o,r);if(!a)throw new D(Z.InvalidParams,`Task "${o}" not found - it may have been cleaned up`);if(Qr(a.status))throw new D(Z.InvalidParams,`Cannot update task "${o}" from terminal status "${a.status}" to "${s}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(o,s,i,r);let c=await n.getTask(o,r);if(c){let u=Gs.parse({method:"notifications/tasks/status",params:c});await this.notification(u),Qr(c.status)&&this._cleanupTaskProgressHandler(o)}},listTasks:o=>n.listTasks(o,r)}}}});var ti=C(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.regexpCode=de.getEsmExportName=de.getProperty=de.safeStringify=de.stringify=de.strConcat=de.addCodeArg=de.str=de._=de.nil=de._Code=de.Name=de.IDENTIFIER=de._CodeOrName=void 0;var Qs=class{};de._CodeOrName=Qs;de.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Zn=class extends Qs{constructor(e){if(super(),!de.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}}};de.Name=Zn;var Lt=class extends Qs{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 Zn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};de._Code=Lt;de.nil=new Lt("");function Eb(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Jm(r,e[n]),r.push(t[++n]);return new Lt(r)}de._=Eb;var Km=new Lt("+");function Tb(t,...e){let r=[ei(t[0])],n=0;for(;n<e.length;)r.push(Km),Jm(r,e[n]),r.push(Km,ei(t[++n]));return rI(r),new Lt(r)}de.str=Tb;function Jm(t,e){e instanceof Lt?t.push(...e._items):e instanceof Zn?t.push(e):t.push(sI(e))}de.addCodeArg=Jm;function rI(t){let e=1;for(;e<t.length-1;){if(t[e]===Km){let r=nI(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function nI(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Zn||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 Zn))return`"${t}${e.slice(1)}`}function oI(t,e){return e.emptyStr()?t:t.emptyStr()?e:Tb`${t}${e}`}de.strConcat=oI;function sI(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:ei(Array.isArray(t)?t.join(","):t)}function iI(t){return new Lt(ei(t))}de.stringify=iI;function ei(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}de.safeStringify=ei;function aI(t){return typeof t=="string"&&de.IDENTIFIER.test(t)?new Lt(`.${t}`):Eb`[${t}]`}de.getProperty=aI;function cI(t){if(typeof t=="string"&&de.IDENTIFIER.test(t))return new Lt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}de.getEsmExportName=cI;function uI(t){return new Lt(t.toString())}de.regexpCode=uI});var Qm=C(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.ValueScope=_t.ValueScopeName=_t.Scope=_t.varKinds=_t.UsedValueState=void 0;var gt=ti(),Ym=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},yc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(yc||(_t.UsedValueState=yc={}));_t.varKinds={const:new gt.Name("const"),let:new gt.Name("let"),var:new gt.Name("var")};var xc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof gt.Name?e:this.name(e)}name(e){return new gt.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=xc;var vc=class extends gt.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,gt._)`.${new gt.Name(r)}[${n}]`}};_t.ValueScopeName=vc;var lI=(0,gt._)`\n`,Xm=class extends xc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?lI:gt.nil}}get(){return this._scope}name(e){return new vc(e,this._newName(e))}value(e,r){var n;if(r.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(e),{prefix:s}=o,i=(n=r.key)!==null&&n!==void 0?n:r.ref,a=this._values[s];if(a){let l=a.get(i);if(l)return l}else a=this._values[s]=new Map;a.set(i,o);let c=this._scope[s]||(this._scope[s]=[]),u=c.length;return c[u]=r.ref,o.setValue(r,{property:s,itemIndex:u}),o}getValue(e,r){let n=this._values[e];if(n)return n.get(r)}scopeRefs(e,r=this._values){return this._reduceValues(r,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,gt._)`${e}${n.scopePath}`})}scopeCode(e=this._values,r,n){return this._reduceValues(e,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},r,n)}_reduceValues(e,r,n={},o){let s=gt.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,yc.Started);let l=r(u);if(l){let d=this.opts.es5?_t.varKinds.var:_t.varKinds.const;s=(0,gt._)`${s}${d} ${u} = ${l};${this.opts._n}`}else if(l=o?.(u))s=(0,gt._)`${s}${l}${this.opts._n}`;else throw new Ym(u);c.set(u,yc.Completed)})}return s}};_t.ValueScope=Xm});var Q=C(ee=>{"use strict";Object.defineProperty(ee,"__esModule",{value:!0});ee.or=ee.and=ee.not=ee.CodeGen=ee.operators=ee.varKinds=ee.ValueScopeName=ee.ValueScope=ee.Scope=ee.Name=ee.regexpCode=ee.stringify=ee.getProperty=ee.nil=ee.strConcat=ee.str=ee._=void 0;var ae=ti(),Xt=Qm(),tn=ti();Object.defineProperty(ee,"_",{enumerable:!0,get:function(){return tn._}});Object.defineProperty(ee,"str",{enumerable:!0,get:function(){return tn.str}});Object.defineProperty(ee,"strConcat",{enumerable:!0,get:function(){return tn.strConcat}});Object.defineProperty(ee,"nil",{enumerable:!0,get:function(){return tn.nil}});Object.defineProperty(ee,"getProperty",{enumerable:!0,get:function(){return tn.getProperty}});Object.defineProperty(ee,"stringify",{enumerable:!0,get:function(){return tn.stringify}});Object.defineProperty(ee,"regexpCode",{enumerable:!0,get:function(){return tn.regexpCode}});Object.defineProperty(ee,"Name",{enumerable:!0,get:function(){return tn.Name}});var wc=Qm();Object.defineProperty(ee,"Scope",{enumerable:!0,get:function(){return wc.Scope}});Object.defineProperty(ee,"ValueScope",{enumerable:!0,get:function(){return wc.ValueScope}});Object.defineProperty(ee,"ValueScopeName",{enumerable:!0,get:function(){return wc.ValueScopeName}});Object.defineProperty(ee,"varKinds",{enumerable:!0,get:function(){return wc.varKinds}});ee.operators={GT:new ae._Code(">"),GTE:new ae._Code(">="),LT:new ae._Code("<"),LTE:new ae._Code("<="),EQ:new ae._Code("==="),NEQ:new ae._Code("!=="),NOT:new ae._Code("!"),OR:new ae._Code("||"),AND:new ae._Code("&&"),ADD:new ae._Code("+")};var Cr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},ef=class extends Cr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?Xt.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+r}optimizeNames(e,r){if(e[this.name.str])return this.rhs&&(this.rhs=jo(this.rhs,e,r)),this}get names(){return this.rhs instanceof ae._CodeOrName?this.rhs.names:{}}},bc=class extends Cr{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 ae.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=jo(this.rhs,e,r),this}get names(){let e=this.lhs instanceof ae.Name?{}:{...this.lhs.names};return kc(e,this.rhs)}},tf=class extends bc{constructor(e,r,n,o){super(e,n,o),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},rf=class extends Cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},nf=class extends Cr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},of=class extends Cr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},sf=class extends Cr{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=jo(this.code,e,r),this}get names(){return this.code instanceof ae._CodeOrName?this.code.names:{}}},ri=class extends Cr{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((r,n)=>r+n.render(e),"")}optimizeNodes(){let{nodes:e}=this,r=e.length;for(;r--;){let n=e[r].optimizeNodes();Array.isArray(n)?e.splice(r,1,...n):n?e[r]=n:e.splice(r,1)}return e.length>0?this:void 0}optimizeNames(e,r){let{nodes:n}=this,o=n.length;for(;o--;){let s=n[o];s.optimizeNames(e,r)||(dI(e,s.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>Bn(e,r.names),{})}},Or=class extends ri{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},af=class extends ri{},zo=class extends Or{};zo.kind="else";var Hn=class t extends Or{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 zo(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(Pb(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=jo(this.condition,e,r),this}get names(){let e=super.names;return kc(e,this.condition),this.else&&Bn(e,this.else.names),e}};Hn.kind="if";var qn=class extends Or{};qn.kind="for";var cf=class extends qn{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=jo(this.iteration,e,r),this}get names(){return Bn(super.names,this.iteration.names)}},uf=class extends qn{constructor(e,r,n,o){super(),this.varKind=e,this.name=r,this.from=n,this.to=o}render(e){let r=e.es5?Xt.varKinds.var:this.varKind,{name:n,from:o,to:s}=this;return`for(${r} ${n}=${o}; ${n}<${s}; ${n}++)`+super.render(e)}get names(){let e=kc(super.names,this.from);return kc(e,this.to)}},Sc=class extends qn{constructor(e,r,n,o){super(),this.loop=e,this.varKind=r,this.name=n,this.iterable=o}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,r){if(super.optimizeNames(e,r))return this.iterable=jo(this.iterable,e,r),this}get names(){return Bn(super.names,this.iterable.names)}},ni=class extends Or{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)}};ni.kind="func";var oi=class extends ri{render(e){return"return "+super.render(e)}};oi.kind="return";var lf=class extends Or{render(e){let r="try"+super.render(e);return this.catch&&(r+=this.catch.render(e)),this.finally&&(r+=this.finally.render(e)),r}optimizeNodes(){var e,r;return super.optimizeNodes(),(e=this.catch)===null||e===void 0||e.optimizeNodes(),(r=this.finally)===null||r===void 0||r.optimizeNodes(),this}optimizeNames(e,r){var n,o;return super.optimizeNames(e,r),(n=this.catch)===null||n===void 0||n.optimizeNames(e,r),(o=this.finally)===null||o===void 0||o.optimizeNames(e,r),this}get names(){let e=super.names;return this.catch&&Bn(e,this.catch.names),this.finally&&Bn(e,this.finally.names),e}},si=class extends Or{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};si.kind="catch";var ii=class extends Or{render(e){return"finally"+super.render(e)}};ii.kind="finally";var df=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
51
- `:""},this._extScope=e,this._scope=new Xt.Scope({parent:e}),this._nodes=[new af]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,r){let n=this._extScope.value(e,r);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,r){return this._extScope.getValue(e,r)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,r,n,o){let s=this._scope.toName(r);return n!==void 0&&o&&(this._constants[s.str]=n),this._leafNode(new ef(e,s,n)),s}const(e,r,n){return this._def(Xt.varKinds.const,e,r,n)}let(e,r,n){return this._def(Xt.varKinds.let,e,r,n)}var(e,r,n){return this._def(Xt.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new bc(e,r,n))}add(e,r){return this._leafNode(new tf(e,ee.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==ae.nil&&this._leafNode(new sf(e)),this}object(...e){let r=["{"];for(let[n,o]of e)r.length>1&&r.push(","),r.push(n),(n!==o||this.opts.es5)&&(r.push(":"),(0,ae.addCodeArg)(r,o));return r.push("}"),new ae._Code(r)}if(e,r,n){if(this._blockNode(new Hn(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 Hn(e))}else(){return this._elseNode(new zo)}endIf(){return this._endBlockNode(Hn,zo)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new cf(e),r)}forRange(e,r,n,o,s=this.opts.es5?Xt.varKinds.var:Xt.varKinds.let){let i=this._scope.toName(e);return this._for(new uf(s,i,r,n),()=>o(i))}forOf(e,r,n,o=Xt.varKinds.const){let s=this._scope.toName(e);if(this.opts.es5){let i=r instanceof ae.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,ae._)`${i}.length`,a=>{this.var(s,(0,ae._)`${i}[${a}]`),n(s)})}return this._for(new Sc("of",o,s,r),()=>n(s))}forIn(e,r,n,o=this.opts.es5?Xt.varKinds.var:Xt.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,ae._)`Object.keys(${r})`,n);let s=this._scope.toName(e);return this._for(new Sc("in",o,s,r),()=>n(s))}endFor(){return this._endBlockNode(qn)}label(e){return this._leafNode(new rf(e))}break(e){return this._leafNode(new nf(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 o=new lf;if(this._blockNode(o),this.code(e),r){let s=this.name("e");this._currNode=o.catch=new si(s),r(s)}return n&&(this._currNode=o.finally=new ii,this.code(n)),this._endBlockNode(si,ii)}throw(e){return this._leafNode(new of(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=ae.nil,n,o){return this._blockNode(new ni(e,r,n)),o&&this.code(o).endFunc(),this}endFunc(){return this._endBlockNode(ni)}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 Hn))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}};ee.CodeGen=df;function Bn(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function kc(t,e){return e instanceof ae._CodeOrName?Bn(t,e.names):t}function jo(t,e,r){if(t instanceof ae.Name)return n(t);if(!o(t))return t;return new ae._Code(t._items.reduce((s,i)=>(i instanceof ae.Name&&(i=n(i)),i instanceof ae._Code?s.push(...i._items):s.push(i),s),[]));function n(s){let i=r[s.str];return i===void 0||e[s.str]!==1?s:(delete e[s.str],i)}function o(s){return s instanceof ae._Code&&s._items.some(i=>i instanceof ae.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function dI(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function Pb(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,ae._)`!${pf(t)}`}ee.not=Pb;var pI=Rb(ee.operators.AND);function mI(...t){return t.reduce(pI)}ee.and=mI;var fI=Rb(ee.operators.OR);function hI(...t){return t.reduce(fI)}ee.or=hI;function Rb(t){return(e,r)=>e===ae.nil?r:r===ae.nil?e:(0,ae._)`${pf(e)} ${t} ${pf(r)}`}function pf(t){return t instanceof ae.Name?t:(0,ae._)`(${t})`}});var ue=C(te=>{"use strict";Object.defineProperty(te,"__esModule",{value:!0});te.checkStrictMode=te.getErrorPath=te.Type=te.useFunc=te.setEvaluated=te.evaluatedPropsToName=te.mergeEvaluated=te.eachItem=te.unescapeJsonPointer=te.escapeJsonPointer=te.escapeFragment=te.unescapeFragment=te.schemaRefOrVal=te.schemaHasRulesButRef=te.schemaHasRules=te.checkUnknownRules=te.alwaysValidSchema=te.toHash=void 0;var xe=Q(),gI=ti();function _I(t){let e={};for(let r of t)e[r]=!0;return e}te.toHash=_I;function yI(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(Ib(t,e),!Ab(e,t.self.RULES.all))}te.alwaysValidSchema=yI;function Ib(t,e=t.schema){let{opts:r,self:n}=t;if(!r.strictSchema||typeof e=="boolean")return;let o=n.RULES.keywords;for(let s in e)o[s]||jb(t,`unknown keyword: "${s}"`)}te.checkUnknownRules=Ib;function Ab(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}te.schemaHasRules=Ab;function xI(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}te.schemaHasRulesButRef=xI;function vI({topSchemaRef:t,schemaPath:e},r,n,o){if(!o){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,xe._)`${r}`}return(0,xe._)`${t}${e}${(0,xe.getProperty)(n)}`}te.schemaRefOrVal=vI;function bI(t){return Nb(decodeURIComponent(t))}te.unescapeFragment=bI;function SI(t){return encodeURIComponent(ff(t))}te.escapeFragment=SI;function ff(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}te.escapeJsonPointer=ff;function Nb(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}te.unescapeJsonPointer=Nb;function kI(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}te.eachItem=kI;function Cb({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(o,s,i,a)=>{let c=i===void 0?s:i instanceof xe.Name?(s instanceof xe.Name?t(o,s,i):e(o,s,i),i):s instanceof xe.Name?(e(o,i,s),s):r(s,i);return a===xe.Name&&!(c instanceof xe.Name)?n(o,c):c}}te.mergeEvaluated={props:Cb({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,xe._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,xe._)`${r} || {}`).code((0,xe._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,xe._)`${r} || {}`),hf(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:zb}),items:Cb({mergeNames:(t,e,r)=>t.if((0,xe._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,xe._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,xe._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,xe._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function zb(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,xe._)`{}`);return e!==void 0&&hf(t,r,e),r}te.evaluatedPropsToName=zb;function hf(t,e,r){Object.keys(r).forEach(n=>t.assign((0,xe._)`${e}${(0,xe.getProperty)(n)}`,!0))}te.setEvaluated=hf;var Ob={};function wI(t,e){return t.scopeValue("func",{ref:e,code:Ob[e.code]||(Ob[e.code]=new gI._Code(e.code))})}te.useFunc=wI;var mf;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(mf||(te.Type=mf={}));function $I(t,e,r){if(t instanceof xe.Name){let n=e===mf.Num;return r?n?(0,xe._)`"[" + ${t} + "]"`:(0,xe._)`"['" + ${t} + "']"`:n?(0,xe._)`"/" + ${t}`:(0,xe._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,xe.getProperty)(t).toString():"/"+ff(t)}te.getErrorPath=$I;function jb(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}te.checkStrictMode=jb});var Ir=C(gf=>{"use strict";Object.defineProperty(gf,"__esModule",{value:!0});var tt=Q(),EI={data:new tt.Name("data"),valCxt:new tt.Name("valCxt"),instancePath:new tt.Name("instancePath"),parentData:new tt.Name("parentData"),parentDataProperty:new tt.Name("parentDataProperty"),rootData:new tt.Name("rootData"),dynamicAnchors:new tt.Name("dynamicAnchors"),vErrors:new tt.Name("vErrors"),errors:new tt.Name("errors"),this:new tt.Name("this"),self:new tt.Name("self"),scope:new tt.Name("scope"),json:new tt.Name("json"),jsonPos:new tt.Name("jsonPos"),jsonLen:new tt.Name("jsonLen"),jsonPart:new tt.Name("jsonPart")};gf.default=EI});var ai=C(rt=>{"use strict";Object.defineProperty(rt,"__esModule",{value:!0});rt.extendErrors=rt.resetErrorsCount=rt.reportExtraError=rt.reportError=rt.keyword$DataError=rt.keywordError=void 0;var le=Q(),$c=ue(),ut=Ir();rt.keywordError={message:({keyword:t})=>(0,le.str)`must pass "${t}" keyword validation`};rt.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,le.str)`"${t}" keyword must be ${e} ($data)`:(0,le.str)`"${t}" keyword is invalid ($data)`};function TI(t,e=rt.keywordError,r,n){let{it:o}=t,{gen:s,compositeRule:i,allErrors:a}=o,c=Lb(t,e,r);n??(i||a)?Db(s,c):Mb(o,(0,le._)`[${c}]`)}rt.reportError=TI;function PI(t,e=rt.keywordError,r){let{it:n}=t,{gen:o,compositeRule:s,allErrors:i}=n,a=Lb(t,e,r);Db(o,a),s||i||Mb(n,ut.default.vErrors)}rt.reportExtraError=PI;function RI(t,e){t.assign(ut.default.errors,e),t.if((0,le._)`${ut.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,le._)`${ut.default.vErrors}.length`,e),()=>t.assign(ut.default.vErrors,null)))}rt.resetErrorsCount=RI;function CI({gen:t,keyword:e,schemaValue:r,data:n,errsCount:o,it:s}){if(o===void 0)throw new Error("ajv implementation error");let i=t.name("err");t.forRange("i",o,ut.default.errors,a=>{t.const(i,(0,le._)`${ut.default.vErrors}[${a}]`),t.if((0,le._)`${i}.instancePath === undefined`,()=>t.assign((0,le._)`${i}.instancePath`,(0,le.strConcat)(ut.default.instancePath,s.errorPath))),t.assign((0,le._)`${i}.schemaPath`,(0,le.str)`${s.errSchemaPath}/${e}`),s.opts.verbose&&(t.assign((0,le._)`${i}.schema`,r),t.assign((0,le._)`${i}.data`,n))})}rt.extendErrors=CI;function Db(t,e){let r=t.const("err",e);t.if((0,le._)`${ut.default.vErrors} === null`,()=>t.assign(ut.default.vErrors,(0,le._)`[${r}]`),(0,le._)`${ut.default.vErrors}.push(${r})`),t.code((0,le._)`${ut.default.errors}++`)}function Mb(t,e){let{gen:r,validateName:n,schemaEnv:o}=t;o.$async?r.throw((0,le._)`new ${t.ValidationError}(${e})`):(r.assign((0,le._)`${n}.errors`,e),r.return(!1))}var Vn={keyword:new le.Name("keyword"),schemaPath:new le.Name("schemaPath"),params:new le.Name("params"),propertyName:new le.Name("propertyName"),message:new le.Name("message"),schema:new le.Name("schema"),parentSchema:new le.Name("parentSchema")};function Lb(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,le._)`{}`:OI(t,e,r)}function OI(t,e,r={}){let{gen:n,it:o}=t,s=[II(o,r),AI(t,r)];return NI(t,e,s),n.object(...s)}function II({errorPath:t},{instancePath:e}){let r=e?(0,le.str)`${t}${(0,$c.getErrorPath)(e,$c.Type.Str)}`:t;return[ut.default.instancePath,(0,le.strConcat)(ut.default.instancePath,r)]}function AI({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let o=n?e:(0,le.str)`${e}/${t}`;return r&&(o=(0,le.str)`${o}${(0,$c.getErrorPath)(r,$c.Type.Str)}`),[Vn.schemaPath,o]}function NI(t,{params:e,message:r},n){let{keyword:o,data:s,schemaValue:i,it:a}=t,{opts:c,propertyName:u,topSchemaRef:l,schemaPath:d}=a;n.push([Vn.keyword,o],[Vn.params,typeof e=="function"?e(t):e||(0,le._)`{}`]),c.messages&&n.push([Vn.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([Vn.schema,i],[Vn.parentSchema,(0,le._)`${l}${d}`],[ut.default.data,s]),u&&n.push([Vn.propertyName,u])}});var Ub=C(Do=>{"use strict";Object.defineProperty(Do,"__esModule",{value:!0});Do.boolOrEmptySchema=Do.topBoolOrEmptySchema=void 0;var zI=ai(),jI=Q(),DI=Ir(),MI={message:"boolean schema is false"};function LI(t){let{gen:e,schema:r,validateName:n}=t;r===!1?Fb(t,!1):typeof r=="object"&&r.$async===!0?e.return(DI.default.data):(e.assign((0,jI._)`${n}.errors`,null),e.return(!0))}Do.topBoolOrEmptySchema=LI;function FI(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),Fb(t)):r.var(e,!0)}Do.boolOrEmptySchema=FI;function Fb(t,e){let{gen:r,data:n}=t,o={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,zI.reportError)(o,MI,void 0,e)}});var _f=C(Mo=>{"use strict";Object.defineProperty(Mo,"__esModule",{value:!0});Mo.getRules=Mo.isJSONType=void 0;var UI=["string","number","integer","boolean","null","object","array"],ZI=new Set(UI);function HI(t){return typeof t=="string"&&ZI.has(t)}Mo.isJSONType=HI;function qI(){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:{}}}Mo.getRules=qI});var yf=C(rn=>{"use strict";Object.defineProperty(rn,"__esModule",{value:!0});rn.shouldUseRule=rn.shouldUseGroup=rn.schemaHasRulesForType=void 0;function BI({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&Zb(t,n)}rn.schemaHasRulesForType=BI;function Zb(t,e){return e.rules.some(r=>Hb(t,r))}rn.shouldUseGroup=Zb;function Hb(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))}rn.shouldUseRule=Hb});var ci=C(nt=>{"use strict";Object.defineProperty(nt,"__esModule",{value:!0});nt.reportTypeError=nt.checkDataTypes=nt.checkDataType=nt.coerceAndCheckDataType=nt.getJSONTypes=nt.getSchemaTypes=nt.DataType=void 0;var VI=_f(),WI=yf(),GI=ai(),Y=Q(),qb=ue(),Lo;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Lo||(nt.DataType=Lo={}));function KI(t){let e=Bb(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}nt.getSchemaTypes=KI;function Bb(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(VI.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}nt.getJSONTypes=Bb;function JI(t,e){let{gen:r,data:n,opts:o}=t,s=YI(e,o.coerceTypes),i=e.length>0&&!(s.length===0&&e.length===1&&(0,WI.schemaHasRulesForType)(t,e[0]));if(i){let a=vf(e,n,o.strictNumbers,Lo.Wrong);r.if(a,()=>{s.length?XI(t,e,s):bf(t)})}return i}nt.coerceAndCheckDataType=JI;var Vb=new Set(["string","number","integer","boolean","null"]);function YI(t,e){return e?t.filter(r=>Vb.has(r)||e==="array"&&r==="array"):[]}function XI(t,e,r){let{gen:n,data:o,opts:s}=t,i=n.let("dataType",(0,Y._)`typeof ${o}`),a=n.let("coerced",(0,Y._)`undefined`);s.coerceTypes==="array"&&n.if((0,Y._)`${i} == 'object' && Array.isArray(${o}) && ${o}.length == 1`,()=>n.assign(o,(0,Y._)`${o}[0]`).assign(i,(0,Y._)`typeof ${o}`).if(vf(e,o,s.strictNumbers),()=>n.assign(a,o))),n.if((0,Y._)`${a} !== undefined`);for(let u of r)(Vb.has(u)||u==="array"&&s.coerceTypes==="array")&&c(u);n.else(),bf(t),n.endIf(),n.if((0,Y._)`${a} !== undefined`,()=>{n.assign(o,a),QI(t,a)});function c(u){switch(u){case"string":n.elseIf((0,Y._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Y._)`"" + ${o}`).elseIf((0,Y._)`${o} === null`).assign(a,(0,Y._)`""`);return;case"number":n.elseIf((0,Y._)`${i} == "boolean" || ${o} === null
52
- || (${i} == "string" && ${o} && ${o} == +${o})`).assign(a,(0,Y._)`+${o}`);return;case"integer":n.elseIf((0,Y._)`${i} === "boolean" || ${o} === null
53
- || (${i} === "string" && ${o} && ${o} == +${o} && !(${o} % 1))`).assign(a,(0,Y._)`+${o}`);return;case"boolean":n.elseIf((0,Y._)`${o} === "false" || ${o} === 0 || ${o} === null`).assign(a,!1).elseIf((0,Y._)`${o} === "true" || ${o} === 1`).assign(a,!0);return;case"null":n.elseIf((0,Y._)`${o} === "" || ${o} === 0 || ${o} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Y._)`${i} === "string" || ${i} === "number"
54
- || ${i} === "boolean" || ${o} === null`).assign(a,(0,Y._)`[${o}]`)}}}function QI({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Y._)`${e} !== undefined`,()=>t.assign((0,Y._)`${e}[${r}]`,n))}function xf(t,e,r,n=Lo.Correct){let o=n===Lo.Correct?Y.operators.EQ:Y.operators.NEQ,s;switch(t){case"null":return(0,Y._)`${e} ${o} null`;case"array":s=(0,Y._)`Array.isArray(${e})`;break;case"object":s=(0,Y._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":s=i((0,Y._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":s=i();break;default:return(0,Y._)`typeof ${e} ${o} ${t}`}return n===Lo.Correct?s:(0,Y.not)(s);function i(a=Y.nil){return(0,Y.and)((0,Y._)`typeof ${e} == "number"`,a,r?(0,Y._)`isFinite(${e})`:Y.nil)}}nt.checkDataType=xf;function vf(t,e,r,n){if(t.length===1)return xf(t[0],e,r,n);let o,s=(0,qb.toHash)(t);if(s.array&&s.object){let i=(0,Y._)`typeof ${e} != "object"`;o=s.null?i:(0,Y._)`!${e} || ${i}`,delete s.null,delete s.array,delete s.object}else o=Y.nil;s.number&&delete s.integer;for(let i in s)o=(0,Y.and)(o,xf(i,e,r,n));return o}nt.checkDataTypes=vf;var e1={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Y._)`{type: ${t}}`:(0,Y._)`{type: ${e}}`};function bf(t){let e=t1(t);(0,GI.reportError)(e,e1)}nt.reportTypeError=bf;function t1(t){let{gen:e,data:r,schema:n}=t,o=(0,qb.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:o,schemaValue:o,parentSchema:n,params:{},it:t}}});var Gb=C(Ec=>{"use strict";Object.defineProperty(Ec,"__esModule",{value:!0});Ec.assignDefaults=void 0;var Fo=Q(),r1=ue();function n1(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let o in r)Wb(t,o,r[o].default);else e==="array"&&Array.isArray(n)&&n.forEach((o,s)=>Wb(t,s,o.default))}Ec.assignDefaults=n1;function Wb(t,e,r){let{gen:n,compositeRule:o,data:s,opts:i}=t;if(r===void 0)return;let a=(0,Fo._)`${s}${(0,Fo.getProperty)(e)}`;if(o){(0,r1.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Fo._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Fo._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Fo._)`${a} = ${(0,Fo.stringify)(r)}`)}});var Ft=C(_e=>{"use strict";Object.defineProperty(_e,"__esModule",{value:!0});_e.validateUnion=_e.validateArray=_e.usePattern=_e.callValidateCode=_e.schemaProperties=_e.allSchemaProperties=_e.noPropertyInData=_e.propertyInData=_e.isOwnProperty=_e.hasPropFunc=_e.reportMissingProp=_e.checkMissingProp=_e.checkReportMissingProp=void 0;var Ee=Q(),Sf=ue(),nn=Ir(),o1=ue();function s1(t,e){let{gen:r,data:n,it:o}=t;r.if(wf(r,n,e,o.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Ee._)`${e}`},!0),t.error()})}_e.checkReportMissingProp=s1;function i1({gen:t,data:e,it:{opts:r}},n,o){return(0,Ee.or)(...n.map(s=>(0,Ee.and)(wf(t,e,s,r.ownProperties),(0,Ee._)`${o} = ${s}`)))}_e.checkMissingProp=i1;function a1(t,e){t.setParams({missingProperty:e},!0),t.error()}_e.reportMissingProp=a1;function Kb(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Ee._)`Object.prototype.hasOwnProperty`})}_e.hasPropFunc=Kb;function kf(t,e,r){return(0,Ee._)`${Kb(t)}.call(${e}, ${r})`}_e.isOwnProperty=kf;function c1(t,e,r,n){let o=(0,Ee._)`${e}${(0,Ee.getProperty)(r)} !== undefined`;return n?(0,Ee._)`${o} && ${kf(t,e,r)}`:o}_e.propertyInData=c1;function wf(t,e,r,n){let o=(0,Ee._)`${e}${(0,Ee.getProperty)(r)} === undefined`;return n?(0,Ee.or)(o,(0,Ee.not)(kf(t,e,r))):o}_e.noPropertyInData=wf;function Jb(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}_e.allSchemaProperties=Jb;function u1(t,e){return Jb(e).filter(r=>!(0,Sf.alwaysValidSchema)(t,e[r]))}_e.schemaProperties=u1;function l1({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:o,errorPath:s},it:i},a,c,u){let l=u?(0,Ee._)`${t}, ${e}, ${n}${o}`:e,d=[[nn.default.instancePath,(0,Ee.strConcat)(nn.default.instancePath,s)],[nn.default.parentData,i.parentData],[nn.default.parentDataProperty,i.parentDataProperty],[nn.default.rootData,nn.default.rootData]];i.opts.dynamicRef&&d.push([nn.default.dynamicAnchors,nn.default.dynamicAnchors]);let p=(0,Ee._)`${l}, ${r.object(...d)}`;return c!==Ee.nil?(0,Ee._)`${a}.call(${c}, ${p})`:(0,Ee._)`${a}(${p})`}_e.callValidateCode=l1;var d1=(0,Ee._)`new RegExp`;function p1({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:o}=e.code,s=o(r,n);return t.scopeValue("pattern",{key:s.toString(),ref:s,code:(0,Ee._)`${o.code==="new RegExp"?d1:(0,o1.useFunc)(t,o)}(${r}, ${n})`})}_e.usePattern=p1;function m1(t){let{gen:e,data:r,keyword:n,it:o}=t,s=e.name("valid");if(o.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(s,!0),i(()=>e.break()),s;function i(a){let c=e.const("len",(0,Ee._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:Sf.Type.Num},s),e.if((0,Ee.not)(s),a)})}}_e.validateArray=m1;function f1(t){let{gen:e,schema:r,keyword:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(r.some(c=>(0,Sf.alwaysValidSchema)(o,c))&&!o.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let l=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Ee._)`${i} || ${a}`),t.mergeValidEvaluated(l,a)||e.if((0,Ee.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}_e.validateUnion=f1});var Qb=C(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.validateKeywordUsage=dr.validSchemaType=dr.funcKeywordCode=dr.macroKeywordCode=void 0;var lt=Q(),Wn=Ir(),h1=Ft(),g1=ai();function _1(t,e){let{gen:r,keyword:n,schema:o,parentSchema:s,it:i}=t,a=e.macro.call(i.self,o,s,i),c=Xb(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:lt.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}dr.macroKeywordCode=_1;function y1(t,e){var r;let{gen:n,keyword:o,schema:s,parentSchema:i,$data:a,it:c}=t;v1(c,e);let u=!a&&e.compile?e.compile.call(c.self,s,i,c):e.validate,l=Xb(n,o,u),d=n.let("valid");t.block$data(d,p),t.ok((r=e.valid)!==null&&r!==void 0?r:d);function p(){if(e.errors===!1)h(),e.modifying&&Yb(t),g(()=>t.error());else{let y=e.async?f():m();e.modifying&&Yb(t),g(()=>x1(t,y))}}function f(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,lt._)`await `),_=>n.assign(d,!1).if((0,lt._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,lt._)`${_}.errors`),()=>n.throw(_))),y}function m(){let y=(0,lt._)`${l}.errors`;return n.assign(y,null),h(lt.nil),y}function h(y=e.async?(0,lt._)`await `:lt.nil){let _=c.opts.passContext?Wn.default.this:Wn.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(d,(0,lt._)`${y}${(0,h1.callValidateCode)(t,l,_,x)}`,e.modifying)}function g(y){var _;n.if((0,lt.not)((_=e.valid)!==null&&_!==void 0?_:d),y)}}dr.funcKeywordCode=y1;function Yb(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,lt._)`${n.parentData}[${n.parentDataProperty}]`))}function x1(t,e){let{gen:r}=t;r.if((0,lt._)`Array.isArray(${e})`,()=>{r.assign(Wn.default.vErrors,(0,lt._)`${Wn.default.vErrors} === null ? ${e} : ${Wn.default.vErrors}.concat(${e})`).assign(Wn.default.errors,(0,lt._)`${Wn.default.vErrors}.length`),(0,g1.extendErrors)(t)},()=>t.error())}function v1({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function Xb(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,lt.stringify)(r)})}function b1(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")}dr.validSchemaType=b1;function S1({schema:t,opts:e,self:r,errSchemaPath:n},o,s){if(Array.isArray(o.keyword)?!o.keyword.includes(s):o.keyword!==s)throw new Error("ajv implementation error");let i=o.dependencies;if(i?.some(a=>!Object.prototype.hasOwnProperty.call(t,a)))throw new Error(`parent schema must have dependencies of ${s}: ${i.join(",")}`);if(o.validateSchema&&!o.validateSchema(t[s])){let c=`keyword "${s}" value is invalid at path "${n}": `+r.errorsText(o.validateSchema.errors);if(e.validateSchema==="log")r.logger.error(c);else throw new Error(c)}}dr.validateKeywordUsage=S1});var tS=C(on=>{"use strict";Object.defineProperty(on,"__esModule",{value:!0});on.extendSubschemaMode=on.extendSubschemaData=on.getSubschema=void 0;var pr=Q(),eS=ue();function k1(t,{keyword:e,schemaProp:r,schema:n,schemaPath:o,errSchemaPath:s,topSchemaRef:i}){if(e!==void 0&&n!==void 0)throw new Error('both "keyword" and "schema" passed, only one allowed');if(e!==void 0){let a=t.schema[e];return r===void 0?{schema:a,schemaPath:(0,pr._)`${t.schemaPath}${(0,pr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,pr._)`${t.schemaPath}${(0,pr.getProperty)(e)}${(0,pr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,eS.escapeFragment)(r)}`}}if(n!==void 0){if(o===void 0||s===void 0||i===void 0)throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');return{schema:n,schemaPath:o,topSchemaRef:i,errSchemaPath:s}}throw new Error('either "keyword" or "schema" must be passed')}on.getSubschema=k1;function w1(t,e,{dataProp:r,dataPropType:n,data:o,dataTypes:s,propertyName:i}){if(o!==void 0&&r!==void 0)throw new Error('both "data" and "dataProp" passed, only one allowed');let{gen:a}=e;if(r!==void 0){let{errorPath:u,dataPathArr:l,opts:d}=e,p=a.let("data",(0,pr._)`${e.data}${(0,pr.getProperty)(r)}`,!0);c(p),t.errorPath=(0,pr.str)`${u}${(0,eS.getErrorPath)(r,n,d.jsPropertySyntax)}`,t.parentDataProperty=(0,pr._)`${r}`,t.dataPathArr=[...l,t.parentDataProperty]}if(o!==void 0){let u=o instanceof pr.Name?o:a.let("data",o,!0);c(u),i!==void 0&&(t.propertyName=i)}s&&(t.dataTypes=s);function c(u){t.data=u,t.dataLevel=e.dataLevel+1,t.dataTypes=[],e.definedProperties=new Set,t.parentData=e.data,t.dataNames=[...e.dataNames,u]}}on.extendSubschemaData=w1;function $1(t,{jtdDiscriminator:e,jtdMetadata:r,compositeRule:n,createErrors:o,allErrors:s}){n!==void 0&&(t.compositeRule=n),o!==void 0&&(t.createErrors=o),s!==void 0&&(t.allErrors=s),t.jtdDiscriminator=e,t.jtdMetadata=r}on.extendSubschemaMode=$1});var $f=C((pB,rS)=>{"use strict";rS.exports=function t(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var n,o,s;if(Array.isArray(e)){if(n=e.length,n!=r.length)return!1;for(o=n;o--!==0;)if(!t(e[o],r[o]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(s=Object.keys(e),n=s.length,n!==Object.keys(r).length)return!1;for(o=n;o--!==0;)if(!Object.prototype.hasOwnProperty.call(r,s[o]))return!1;for(o=n;o--!==0;){var i=s[o];if(!t(e[i],r[i]))return!1}return!0}return e!==e&&r!==r}});var oS=C((mB,nS)=>{"use strict";var sn=nS.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},o=r.post||function(){};Tc(e,n,o,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 Tc(t,e,r,n,o,s,i,a,c,u){if(n&&typeof n=="object"&&!Array.isArray(n)){e(n,o,s,i,a,c,u);for(var l in n){var d=n[l];if(Array.isArray(d)){if(l in sn.arrayKeywords)for(var p=0;p<d.length;p++)Tc(t,e,r,d[p],o+"/"+l+"/"+p,s,o,l,n,p)}else if(l in sn.propsKeywords){if(d&&typeof d=="object")for(var f in d)Tc(t,e,r,d[f],o+"/"+l+"/"+E1(f),s,o,l,n,f)}else(l in sn.keywords||t.allKeys&&!(l in sn.skipKeywords))&&Tc(t,e,r,d,o+"/"+l,s,o,l,n)}r(n,o,s,i,a,c,u)}}function E1(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var ui=C(yt=>{"use strict";Object.defineProperty(yt,"__esModule",{value:!0});yt.getSchemaRefs=yt.resolveUrl=yt.normalizeId=yt._getFullPath=yt.getFullPath=yt.inlineRef=void 0;var T1=ue(),P1=$f(),R1=oS(),C1=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function O1(t,e=!0){return typeof t=="boolean"?!0:e===!0?!Ef(t):e?sS(t)<=e:!1}yt.inlineRef=O1;var I1=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function Ef(t){for(let e in t){if(I1.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(Ef)||typeof r=="object"&&Ef(r))return!0}return!1}function sS(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!C1.has(r)&&(typeof t[r]=="object"&&(0,T1.eachItem)(t[r],n=>e+=sS(n)),e===1/0))return 1/0}return e}function iS(t,e="",r){r!==!1&&(e=Uo(e));let n=t.parse(e);return aS(t,n)}yt.getFullPath=iS;function aS(t,e){return t.serialize(e).split("#")[0]+"#"}yt._getFullPath=aS;var A1=/#\/?$/;function Uo(t){return t?t.replace(A1,""):""}yt.normalizeId=Uo;function N1(t,e,r){return r=Uo(r),t.resolve(e,r)}yt.resolveUrl=N1;var z1=/^[a-z_][-a-z0-9._]*$/i;function j1(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,o=Uo(t[r]||e),s={"":o},i=iS(n,o,!1),a={},c=new Set;return R1(t,{allKeys:!0},(d,p,f,m)=>{if(m===void 0)return;let h=i+p,g=s[m];typeof d[r]=="string"&&(g=y.call(this,d[r])),_.call(this,d.$anchor),_.call(this,d.$dynamicAnchor),s[p]=g;function y(x){let k=this.opts.uriResolver.resolve;if(x=Uo(g?k(g,x):x),c.has(x))throw l(x);c.add(x);let E=this.refs[x];return typeof E=="string"&&(E=this.refs[E]),typeof E=="object"?u(d,E.schema,x):x!==Uo(h)&&(x[0]==="#"?(u(d,a[x],x),a[x]=d):this.refs[x]=h),x}function _(x){if(typeof x=="string"){if(!z1.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(d,p,f){if(p!==void 0&&!P1(d,p))throw l(f)}function l(d){return new Error(`reference "${d}" resolves to more than one schema`)}}yt.getSchemaRefs=j1});var pi=C(an=>{"use strict";Object.defineProperty(an,"__esModule",{value:!0});an.getData=an.KeywordCxt=an.validateFunctionCode=void 0;var pS=Ub(),cS=ci(),Pf=yf(),Pc=ci(),D1=Gb(),di=Qb(),Tf=tS(),F=Q(),G=Ir(),M1=ui(),Ar=ue(),li=ai();function L1(t){if(hS(t)&&(gS(t),fS(t))){Z1(t);return}mS(t,()=>(0,pS.topBoolOrEmptySchema)(t))}an.validateFunctionCode=L1;function mS({gen:t,validateName:e,schema:r,schemaEnv:n,opts:o},s){o.code.es5?t.func(e,(0,F._)`${G.default.data}, ${G.default.valCxt}`,n.$async,()=>{t.code((0,F._)`"use strict"; ${uS(r,o)}`),U1(t,o),t.code(s)}):t.func(e,(0,F._)`${G.default.data}, ${F1(o)}`,n.$async,()=>t.code(uS(r,o)).code(s))}function F1(t){return(0,F._)`{${G.default.instancePath}="", ${G.default.parentData}, ${G.default.parentDataProperty}, ${G.default.rootData}=${G.default.data}${t.dynamicRef?(0,F._)`, ${G.default.dynamicAnchors}={}`:F.nil}}={}`}function U1(t,e){t.if(G.default.valCxt,()=>{t.var(G.default.instancePath,(0,F._)`${G.default.valCxt}.${G.default.instancePath}`),t.var(G.default.parentData,(0,F._)`${G.default.valCxt}.${G.default.parentData}`),t.var(G.default.parentDataProperty,(0,F._)`${G.default.valCxt}.${G.default.parentDataProperty}`),t.var(G.default.rootData,(0,F._)`${G.default.valCxt}.${G.default.rootData}`),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`${G.default.valCxt}.${G.default.dynamicAnchors}`)},()=>{t.var(G.default.instancePath,(0,F._)`""`),t.var(G.default.parentData,(0,F._)`undefined`),t.var(G.default.parentDataProperty,(0,F._)`undefined`),t.var(G.default.rootData,G.default.data),e.dynamicRef&&t.var(G.default.dynamicAnchors,(0,F._)`{}`)})}function Z1(t){let{schema:e,opts:r,gen:n}=t;mS(t,()=>{r.$comment&&e.$comment&&yS(t),W1(t),n.let(G.default.vErrors,null),n.let(G.default.errors,0),r.unevaluated&&H1(t),_S(t),J1(t)})}function H1(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,F._)`${r}.evaluated`),e.if((0,F._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,F._)`${t.evaluated}.props`,(0,F._)`undefined`)),e.if((0,F._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,F._)`${t.evaluated}.items`,(0,F._)`undefined`))}function uS(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,F._)`/*# sourceURL=${r} */`:F.nil}function q1(t,e){if(hS(t)&&(gS(t),fS(t))){B1(t,e);return}(0,pS.boolOrEmptySchema)(t,e)}function fS({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 hS(t){return typeof t.schema!="boolean"}function B1(t,e){let{schema:r,gen:n,opts:o}=t;o.$comment&&r.$comment&&yS(t),G1(t),K1(t);let s=n.const("_errs",G.default.errors);_S(t,s),n.var(e,(0,F._)`${s} === ${G.default.errors}`)}function gS(t){(0,Ar.checkUnknownRules)(t),V1(t)}function _S(t,e){if(t.opts.jtd)return lS(t,[],!1,e);let r=(0,cS.getSchemaTypes)(t.schema),n=(0,cS.coerceAndCheckDataType)(t,r);lS(t,r,!n,e)}function V1(t){let{schema:e,errSchemaPath:r,opts:n,self:o}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,Ar.schemaHasRulesButRef)(e,o.RULES)&&o.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function W1(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,Ar.checkStrictMode)(t,"default is ignored in the schema root")}function G1(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,M1.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function K1(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function yS({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:o}){let s=r.$comment;if(o.$comment===!0)t.code((0,F._)`${G.default.self}.logger.log(${s})`);else if(typeof o.$comment=="function"){let i=(0,F.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,F._)`${G.default.self}.opts.$comment(${s}, ${i}, ${a}.schema)`)}}function J1(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:o,opts:s}=t;r.$async?e.if((0,F._)`${G.default.errors} === 0`,()=>e.return(G.default.data),()=>e.throw((0,F._)`new ${o}(${G.default.vErrors})`)):(e.assign((0,F._)`${n}.errors`,G.default.vErrors),s.unevaluated&&Y1(t),e.return((0,F._)`${G.default.errors} === 0`))}function Y1({gen:t,evaluated:e,props:r,items:n}){r instanceof F.Name&&t.assign((0,F._)`${e}.props`,r),n instanceof F.Name&&t.assign((0,F._)`${e}.items`,n)}function lS(t,e,r,n){let{gen:o,schema:s,data:i,allErrors:a,opts:c,self:u}=t,{RULES:l}=u;if(s.$ref&&(c.ignoreKeywordsWithRef||!(0,Ar.schemaHasRulesButRef)(s,l))){o.block(()=>vS(t,"$ref",l.all.$ref.definition));return}c.jtd||X1(t,e),o.block(()=>{for(let p of l.rules)d(p);d(l.post)});function d(p){(0,Pf.shouldUseGroup)(s,p)&&(p.type?(o.if((0,Pc.checkDataType)(p.type,i,c.strictNumbers)),dS(t,p),e.length===1&&e[0]===p.type&&r&&(o.else(),(0,Pc.reportTypeError)(t)),o.endIf()):dS(t,p),a||o.if((0,F._)`${G.default.errors} === ${n||0}`))}}function dS(t,e){let{gen:r,schema:n,opts:{useDefaults:o}}=t;o&&(0,D1.assignDefaults)(t,e.type),r.block(()=>{for(let s of e.rules)(0,Pf.shouldUseRule)(n,s)&&vS(t,s.keyword,s.definition,e.type)})}function X1(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(Q1(t,e),t.opts.allowUnionTypes||eA(t,e),tA(t,t.dataTypes))}function Q1(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{xS(t.dataTypes,r)||Rf(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),nA(t,e)}}function eA(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&Rf(t,"use allowUnionTypes to allow union type keyword")}function tA(t,e){let r=t.self.RULES.all;for(let n in r){let o=r[n];if(typeof o=="object"&&(0,Pf.shouldUseRule)(t.schema,o)){let{type:s}=o.definition;s.length&&!s.some(i=>rA(e,i))&&Rf(t,`missing type "${s.join(",")}" for keyword "${n}"`)}}}function rA(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function xS(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function nA(t,e){let r=[];for(let n of t.dataTypes)xS(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function Rf(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,Ar.checkStrictMode)(t,e,t.opts.strictTypes)}var Rc=class{constructor(e,r,n){if((0,di.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,Ar.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",bS(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,di.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",G.default.errors))}result(e,r,n){this.failResult((0,F.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,F.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,F._)`${r} !== undefined && (${(0,F.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?li.reportExtraError:li.reportError)(this,this.def.error,r)}$dataError(){(0,li.reportError)(this,this.def.$dataError||li.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,li.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=F.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=F.nil,r=F.nil){if(!this.$data)return;let{gen:n,schemaCode:o,schemaType:s,def:i}=this;n.if((0,F.or)((0,F._)`${o} === undefined`,r)),e!==F.nil&&n.assign(e,!0),(s.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==F.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:o,it:s}=this;return(0,F.or)(i(),a());function i(){if(n.length){if(!(r instanceof F.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,F._)`${(0,Pc.checkDataTypes)(c,r,s.opts.strictNumbers,Pc.DataType.Wrong)}`}return F.nil}function a(){if(o.validateSchema){let c=e.scopeValue("validate$data",{ref:o.validateSchema});return(0,F._)`!${c}(${r})`}return F.nil}}subschema(e,r){let n=(0,Tf.getSubschema)(this.it,e);(0,Tf.extendSubschemaData)(n,this.it,e),(0,Tf.extendSubschemaMode)(n,e);let o={...this.it,...n,items:void 0,props:void 0};return q1(o,r),o}mergeEvaluated(e,r){let{it:n,gen:o}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=Ar.mergeEvaluated.props(o,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=Ar.mergeEvaluated.items(o,e.items,n.items,r)))}mergeValidEvaluated(e,r){let{it:n,gen:o}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return o.if(r,()=>this.mergeEvaluated(e,F.Name)),!0}};an.KeywordCxt=Rc;function vS(t,e,r,n){let o=new Rc(t,r,e);"code"in r?r.code(o,n):o.$data&&r.validate?(0,di.funcKeywordCode)(o,r):"macro"in r?(0,di.macroKeywordCode)(o,r):(r.compile||r.validate)&&(0,di.funcKeywordCode)(o,r)}var oA=/^\/(?:[^~]|~0|~1)*$/,sA=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function bS(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let o,s;if(t==="")return G.default.rootData;if(t[0]==="/"){if(!oA.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);o=t,s=G.default.rootData}else{let u=sA.exec(t);if(!u)throw new Error(`Invalid JSON-pointer: ${t}`);let l=+u[1];if(o=u[2],o==="#"){if(l>=e)throw new Error(c("property/index",l));return n[e-l]}if(l>e)throw new Error(c("data",l));if(s=r[e-l],!o)return s}let i=s,a=o.split("/");for(let u of a)u&&(s=(0,F._)`${s}${(0,F.getProperty)((0,Ar.unescapeJsonPointer)(u))}`,i=(0,F._)`${i} && ${s}`);return i;function c(u,l){return`Cannot access ${u} ${l} levels up, current level is ${e}`}}an.getData=bS});var Cc=C(Of=>{"use strict";Object.defineProperty(Of,"__esModule",{value:!0});var Cf=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};Of.default=Cf});var mi=C(Nf=>{"use strict";Object.defineProperty(Nf,"__esModule",{value:!0});var If=ui(),Af=class extends Error{constructor(e,r,n,o){super(o||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,If.resolveUrl)(e,r,n),this.missingSchema=(0,If.normalizeId)((0,If.getFullPath)(e,this.missingRef))}};Nf.default=Af});var Ic=C(Ut=>{"use strict";Object.defineProperty(Ut,"__esModule",{value:!0});Ut.resolveSchema=Ut.getCompilingSchema=Ut.resolveRef=Ut.compileSchema=Ut.SchemaEnv=void 0;var Qt=Q(),iA=Cc(),Gn=Ir(),er=ui(),SS=ue(),aA=pi(),Zo=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,er.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Ut.SchemaEnv=Zo;function jf(t){let e=kS.call(this,t);if(e)return e;let r=(0,er.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:o}=this.opts.code,{ownProperties:s}=this.opts,i=new Qt.CodeGen(this.scope,{es5:n,lines:o,ownProperties:s}),a;t.$async&&(a=i.scopeValue("Error",{ref:iA.default,code:(0,Qt._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:Gn.default.data,parentData:Gn.default.parentData,parentDataProperty:Gn.default.parentDataProperty,dataNames:[Gn.default.data],dataPathArr:[Qt.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,Qt.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:Qt.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,Qt._)`""`,opts:this.opts,self:this},l;try{this._compilations.add(t),(0,aA.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let d=i.toString();l=`${i.scopeRefs(Gn.default.scope)}return ${d}`,this.opts.code.process&&(l=this.opts.code.process(l,t));let f=new Function(`${Gn.default.self}`,`${Gn.default.scope}`,l)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:d,scopeValues:i._values}),this.opts.unevaluated){let{props:m,items:h}=u;f.evaluated={props:m instanceof Qt.Name?void 0:m,items:h instanceof Qt.Name?void 0:h,dynamicProps:m instanceof Qt.Name,dynamicItems:h instanceof Qt.Name},f.source&&(f.source.evaluated=(0,Qt.stringify)(f.evaluated))}return t.validate=f,t}catch(d){throw delete t.validate,delete t.validateName,l&&this.logger.error("Error compiling schema, function code:",l),d}finally{this._compilations.delete(t)}}Ut.compileSchema=jf;function cA(t,e,r){var n;r=(0,er.resolveUrl)(this.opts.uriResolver,e,r);let o=t.refs[r];if(o)return o;let s=dA.call(this,t,r);if(s===void 0){let i=(n=t.localRefs)===null||n===void 0?void 0:n[r],{schemaId:a}=this.opts;i&&(s=new Zo({schema:i,schemaId:a,root:t,baseId:e}))}if(s!==void 0)return t.refs[r]=uA.call(this,s)}Ut.resolveRef=cA;function uA(t){return(0,er.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:jf.call(this,t)}function kS(t){for(let e of this._compilations)if(lA(e,t))return e}Ut.getCompilingSchema=kS;function lA(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function dA(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Oc.call(this,t,e)}function Oc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,er._getFullPath)(this.opts.uriResolver,r),o=(0,er.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===o)return zf.call(this,r,t);let s=(0,er.normalizeId)(n),i=this.refs[s]||this.schemas[s];if(typeof i=="string"){let a=Oc.call(this,t,i);return typeof a?.schema!="object"?void 0:zf.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||jf.call(this,i),s===(0,er.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(o=(0,er.resolveUrl)(this.opts.uriResolver,o,u)),new Zo({schema:a,schemaId:c,root:t,baseId:o})}return zf.call(this,r,i)}}Ut.resolveSchema=Oc;var pA=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function zf(t,{baseId:e,schema:r,root:n}){var o;if(((o=t.fragment)===null||o===void 0?void 0:o[0])!=="/")return;for(let a of t.fragment.slice(1).split("/")){if(typeof r=="boolean")return;let c=r[(0,SS.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!pA.has(a)&&u&&(e=(0,er.resolveUrl)(this.opts.uriResolver,e,u))}let s;if(typeof r!="boolean"&&r.$ref&&!(0,SS.schemaHasRulesButRef)(r,this.RULES)){let a=(0,er.resolveUrl)(this.opts.uriResolver,e,r.$ref);s=Oc.call(this,n,a)}let{schemaId:i}=this.opts;if(s=s||new Zo({schema:r,schemaId:i,root:n,baseId:e}),s.schema!==s.root.schema)return s}});var wS=C((xB,mA)=>{mA.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 Mf=C((vB,PS)=>{"use strict";var fA=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),ES=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 Df(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 hA=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function $S(t){return t.length=0,!0}function gA(t,e,r){if(t.length){let n=Df(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function _A(t){let e=0,r={error:!1,address:"",zone:""},n=[],o=[],s=!1,i=!1,a=gA;for(let c=0;c<t.length;c++){let u=t[c];if(!(u==="["||u==="]"))if(u===":"){if(s===!0&&(i=!0),!a(o,n,r))break;if(++e>7){r.error=!0;break}c>0&&t[c-1]===":"&&(s=!0),n.push(":");continue}else if(u==="%"){if(!a(o,n,r))break;a=$S}else{o.push(u);continue}}return o.length&&(a===$S?r.zone=o.join(""):i?n.push(o.join("")):n.push(Df(o))),r.address=n.join(""),r}function TS(t){if(yA(t,":")<2)return{host:t,isIPV6:!1};let e=_A(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 yA(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function xA(t){let e=t,r=[],n=-1,o=0;for(;o=e.length;){if(o===1){if(e===".")break;if(e==="/"){r.push("/");break}else{r.push(e);break}}else if(o===2){if(e[0]==="."){if(e[1]===".")break;if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&(e[1]==="."||e[1]==="/")){r.push("/");break}}else if(o===3&&e==="/.."){r.length!==0&&r.pop(),r.push("/");break}if(e[0]==="."){if(e[1]==="."){if(e[2]==="/"){e=e.slice(3);continue}}else if(e[1]==="/"){e=e.slice(2);continue}}else if(e[0]==="/"&&e[1]==="."){if(e[2]==="/"){e=e.slice(2);continue}else if(e[2]==="."&&e[3]==="/"){e=e.slice(3),r.length!==0&&r.pop();continue}}if((n=e.indexOf("/",1))===-1){r.push(e);break}else r.push(e.slice(0,n)),e=e.slice(n)}return r.join("")}function vA(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 bA(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!ES(r)){let n=TS(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}PS.exports={nonSimpleDomain:hA,recomposeAuthority:bA,normalizeComponentEncoding:vA,removeDotSegments:xA,isIPv4:ES,isUUID:fA,normalizeIPv6:TS,stringArrayToHexStripped:Df}});var AS=C((bB,IS)=>{"use strict";var{isUUID:SA}=Mf(),kA=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,wA=["http","https","ws","wss","urn","urn:uuid"];function $A(t){return wA.indexOf(t)!==-1}function Lf(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 RS(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function CS(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 EA(t){return t.secure=Lf(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function TA(t){if((t.port===(Lf(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 PA(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(kA);if(r){let n=e.scheme||t.scheme||"urn";t.nid=r[1].toLowerCase(),t.nss=r[2];let o=`${n}:${e.nid||t.nid}`,s=Ff(o);t.path=void 0,s&&(t=s.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function RA(t,e){if(t.nid===void 0)throw new Error("URN without nid cannot be serialized");let r=e.scheme||t.scheme||"urn",n=t.nid.toLowerCase(),o=`${r}:${e.nid||n}`,s=Ff(o);s&&(t=s.serialize(t,e));let i=t,a=t.nss;return i.path=`${n||e.nid}:${a}`,e.skipEscape=!0,i}function CA(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!SA(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function OA(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var OS={scheme:"http",domainHost:!0,parse:RS,serialize:CS},IA={scheme:"https",domainHost:OS.domainHost,parse:RS,serialize:CS},Ac={scheme:"ws",domainHost:!0,parse:EA,serialize:TA},AA={scheme:"wss",domainHost:Ac.domainHost,parse:Ac.parse,serialize:Ac.serialize},NA={scheme:"urn",parse:PA,serialize:RA,skipNormalize:!0},zA={scheme:"urn:uuid",parse:CA,serialize:OA,skipNormalize:!0},Nc={http:OS,https:IA,ws:Ac,wss:AA,urn:NA,"urn:uuid":zA};Object.setPrototypeOf(Nc,null);function Ff(t){return t&&(Nc[t]||Nc[t.toLowerCase()])||void 0}IS.exports={wsIsSecure:Lf,SCHEMES:Nc,isValidSchemeName:$A,getSchemeHandler:Ff}});var jS=C((SB,jc)=>{"use strict";var{normalizeIPv6:jA,removeDotSegments:fi,recomposeAuthority:DA,normalizeComponentEncoding:zc,isIPv4:MA,nonSimpleDomain:LA}=Mf(),{SCHEMES:FA,getSchemeHandler:NS}=AS();function UA(t,e){return typeof t=="string"?t=mr(Nr(t,e),e):typeof t=="object"&&(t=Nr(mr(t,e),e)),t}function ZA(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},o=zS(Nr(t,n),Nr(e,n),n,!0);return n.skipEscape=!0,mr(o,n)}function zS(t,e,r,n){let o={};return n||(t=Nr(mr(t,r),r),e=Nr(mr(e,r),r)),r=r||{},!r.tolerant&&e.scheme?(o.scheme=e.scheme,o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=fi(e.path||""),o.query=e.query):(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0?(o.userinfo=e.userinfo,o.host=e.host,o.port=e.port,o.path=fi(e.path||""),o.query=e.query):(e.path?(e.path[0]==="/"?o.path=fi(e.path):((t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)&&!t.path?o.path="/"+e.path:t.path?o.path=t.path.slice(0,t.path.lastIndexOf("/")+1)+e.path:o.path=e.path,o.path=fi(o.path)),o.query=e.query):(o.path=t.path,e.query!==void 0?o.query=e.query:o.query=t.query),o.userinfo=t.userinfo,o.host=t.host,o.port=t.port),o.scheme=t.scheme),o.fragment=e.fragment,o}function HA(t,e,r){return typeof t=="string"?(t=unescape(t),t=mr(zc(Nr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=mr(zc(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=mr(zc(Nr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=mr(zc(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function mr(t,e){let r={host:t.host,scheme:t.scheme,userinfo:t.userinfo,port:t.port,path:t.path,query:t.query,nid:t.nid,nss:t.nss,uuid:t.uuid,fragment:t.fragment,reference:t.reference,resourceName:t.resourceName,secure:t.secure,error:""},n=Object.assign({},e),o=[],s=NS(n.scheme||r.scheme);s&&s.serialize&&s.serialize(r,n),r.path!==void 0&&(n.skipEscape?r.path=unescape(r.path):(r.path=escape(r.path),r.scheme!==void 0&&(r.path=r.path.split("%3A").join(":")))),n.reference!=="suffix"&&r.scheme&&o.push(r.scheme,":");let i=DA(r);if(i!==void 0&&(n.reference!=="suffix"&&o.push("//"),o.push(i),r.path&&r.path[0]!=="/"&&o.push("/")),r.path!==void 0){let a=r.path;!n.absolutePath&&(!s||!s.absolutePath)&&(a=fi(a)),i===void 0&&a[0]==="/"&&a[1]==="/"&&(a="/%2F"+a.slice(2)),o.push(a)}return r.query!==void 0&&o.push("?",r.query),r.fragment!==void 0&&o.push("#",r.fragment),o.join("")}var qA=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function Nr(t,e){let r=Object.assign({},e),n={scheme:void 0,userinfo:void 0,host:"",port:void 0,path:"",query:void 0,fragment:void 0},o=!1;r.reference==="suffix"&&(r.scheme?t=r.scheme+":"+t:t="//"+t);let s=t.match(qA);if(s){if(n.scheme=s[1],n.userinfo=s[3],n.host=s[4],n.port=parseInt(s[5],10),n.path=s[6]||"",n.query=s[7],n.fragment=s[8],isNaN(n.port)&&(n.port=s[5]),n.host)if(MA(n.host)===!1){let c=jA(n.host);n.host=c.host.toLowerCase(),o=c.isIPV6}else o=!0;n.scheme===void 0&&n.userinfo===void 0&&n.host===void 0&&n.port===void 0&&n.query===void 0&&!n.path?n.reference="same-document":n.scheme===void 0?n.reference="relative":n.fragment===void 0?n.reference="absolute":n.reference="uri",r.reference&&r.reference!=="suffix"&&r.reference!==n.reference&&(n.error=n.error||"URI is not a "+r.reference+" reference.");let i=NS(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&o===!1&&LA(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 Uf={SCHEMES:FA,normalize:UA,resolve:ZA,resolveComponent:zS,equal:HA,serialize:mr,parse:Nr};jc.exports=Uf;jc.exports.default=Uf;jc.exports.fastUri=Uf});var MS=C(Zf=>{"use strict";Object.defineProperty(Zf,"__esModule",{value:!0});var DS=jS();DS.code='require("ajv/dist/runtime/uri").default';Zf.default=DS});var VS=C(Ye=>{"use strict";Object.defineProperty(Ye,"__esModule",{value:!0});Ye.CodeGen=Ye.Name=Ye.nil=Ye.stringify=Ye.str=Ye._=Ye.KeywordCxt=void 0;var BA=pi();Object.defineProperty(Ye,"KeywordCxt",{enumerable:!0,get:function(){return BA.KeywordCxt}});var Ho=Q();Object.defineProperty(Ye,"_",{enumerable:!0,get:function(){return Ho._}});Object.defineProperty(Ye,"str",{enumerable:!0,get:function(){return Ho.str}});Object.defineProperty(Ye,"stringify",{enumerable:!0,get:function(){return Ho.stringify}});Object.defineProperty(Ye,"nil",{enumerable:!0,get:function(){return Ho.nil}});Object.defineProperty(Ye,"Name",{enumerable:!0,get:function(){return Ho.Name}});Object.defineProperty(Ye,"CodeGen",{enumerable:!0,get:function(){return Ho.CodeGen}});var VA=Cc(),HS=mi(),WA=_f(),hi=Ic(),GA=Q(),gi=ui(),Dc=ci(),qf=ue(),LS=wS(),KA=MS(),qS=(t,e)=>new RegExp(t,e);qS.code="new RegExp";var JA=["removeAdditional","useDefaults","coerceTypes"],YA=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),XA={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."},QA={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},FS=200;function eN(t){var e,r,n,o,s,i,a,c,u,l,d,p,f,m,h,g,y,_,x,k,E,H,z,K,Le;let P=t.strict,N=(e=t.code)===null||e===void 0?void 0:e.optimize,ce=N===!0||N===void 0?1:N||0,De=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:qS,Pe=(o=t.uriResolver)!==null&&o!==void 0?o:KA.default;return{strictSchema:(i=(s=t.strictSchema)!==null&&s!==void 0?s: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:(l=(u=t.strictTypes)!==null&&u!==void 0?u:P)!==null&&l!==void 0?l:"log",strictTuples:(p=(d=t.strictTuples)!==null&&d!==void 0?d:P)!==null&&p!==void 0?p:"log",strictRequired:(m=(f=t.strictRequired)!==null&&f!==void 0?f:P)!==null&&m!==void 0?m:!1,code:t.code?{...t.code,optimize:ce,regExp:De}:{optimize:ce,regExp:De},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:FS,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:FS,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(k=t.schemaId)!==null&&k!==void 0?k:"$id",addUsedSchema:(E=t.addUsedSchema)!==null&&E!==void 0?E:!0,validateSchema:(H=t.validateSchema)!==null&&H!==void 0?H:!0,validateFormats:(z=t.validateFormats)!==null&&z!==void 0?z:!0,unicodeRegExp:(K=t.unicodeRegExp)!==null&&K!==void 0?K:!0,int32range:(Le=t.int32range)!==null&&Le!==void 0?Le:!0,uriResolver:Pe}}var _i=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...eN(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new GA.ValueScope({scope:{},prefixes:YA,es5:r,lines:n}),this.logger=iN(e.logger);let o=e.validateFormats;e.validateFormats=!1,this.RULES=(0,WA.getRules)(),US.call(this,XA,e,"NOT SUPPORTED"),US.call(this,QA,e,"DEPRECATED","warn"),this._metaOpts=oN.call(this),e.formats&&rN.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&nN.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),tN.call(this),e.validateFormats=o}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,o=LS;n==="id"&&(o={...LS},o.id=o.$id,delete o.$id),r&&e&&this.addMetaSchema(o,o[n],!1)}defaultMeta(){let{meta:e,schemaId:r}=this.opts;return this.opts.defaultMeta=typeof e=="object"?e[r]||e:void 0}validate(e,r){let n;if(typeof e=="string"){if(n=this.getSchema(e),!n)throw new Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let o=n(r);return"$async"in n||(this.errors=n.errors),o}compile(e,r){let n=this._addSchema(e,r);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,r){if(typeof this.opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");let{loadSchema:n}=this.opts;return o.call(this,e,r);async function o(l,d){await s.call(this,l.$schema);let p=this._addSchema(l,d);return p.validate||i.call(this,p)}async function s(l){l&&!this.getSchema(l)&&await o.call(this,{$ref:l},!0)}async function i(l){try{return this._compileSchemaEnv(l)}catch(d){if(!(d instanceof HS.default))throw d;return a.call(this,d),await c.call(this,d.missingSchema),i.call(this,l)}}function a({missingSchema:l,missingRef:d}){if(this.refs[l])throw new Error(`AnySchema ${l} is loaded but ${d} cannot be resolved`)}async function c(l){let d=await u.call(this,l);this.refs[l]||await s.call(this,d.$schema),this.refs[l]||this.addSchema(d,l,r)}async function u(l){let d=this._loading[l];if(d)return d;try{return await(this._loading[l]=n(l))}finally{delete this._loading[l]}}}addSchema(e,r,n,o=this.opts.validateSchema){if(Array.isArray(e)){for(let i of e)this.addSchema(i,void 0,n,o);return this}let s;if(typeof e=="object"){let{schemaId:i}=this.opts;if(s=e[i],s!==void 0&&typeof s!="string")throw new Error(`schema ${i} must be string`)}return r=(0,gi.normalizeId)(r||s),this._checkUnique(r),this.schemas[r]=this._addSchema(e,n,r,o,!0),this}addMetaSchema(e,r,n=this.opts.validateSchema){return this.addSchema(e,r,!0,n),this}validateSchema(e,r){if(typeof e=="boolean")return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!="string")throw new Error("$schema must be a string");if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn("meta-schema not available"),this.errors=null,!0;let o=this.validate(n,e);if(!o&&r){let s="schema is invalid: "+this.errorsText();if(this.opts.validateSchema==="log")this.logger.error(s);else throw new Error(s)}return o}getSchema(e){let r;for(;typeof(r=ZS.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,o=new hi.SchemaEnv({schema:{},schemaId:n});if(r=hi.resolveSchema.call(this,o,e),!r)return;this.refs[e]=r}return r.validate||this._compileSchemaEnv(r)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case"undefined":return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case"string":{let r=ZS.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,gi.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(cN.call(this,n,r),!r)return(0,qf.eachItem)(n,s=>Hf.call(this,s)),this;lN.call(this,r);let o={...r,type:(0,Dc.getJSONTypes)(r.type),schemaType:(0,Dc.getJSONTypes)(r.schemaType)};return(0,qf.eachItem)(n,o.type.length===0?s=>Hf.call(this,s,o):s=>o.type.forEach(i=>Hf.call(this,s,o,i))),this}getKeyword(e){let r=this.RULES.all[e];return typeof r=="object"?r.definition:!!r}removeKeyword(e){let{RULES:r}=this;delete r.keywords[e],delete r.all[e];for(let n of r.rules){let o=n.rules.findIndex(s=>s.keyword===e);o>=0&&n.rules.splice(o,1)}return this}addFormat(e,r){return typeof r=="string"&&(r=new RegExp(r)),this.formats[e]=r,this}errorsText(e=this.errors,{separator:r=", ",dataVar:n="data"}={}){return!e||e.length===0?"No errors":e.map(o=>`${n}${o.instancePath} ${o.message}`).reduce((o,s)=>o+r+s)}$dataMetaSchema(e,r){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let o of r){let s=o.split("/").slice(1),i=e;for(let a of s)i=i[a];for(let a in n){let c=n[a];if(typeof c!="object")continue;let{$data:u}=c.definition,l=i[a];u&&l&&(i[a]=BS(l))}}return e}_removeAllSchemas(e,r){for(let n in e){let o=e[n];(!r||r.test(n))&&(typeof o=="string"?delete e[n]:o&&!o.meta&&(this._cache.delete(o.schema),delete e[n]))}}_addSchema(e,r,n,o=this.opts.validateSchema,s=this.opts.addUsedSchema){let i,{schemaId:a}=this.opts;if(typeof e=="object")i=e[a];else{if(this.opts.jtd)throw new Error("schema must be object");if(typeof e!="boolean")throw new Error("schema must be object or boolean")}let c=this._cache.get(e);if(c!==void 0)return c;n=(0,gi.normalizeId)(i||n);let u=gi.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),s&&!n.startsWith("#")&&(n&&this._checkUnique(n),this.refs[n]=c),o&&this.validateSchema(e,!0),c}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw new Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):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}}};_i.ValidationError=VA.default;_i.MissingRefError=HS.default;Ye.default=_i;function US(t,e,r,n="error"){for(let o in t){let s=o;s in e&&this.logger[n](`${r}: option ${o}. ${t[s]}`)}}function ZS(t){return t=(0,gi.normalizeId)(t),this.schemas[t]||this.refs[t]}function tN(){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 rN(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function nN(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 oN(){let t={...this.opts};for(let e of JA)delete t[e];return t}var sN={log(){},warn(){},error(){}};function iN(t){if(t===!1)return sN;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 aN=/^[a-z_$][a-z0-9_$:-]*$/i;function cN(t,e){let{RULES:r}=this;if((0,qf.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!aN.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 Hf(t,e,r){var n;let o=e?.post;if(r&&o)throw new Error('keyword with "post" flag cannot have "type"');let{RULES:s}=this,i=o?s.post:s.rules.find(({type:c})=>c===r);if(i||(i={type:r,rules:[]},s.rules.push(i)),s.keywords[t]=!0,!e)return;let a={keyword:t,definition:{...e,type:(0,Dc.getJSONTypes)(e.type),schemaType:(0,Dc.getJSONTypes)(e.schemaType)}};e.before?uN.call(this,i,a,e.before):i.rules.push(a),s.all[t]=a,(n=e.implements)===null||n===void 0||n.forEach(c=>this.addKeyword(c))}function uN(t,e,r){let n=t.rules.findIndex(o=>o.keyword===r);n>=0?t.rules.splice(n,0,e):(t.rules.push(e),this.logger.warn(`rule ${r} is not defined`))}function lN(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=BS(e)),t.validateSchema=this.compile(e,!0))}var dN={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function BS(t){return{anyOf:[t,dN]}}});var WS=C(Bf=>{"use strict";Object.defineProperty(Bf,"__esModule",{value:!0});var pN={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Bf.default=pN});var YS=C(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.callRef=Kn.getValidate=void 0;var mN=mi(),GS=Ft(),xt=Q(),qo=Ir(),KS=Ic(),Mc=ue(),fN={keyword:"$ref",schemaType:"string",code(t){let{gen:e,schema:r,it:n}=t,{baseId:o,schemaEnv:s,validateName:i,opts:a,self:c}=n,{root:u}=s;if((r==="#"||r==="#/")&&o===u.baseId)return d();let l=KS.resolveRef.call(c,u,o,r);if(l===void 0)throw new mN.default(n.opts.uriResolver,o,r);if(l instanceof KS.SchemaEnv)return p(l);return f(l);function d(){if(s===u)return Lc(t,i,s,s.$async);let m=e.scopeValue("root",{ref:u});return Lc(t,(0,xt._)`${m}.validate`,u,u.$async)}function p(m){let h=JS(t,m);Lc(t,h,m,m.$async)}function f(m){let h=e.scopeValue("schema",a.code.source===!0?{ref:m,code:(0,xt.stringify)(m)}:{ref:m}),g=e.name("valid"),y=t.subschema({schema:m,dataTypes:[],schemaPath:xt.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function JS(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,xt._)`${r.scopeValue("wrapper",{ref:e})}.validate`}Kn.getValidate=JS;function Lc(t,e,r,n){let{gen:o,it:s}=t,{allErrors:i,schemaEnv:a,opts:c}=s,u=c.passContext?qo.default.this:xt.nil;n?l():d();function l(){if(!a.$async)throw new Error("async schema referenced by sync schema");let m=o.let("valid");o.try(()=>{o.code((0,xt._)`await ${(0,GS.callValidateCode)(t,e,u)}`),f(e),i||o.assign(m,!0)},h=>{o.if((0,xt._)`!(${h} instanceof ${s.ValidationError})`,()=>o.throw(h)),p(h),i||o.assign(m,!1)}),t.ok(m)}function d(){t.result((0,GS.callValidateCode)(t,e,u),()=>f(e),()=>p(e))}function p(m){let h=(0,xt._)`${m}.errors`;o.assign(qo.default.vErrors,(0,xt._)`${qo.default.vErrors} === null ? ${h} : ${qo.default.vErrors}.concat(${h})`),o.assign(qo.default.errors,(0,xt._)`${qo.default.vErrors}.length`)}function f(m){var h;if(!s.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(s.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(s.props=Mc.mergeEvaluated.props(o,g.props,s.props));else{let y=o.var("props",(0,xt._)`${m}.evaluated.props`);s.props=Mc.mergeEvaluated.props(o,y,s.props,xt.Name)}if(s.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(s.items=Mc.mergeEvaluated.items(o,g.items,s.items));else{let y=o.var("items",(0,xt._)`${m}.evaluated.items`);s.items=Mc.mergeEvaluated.items(o,y,s.items,xt.Name)}}}Kn.callRef=Lc;Kn.default=fN});var XS=C(Vf=>{"use strict";Object.defineProperty(Vf,"__esModule",{value:!0});var hN=WS(),gN=YS(),_N=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",hN.default,gN.default];Vf.default=_N});var QS=C(Wf=>{"use strict";Object.defineProperty(Wf,"__esModule",{value:!0});var Fc=Q(),cn=Fc.operators,Uc={maximum:{okStr:"<=",ok:cn.LTE,fail:cn.GT},minimum:{okStr:">=",ok:cn.GTE,fail:cn.LT},exclusiveMaximum:{okStr:"<",ok:cn.LT,fail:cn.GTE},exclusiveMinimum:{okStr:">",ok:cn.GT,fail:cn.LTE}},yN={message:({keyword:t,schemaCode:e})=>(0,Fc.str)`must be ${Uc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,Fc._)`{comparison: ${Uc[t].okStr}, limit: ${e}}`},xN={keyword:Object.keys(Uc),type:"number",schemaType:"number",$data:!0,error:yN,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,Fc._)`${r} ${Uc[e].fail} ${n} || isNaN(${r})`)}};Wf.default=xN});var e0=C(Gf=>{"use strict";Object.defineProperty(Gf,"__esModule",{value:!0});var yi=Q(),vN={message:({schemaCode:t})=>(0,yi.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,yi._)`{multipleOf: ${t}}`},bN={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:vN,code(t){let{gen:e,data:r,schemaCode:n,it:o}=t,s=o.opts.multipleOfPrecision,i=e.let("res"),a=s?(0,yi._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${s}`:(0,yi._)`${i} !== parseInt(${i})`;t.fail$data((0,yi._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};Gf.default=bN});var r0=C(Kf=>{"use strict";Object.defineProperty(Kf,"__esModule",{value:!0});function t0(t){let e=t.length,r=0,n=0,o;for(;n<e;)r++,o=t.charCodeAt(n++),o>=55296&&o<=56319&&n<e&&(o=t.charCodeAt(n),(o&64512)===56320&&n++);return r}Kf.default=t0;t0.code='require("ajv/dist/runtime/ucs2length").default'});var n0=C(Jf=>{"use strict";Object.defineProperty(Jf,"__esModule",{value:!0});var Jn=Q(),SN=ue(),kN=r0(),wN={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,Jn.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,Jn._)`{limit: ${t}}`},$N={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:wN,code(t){let{keyword:e,data:r,schemaCode:n,it:o}=t,s=e==="maxLength"?Jn.operators.GT:Jn.operators.LT,i=o.opts.unicode===!1?(0,Jn._)`${r}.length`:(0,Jn._)`${(0,SN.useFunc)(t.gen,kN.default)}(${r})`;t.fail$data((0,Jn._)`${i} ${s} ${n}`)}};Jf.default=$N});var o0=C(Yf=>{"use strict";Object.defineProperty(Yf,"__esModule",{value:!0});var EN=Ft(),TN=ue(),Bo=Q(),PN={message:({schemaCode:t})=>(0,Bo.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,Bo._)`{pattern: ${t}}`},RN={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:PN,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t,a=i.opts.unicodeRegExp?"u":"";if(n){let{regExp:c}=i.opts.code,u=c.code==="new RegExp"?(0,Bo._)`new RegExp`:(0,TN.useFunc)(e,c),l=e.let("valid");e.try(()=>e.assign(l,(0,Bo._)`${u}(${s}, ${a}).test(${r})`),()=>e.assign(l,!1)),t.fail$data((0,Bo._)`!${l}`)}else{let c=(0,EN.usePattern)(t,o);t.fail$data((0,Bo._)`!${c}.test(${r})`)}}};Yf.default=RN});var s0=C(Xf=>{"use strict";Object.defineProperty(Xf,"__esModule",{value:!0});var xi=Q(),CN={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,xi.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,xi._)`{limit: ${t}}`},ON={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:CN,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxProperties"?xi.operators.GT:xi.operators.LT;t.fail$data((0,xi._)`Object.keys(${r}).length ${o} ${n}`)}};Xf.default=ON});var i0=C(Qf=>{"use strict";Object.defineProperty(Qf,"__esModule",{value:!0});var vi=Ft(),bi=Q(),IN=ue(),AN={message:({params:{missingProperty:t}})=>(0,bi.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,bi._)`{missingProperty: ${t}}`},NN={keyword:"required",type:"object",schemaType:"array",$data:!0,error:AN,code(t){let{gen:e,schema:r,schemaCode:n,data:o,$data:s,it:i}=t,{opts:a}=i;if(!s&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():l(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:m}=t.it;for(let h of r)if(f?.[h]===void 0&&!m.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,IN.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||s)t.block$data(bi.nil,d);else for(let f of r)(0,vi.checkReportMissingProp)(t,f)}function l(){let f=e.let("missing");if(c||s){let m=e.let("valid",!0);t.block$data(m,()=>p(f,m)),t.ok(m)}else e.if((0,vi.checkMissingProp)(t,r,f)),(0,vi.reportMissingProp)(t,f),e.else()}function d(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,vi.noPropertyInData)(e,o,f,a.ownProperties),()=>t.error())})}function p(f,m){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(m,(0,vi.propertyInData)(e,o,f,a.ownProperties)),e.if((0,bi.not)(m),()=>{t.error(),e.break()})},bi.nil)}}};Qf.default=NN});var a0=C(eh=>{"use strict";Object.defineProperty(eh,"__esModule",{value:!0});var Si=Q(),zN={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Si.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Si._)`{limit: ${t}}`},jN={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:zN,code(t){let{keyword:e,data:r,schemaCode:n}=t,o=e==="maxItems"?Si.operators.GT:Si.operators.LT;t.fail$data((0,Si._)`${r}.length ${o} ${n}`)}};eh.default=jN});var Zc=C(th=>{"use strict";Object.defineProperty(th,"__esModule",{value:!0});var c0=$f();c0.code='require("ajv/dist/runtime/equal").default';th.default=c0});var u0=C(nh=>{"use strict";Object.defineProperty(nh,"__esModule",{value:!0});var rh=ci(),Xe=Q(),DN=ue(),MN=Zc(),LN={message:({params:{i:t,j:e}})=>(0,Xe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Xe._)`{i: ${t}, j: ${e}}`},FN={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:LN,code(t){let{gen:e,data:r,$data:n,schema:o,parentSchema:s,schemaCode:i,it:a}=t;if(!n&&!o)return;let c=e.let("valid"),u=s.items?(0,rh.getSchemaTypes)(s.items):[];t.block$data(c,l,(0,Xe._)`${i} === false`),t.ok(c);function l(){let m=e.let("i",(0,Xe._)`${r}.length`),h=e.let("j");t.setParams({i:m,j:h}),e.assign(c,!0),e.if((0,Xe._)`${m} > 1`,()=>(d()?p:f)(m,h))}function d(){return u.length>0&&!u.some(m=>m==="object"||m==="array")}function p(m,h){let g=e.name("item"),y=(0,rh.checkDataTypes)(u,g,a.opts.strictNumbers,rh.DataType.Wrong),_=e.const("indices",(0,Xe._)`{}`);e.for((0,Xe._)`;${m}--;`,()=>{e.let(g,(0,Xe._)`${r}[${m}]`),e.if(y,(0,Xe._)`continue`),u.length>1&&e.if((0,Xe._)`typeof ${g} == "string"`,(0,Xe._)`${g} += "_"`),e.if((0,Xe._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,Xe._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Xe._)`${_}[${g}] = ${m}`)})}function f(m,h){let g=(0,DN.useFunc)(e,MN.default),y=e.name("outer");e.label(y).for((0,Xe._)`;${m}--;`,()=>e.for((0,Xe._)`${h} = ${m}; ${h}--;`,()=>e.if((0,Xe._)`${g}(${r}[${m}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};nh.default=FN});var l0=C(sh=>{"use strict";Object.defineProperty(sh,"__esModule",{value:!0});var oh=Q(),UN=ue(),ZN=Zc(),HN={message:"must be equal to constant",params:({schemaCode:t})=>(0,oh._)`{allowedValue: ${t}}`},qN={keyword:"const",$data:!0,error:HN,code(t){let{gen:e,data:r,$data:n,schemaCode:o,schema:s}=t;n||s&&typeof s=="object"?t.fail$data((0,oh._)`!${(0,UN.useFunc)(e,ZN.default)}(${r}, ${o})`):t.fail((0,oh._)`${s} !== ${r}`)}};sh.default=qN});var d0=C(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var ki=Q(),BN=ue(),VN=Zc(),WN={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,ki._)`{allowedValues: ${t}}`},GN={keyword:"enum",schemaType:"array",$data:!0,error:WN,code(t){let{gen:e,data:r,$data:n,schema:o,schemaCode:s,it:i}=t;if(!n&&o.length===0)throw new Error("enum must have non-empty array");let a=o.length>=i.opts.loopEnum,c,u=()=>c??(c=(0,BN.useFunc)(e,VN.default)),l;if(a||n)l=e.let("valid"),t.block$data(l,d);else{if(!Array.isArray(o))throw new Error("ajv implementation error");let f=e.const("vSchema",s);l=(0,ki.or)(...o.map((m,h)=>p(f,h)))}t.pass(l);function d(){e.assign(l,!1),e.forOf("v",s,f=>e.if((0,ki._)`${u()}(${r}, ${f})`,()=>e.assign(l,!0).break()))}function p(f,m){let h=o[m];return typeof h=="object"&&h!==null?(0,ki._)`${u()}(${r}, ${f}[${m}])`:(0,ki._)`${r} === ${h}`}}};ih.default=GN});var p0=C(ah=>{"use strict";Object.defineProperty(ah,"__esModule",{value:!0});var KN=QS(),JN=e0(),YN=n0(),XN=o0(),QN=s0(),ez=i0(),tz=a0(),rz=u0(),nz=l0(),oz=d0(),sz=[KN.default,JN.default,YN.default,XN.default,QN.default,ez.default,tz.default,rz.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},nz.default,oz.default];ah.default=sz});var uh=C(wi=>{"use strict";Object.defineProperty(wi,"__esModule",{value:!0});wi.validateAdditionalItems=void 0;var Yn=Q(),ch=ue(),iz={message:({params:{len:t}})=>(0,Yn.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,Yn._)`{limit: ${t}}`},az={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:iz,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,ch.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}m0(t,n)}};function m0(t,e){let{gen:r,schema:n,data:o,keyword:s,it:i}=t;i.items=!0;let a=r.const("len",(0,Yn._)`${o}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,Yn._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,ch.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,Yn._)`${a} <= ${e.length}`);r.if((0,Yn.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,l=>{t.subschema({keyword:s,dataProp:l,dataPropType:ch.Type.Num},u),i.allErrors||r.if((0,Yn.not)(u),()=>r.break())})}}wi.validateAdditionalItems=m0;wi.default=az});var lh=C($i=>{"use strict";Object.defineProperty($i,"__esModule",{value:!0});$i.validateTuple=void 0;var f0=Q(),Hc=ue(),cz=Ft(),uz={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return h0(t,"additionalItems",e);r.items=!0,!(0,Hc.alwaysValidSchema)(r,e)&&t.ok((0,cz.validateArray)(t))}};function h0(t,e,r=t.schema){let{gen:n,parentSchema:o,data:s,keyword:i,it:a}=t;l(o),a.opts.unevaluated&&r.length&&a.items!==!0&&(a.items=Hc.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,f0._)`${s}.length`);r.forEach((d,p)=>{(0,Hc.alwaysValidSchema)(a,d)||(n.if((0,f0._)`${u} > ${p}`,()=>t.subschema({keyword:i,schemaProp:p,dataProp:p},c)),t.ok(c))});function l(d){let{opts:p,errSchemaPath:f}=a,m=r.length,h=m===d.minItems&&(m===d.maxItems||d[e]===!1);if(p.strictTuples&&!h){let g=`"${i}" is ${m}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,Hc.checkStrictMode)(a,g,p.strictTuples)}}}$i.validateTuple=h0;$i.default=uz});var g0=C(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var lz=lh(),dz={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,lz.validateTuple)(t,"items")};dh.default=dz});var y0=C(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var _0=Q(),pz=ue(),mz=Ft(),fz=uh(),hz={message:({params:{len:t}})=>(0,_0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,_0._)`{limit: ${t}}`},gz={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:hz,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:o}=r;n.items=!0,!(0,pz.alwaysValidSchema)(n,e)&&(o?(0,fz.validateAdditionalItems)(t,o):t.ok((0,mz.validateArray)(t)))}};ph.default=gz});var x0=C(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var Zt=Q(),qc=ue(),_z={message:({params:{min:t,max:e}})=>e===void 0?(0,Zt.str)`must contain at least ${t} valid item(s)`:(0,Zt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Zt._)`{minContains: ${t}}`:(0,Zt._)`{minContains: ${t}, maxContains: ${e}}`},yz={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:_z,code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t,i,a,{minContains:c,maxContains:u}=n;s.opts.next?(i=c===void 0?1:c,a=u):i=1;let l=e.const("len",(0,Zt._)`${o}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,qc.checkStrictMode)(s,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,qc.checkStrictMode)(s,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,qc.alwaysValidSchema)(s,r)){let h=(0,Zt._)`${l} >= ${i}`;a!==void 0&&(h=(0,Zt._)`${h} && ${l} <= ${a}`),t.pass(h);return}s.items=!0;let d=e.name("valid");a===void 0&&i===1?f(d,()=>e.if(d,()=>e.break())):i===0?(e.let(d,!0),a!==void 0&&e.if((0,Zt._)`${o}.length > 0`,p)):(e.let(d,!1),p()),t.result(d,()=>t.reset());function p(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>m(g)))}function f(h,g){e.forRange("i",0,l,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:qc.Type.Num,compositeRule:!0},h),g()})}function m(h){e.code((0,Zt._)`${h}++`),a===void 0?e.if((0,Zt._)`${h} >= ${i}`,()=>e.assign(d,!0).break()):(e.if((0,Zt._)`${h} > ${a}`,()=>e.assign(d,!1).break()),i===1?e.assign(d,!0):e.if((0,Zt._)`${h} >= ${i}`,()=>e.assign(d,!0)))}}};mh.default=yz});var S0=C(fr=>{"use strict";Object.defineProperty(fr,"__esModule",{value:!0});fr.validateSchemaDeps=fr.validatePropertyDeps=fr.error=void 0;var fh=Q(),xz=ue(),Ei=Ft();fr.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,fh.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,fh._)`{property: ${t},
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 gf,sr,UA,Ac=v(()=>{cn();sr={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:()=>(gf===void 0&&(gf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),gf),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-_]*$/};UA=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789")});function Nc(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===P.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]})??Ne(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===P.ZodString&&t.keyType._def.checks?.length){let{type:n,...s}=Ic(t.keyType._def,e);return{...r,propertyNames:s}}else{if(t.keyType?._def.typeName===P.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};if(t.keyType?._def.typeName===P.ZodBranded&&t.keyType._def.type._def.typeName===P.ZodString&&t.keyType._def.type._def.checks?.length){let{type:n,...s}=Cc(t.keyType._def,e);return{...r,propertyNames:s}}}return r}var Dc=v(()=>{jo();He();Ac();Oc();Vt()});function cS(t,e){if(e.mapStrategy==="record")return Nc(t,e);let r=J(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ne(e),n=J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ne(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,n],minItems:2,maxItems:2}}}var _f=v(()=>{He();Dc();Vt()});function uS(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 xf=v(()=>{});function lS(t){return t.target==="openAi"?void 0:{not:Ne({...t,currentPath:[...t.currentPath,"not"]})}}var vf=v(()=>{Vt()});function dS(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var bf=v(()=>{});function mS(t,e){if(e.target==="openApi3")return pS(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(n=>n._def.typeName in ui&&(!n._def.checks||!n._def.checks.length))){let n=r.reduce((s,o)=>{let i=ui[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 pS(t,e)}var ui,pS,Mc=v(()=>{He();ui={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};pS=(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 fS(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:ui[t.innerType._def.typeName],nullable:!0}:{type:[ui[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 Sf=v(()=>{He();Mc()});function hS(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?ue(r,"minimum",n.value,n.message,e):ue(r,"exclusiveMinimum",n.value,n.message,e):(n.inclusive||(r.exclusiveMinimum=!0),ue(r,"minimum",n.value,n.message,e));break;case"max":e.target==="jsonSchema7"?n.inclusive?ue(r,"maximum",n.value,n.message,e):ue(r,"exclusiveMaximum",n.value,n.message,e):(n.inclusive||(r.exclusiveMaximum=!0),ue(r,"maximum",n.value,n.message,e));break;case"multipleOf":ue(r,"multipleOf",n.value,n.message,e);break}return r}var kf=v(()=>{cn()});function gS(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=BA(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=ZA(t,e);return i!==void 0&&(n.additionalProperties=i),n}function ZA(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 BA(t){try{return t.isOptional()}catch{return!0}}var wf=v(()=>{He()});var yS,Ef=v(()=>{He();Vt();yS=(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:Ne(e)},r]}:Ne(e)}});var _S,$f=v(()=>{He();_S=(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 xS(t,e){return J(t.type._def,e)}var Tf=v(()=>{He()});function vS(t,e){let n={type:"array",uniqueItems:!0,items:J(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ue(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ue(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}var Pf=v(()=>{cn();He()});function bS(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 Rf=v(()=>{He()});function SS(t){return{not:Ne(t)}}var Cf=v(()=>{Vt()});function kS(t){return Ne(t)}var Of=v(()=>{Vt()});var wS,If=v(()=>{He();wS=(t,e)=>J(t.innerType._def,e)});var ES,Af=v(()=>{jo();Vt();sf();of();af();Oc();cf();lf();df();pf();mf();ff();hf();_f();xf();vf();bf();Sf();kf();wf();Ef();$f();Tf();Dc();Pf();Ac();Rf();Cf();Mc();Of();If();ES=(t,e,r)=>{switch(e){case P.ZodString:return Ic(t,r);case P.ZodNumber:return hS(t,r);case P.ZodObject:return gS(t,r);case P.ZodBigInt:return Qb(t,r);case P.ZodBoolean:return eS();case P.ZodDate:return uf(t,r);case P.ZodUndefined:return SS(r);case P.ZodNull:return dS(r);case P.ZodArray:return Xb(t,r);case P.ZodUnion:case P.ZodDiscriminatedUnion:return mS(t,r);case P.ZodIntersection:return oS(t,r);case P.ZodTuple:return bS(t,r);case P.ZodRecord:return Nc(t,r);case P.ZodLiteral:return iS(t,r);case P.ZodEnum:return sS(t);case P.ZodNativeEnum:return uS(t);case P.ZodNullable:return fS(t,r);case P.ZodOptional:return yS(t,r);case P.ZodMap:return cS(t,r);case P.ZodSet:return vS(t,r);case P.ZodLazy:return()=>t.getter()._def;case P.ZodPromise:return xS(t,r);case P.ZodNaN:case P.ZodNever:return lS(r);case P.ZodEffects:return nS(t,r);case P.ZodAny:return Ne(r);case P.ZodUnknown:return kS(r);case P.ZodDefault:return rS(t,r);case P.ZodBranded:return Cc(t,r);case P.ZodReadonly:return wS(t,r);case P.ZodCatch:return tS(t,r);case P.ZodPipeline:return _S(t,r);case P.ZodFunction:case P.ZodVoid:case P.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!==Kb)return a}if(n&&!r){let a=qA(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=ES(t,t.typeName,e),i=typeof o=="function"?J(o(),e):o;if(i&&VA(t,e,i),e.postProcess){let a=e.postProcess(i,t,e);return s.jsonSchema=i,a}return s.jsonSchema=i,i}var qA,VA,He=v(()=>{Tc();Af();Rc();Vt();qA=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:Pc(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`),Ne(e)):e.$refStrategy==="seen"?Ne(e):void 0}},VA=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r)});var $S=v(()=>{});var Nf,Df=v(()=>{He();rf();Vt();Nf=(t,e)=>{let r=Yb(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)??Ne(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)??Ne(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 TS=v(()=>{Tc();rf();cn();Rc();He();$S();Vt();sf();of();af();Oc();cf();lf();df();pf();mf();ff();hf();_f();xf();vf();bf();Sf();kf();wf();Ef();$f();Tf();If();Dc();Pf();Ac();Rf();Cf();Mc();Of();Af();Df();Df()});function WA(t){return!t||t==="jsonSchema7"||t==="draft-7"?"draft-7":t==="jsonSchema2019-09"||t==="draft-2020-12"?"draft-2020-12":"draft-7"}function Mf(t,e){return Zt(t)?Sm(t,{target:WA(e?.target),io:e?.pipeStrategy??"input"}):Nf(t,{strictUnions:e?.strictUnions??!0,pipeStrategy:e?.pipeStrategy??"input"})}function jf(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ic(r);if(typeof n!="string")throw new Error("Schema method literal must be a string");return n}function zf(t,e){let r=nn(t,e);if(!r.success)throw r.error;return r.data}var Lf=v(()=>{Em();Jo();TS()});function PS(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function RS(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];PS(i)&&PS(o)?r[s]={...i,...o}:r[s]=o}return r}var GA,jc,CS=v(()=>{Jo();Yn();Wb();Lf();GA=6e4,jc=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(mc,r=>{this._oncancel(r)}),this.setNotificationHandler(hc,r=>{this._onprogress(r)}),this.setRequestHandler(fc,r=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(gc,async(r,n)=>{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new L(q.InvalidParams,"Failed to retrieve task: Task not found");return{...s}}),this.setRequestHandler(_c,async(r,n)=>{let s=async()=>{let o=r.params.taskId;if(this._taskMessageQueue){let a;for(;a=await this._taskMessageQueue.dequeue(o,n.sessionId);){if(a.type==="response"||a.type==="error"){let c=a.message,u=c.id,d=this._requestResolvers.get(u);if(d)if(this._requestResolvers.delete(u),a.type==="response")d(c);else{let l=c,m=new L(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 L(q.InvalidParams,`Task not found: ${o}`);if(!an(i.status))return await this._waitForTaskUpdate(o,n.signal),await s();if(an(i.status)){let a=await this._taskStore.getTaskResult(o,n.sessionId);return this._clearTaskQueue(o),{...a,_meta:{...a._meta,[on]:{taskId:o}}}}return await s()};return await s()}),this.setRequestHandler(xc,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 L(q.InvalidParams,`Failed to list tasks: ${s instanceof Error?s.message:String(s)}`)}}),this.setRequestHandler(bc,async(r,n)=>{try{let s=await this._taskStore.getTask(r.params.taskId,n.sessionId);if(!s)throw new L(q.InvalidParams,`Task not found: ${r.params.taskId}`);if(an(s.status))throw new L(q.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 L(q.InvalidParams,`Task not found after cancellation: ${r.params.taskId}`);return{_meta:{},...o}}catch(s){throw s instanceof L?s:new L(q.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),L.fromError(q.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),ei(o)||Mb(o)?this._onresponse(o):Hm(o)?this._onrequest(o,i):Db(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=L.fromError(q.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?.[on]?.taskId;if(n===void 0){let d={jsonrpc:"2.0",id:e.id,error:{code:q.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=Ib(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 L(q.ConnectionClosed,"Request was cancelled");let f={...m,relatedRequestId:e.id};o&&!f.relatedTask&&(f.relatedTask={taskId:o});let p=f.relatedTask?.taskId??o;return p&&c&&await c.updateTaskStatus(p,"input_required"),await this.request(d,l,f)},authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo,taskId: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:q.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),ei(e))n(e);else{let i=new L(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(ei(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),ei(e))s(e);else{let i=L.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 L?i:new L(q.InternalError,String(i))}}return}let o;try{let i=await this.request(e,Fs,n);if(i.task)o=i.task.taskId,yield{type:"taskCreated",task:i.task};else throw new L(q.InternalError,"Task creation did not return a task");for(;;){let a=await this.getTask({taskId:o},n);if(yield{type:"taskStatus",task:a},an(a.status)){a.status==="completed"?yield{type:"result",result:await this.getTaskResult({taskId:o},r,n)}:a.status==="failed"?yield{type:"error",error:new L(q.InternalError,`Task ${o} failed`)}:a.status==="cancelled"&&(yield{type:"error",error:new L(q.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 L?i:new L(q.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=_=>{d(_)};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(_){l(_);return}n?.signal?.throwIfAborted();let m=this._requestMessageId++,f={...e,jsonrpc:"2.0",id:m};n?.onprogress&&(this._progressHandlers.set(m,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta||{},progressToken:m}}),a&&(f.params={...f.params,task:a}),c&&(f.params={...f.params,_meta:{...f.params?._meta||{},[on]:c}});let p=_=>{this._responseHandlers.delete(m),this._progressHandlers.delete(m),this._cleanupTimeout(m),this._transport?.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:m,reason:String(_)}},{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(S=>this._onerror(new Error(`Failed to send cancellation: ${S}`)));let x=_ instanceof L?_:new L(q.RequestTimeout,String(_));d(x)};this._responseHandlers.set(m,_=>{if(!n?.signal?.aborted){if(_ instanceof Error)return d(_);try{let x=nn(r,_.result);x.success?u(x.data):d(x.error)}catch(x){d(x)}}}),n?.signal?.addEventListener("abort",()=>{p(n?.signal?.reason)});let h=n?.timeout??GA,g=()=>p(L.fromError(q.RequestTimeout,"Request timed out",{timeout:h}));this._setupTimeout(m,h,n?.maxTotalTimeout,g,n?.resetTimeoutOnProgress??!1);let y=c?.taskId;if(y){let _=x=>{let S=this._responseHandlers.get(m);S?S(x):this._onerror(new Error(`Response handler missing for side-channeled request ${m}`))};this._requestResolvers.set(m,_),this._enqueueTaskMessage(y,{type:"request",message:f,timestamp:Date.now()}).catch(x=>{this._cleanupTimeout(m),d(x)})}else this._transport.send(f,{relatedRequestId:s,resumptionToken:o,onresumptiontoken:i}).catch(_=>{this._cleanupTimeout(m),d(_)})})}async getTask(e,r){return this.request({method:"tasks/get",params:e},yc,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},vc,r)}async cancelTask(e,r){return this.request({method:"tasks/cancel",params:e},Lb,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||{},[on]: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||{},[on]: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||{},[on]:r.relatedTask}}}),await this._transport.send(i,r)}setRequestHandler(e,r){let n=jf(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(s,o)=>{let i=zf(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=jf(e);this._notificationHandlers.set(n,s=>{let o=zf(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"&&Hm(s.message)){let o=s.message.id,i=this._requestResolvers.get(o);i?(i(new L(q.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 L(q.InvalidRequest,"Request cancelled"));return}let i=setTimeout(s,n);r.addEventListener("abort",()=>{clearTimeout(i),o(new L(q.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 L(q.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=oi.parse({method:"notifications/tasks/status",params:a});await this.notification(c),an(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 L(q.InvalidParams,`Task "${s}" not found - it may have been cleaned up`);if(an(a.status))throw new L(q.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=oi.parse({method:"notifications/tasks/status",params:c});await this.notification(u),an(c.status)&&this._cleanupTaskProgressHandler(s)}},listTasks:s=>n.listTasks(s,r)}}}});var pi=N(me=>{"use strict";Object.defineProperty(me,"__esModule",{value:!0});me.regexpCode=me.getEsmExportName=me.getProperty=me.safeStringify=me.stringify=me.strConcat=me.addCodeArg=me.str=me._=me.nil=me._Code=me.Name=me.IDENTIFIER=me._CodeOrName=void 0;var li=class{};me._CodeOrName=li;me.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Xn=class extends li{constructor(e){if(super(),!me.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}}};me.Name=Xn;var Wt=class extends li{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 Xn&&(r[n.str]=(r[n.str]||0)+1),r),{})}};me._Code=Wt;me.nil=new Wt("");function OS(t,...e){let r=[t[0]],n=0;for(;n<e.length;)Uf(r,e[n]),r.push(t[++n]);return new Wt(r)}me._=OS;var Ff=new Wt("+");function IS(t,...e){let r=[di(t[0])],n=0;for(;n<e.length;)r.push(Ff),Uf(r,e[n]),r.push(Ff,di(t[++n]));return KA(r),new Wt(r)}me.str=IS;function Uf(t,e){e instanceof Wt?t.push(...e._items):e instanceof Xn?t.push(e):t.push(XA(e))}me.addCodeArg=Uf;function KA(t){let e=1;for(;e<t.length-1;){if(t[e]===Ff){let r=JA(t[e-1],t[e+1]);if(r!==void 0){t.splice(e-1,3,r);continue}t[e++]="+"}e++}}function JA(t,e){if(e==='""')return t;if(t==='""')return e;if(typeof t=="string")return e instanceof Xn||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 Xn))return`"${t}${e.slice(1)}`}function YA(t,e){return e.emptyStr()?t:t.emptyStr()?e:IS`${t}${e}`}me.strConcat=YA;function XA(t){return typeof t=="number"||typeof t=="boolean"||t===null?t:di(Array.isArray(t)?t.join(","):t)}function QA(t){return new Wt(di(t))}me.stringify=QA;function di(t){return JSON.stringify(t).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}me.safeStringify=di;function e1(t){return typeof t=="string"&&me.IDENTIFIER.test(t)?new Wt(`.${t}`):OS`[${t}]`}me.getProperty=e1;function t1(t){if(typeof t=="string"&&me.IDENTIFIER.test(t))return new Wt(`${t}`);throw new Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}me.getEsmExportName=t1;function r1(t){return new Wt(t.toString())}me.regexpCode=r1});var Bf=N(kt=>{"use strict";Object.defineProperty(kt,"__esModule",{value:!0});kt.ValueScope=kt.ValueScopeName=kt.Scope=kt.varKinds=kt.UsedValueState=void 0;var St=pi(),Hf=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},zc;(function(t){t[t.Started=0]="Started",t[t.Completed=1]="Completed"})(zc||(kt.UsedValueState=zc={}));kt.varKinds={const:new St.Name("const"),let:new St.Name("let"),var:new St.Name("var")};var Lc=class{constructor({prefixes:e,parent:r}={}){this._names={},this._prefixes=e,this._parent=r}toName(e){return e instanceof St.Name?e:this.name(e)}name(e){return new St.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}}};kt.Scope=Lc;var Fc=class extends St.Name{constructor(e,r){super(r),this.prefix=e}setValue(e,{property:r,itemIndex:n}){this.value=e,this.scopePath=(0,St._)`.${new St.Name(r)}[${n}]`}};kt.ValueScopeName=Fc;var n1=(0,St._)`\n`,Zf=class extends Lc{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?n1:St.nil}}get(){return this._scope}name(e){return new Fc(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,St._)`${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=St.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,zc.Started);let d=r(u);if(d){let l=this.opts.es5?kt.varKinds.var:kt.varKinds.const;o=(0,St._)`${o}${l} ${u} = ${d};${this.opts._n}`}else if(d=s?.(u))o=(0,St._)`${o}${d}${this.opts._n}`;else throw new Hf(u);c.set(u,zc.Completed)})}return o}};kt.ValueScope=Zf});var te=N(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.or=re.and=re.not=re.CodeGen=re.operators=re.varKinds=re.ValueScopeName=re.ValueScope=re.Scope=re.Name=re.regexpCode=re.stringify=re.getProperty=re.nil=re.strConcat=re.str=re._=void 0;var le=pi(),ir=Bf(),un=pi();Object.defineProperty(re,"_",{enumerable:!0,get:function(){return un._}});Object.defineProperty(re,"str",{enumerable:!0,get:function(){return un.str}});Object.defineProperty(re,"strConcat",{enumerable:!0,get:function(){return un.strConcat}});Object.defineProperty(re,"nil",{enumerable:!0,get:function(){return un.nil}});Object.defineProperty(re,"getProperty",{enumerable:!0,get:function(){return un.getProperty}});Object.defineProperty(re,"stringify",{enumerable:!0,get:function(){return un.stringify}});Object.defineProperty(re,"regexpCode",{enumerable:!0,get:function(){return un.regexpCode}});Object.defineProperty(re,"Name",{enumerable:!0,get:function(){return un.Name}});var Bc=Bf();Object.defineProperty(re,"Scope",{enumerable:!0,get:function(){return Bc.Scope}});Object.defineProperty(re,"ValueScope",{enumerable:!0,get:function(){return Bc.ValueScope}});Object.defineProperty(re,"ValueScopeName",{enumerable:!0,get:function(){return Bc.ValueScopeName}});Object.defineProperty(re,"varKinds",{enumerable:!0,get:function(){return Bc.varKinds}});re.operators={GT:new le._Code(">"),GTE:new le._Code(">="),LT:new le._Code("<"),LTE:new le._Code("<="),EQ:new le._Code("==="),NEQ:new le._Code("!=="),NOT:new le._Code("!"),OR:new le._Code("||"),AND:new le._Code("&&"),ADD:new le._Code("+")};var Nr=class{optimizeNodes(){return this}optimizeNames(e,r){return this}},qf=class extends Nr{constructor(e,r,n){super(),this.varKind=e,this.name=r,this.rhs=n}render({es5:e,_n:r}){let n=e?ir.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=Gs(this.rhs,e,r)),this}get names(){return this.rhs instanceof le._CodeOrName?this.rhs.names:{}}},Uc=class extends Nr{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 le.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=Gs(this.rhs,e,r),this}get names(){let e=this.lhs instanceof le.Name?{}:{...this.lhs.names};return Zc(e,this.rhs)}},Vf=class extends Uc{constructor(e,r,n,s){super(e,n,s),this.op=r}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},Wf=class extends Nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},Gf=class extends Nr{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:""};`+e}},Kf=class extends Nr{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},Jf=class extends Nr{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=Gs(this.code,e,r),this}get names(){return this.code instanceof le._CodeOrName?this.code.names:{}}},mi=class extends Nr{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)||(s1(e,o.names),n.splice(s,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,r)=>ts(e,r.names),{})}},Dr=class extends mi{render(e){return"{"+e._n+super.render(e)+"}"+e._n}},Yf=class extends mi{},Ws=class extends Dr{};Ws.kind="else";var Qn=class t extends Dr{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 Ws(n):n}if(r)return e===!1?r instanceof t?r:r.nodes:this.nodes.length?this:new t(AS(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=Gs(this.condition,e,r),this}get names(){let e=super.names;return Zc(e,this.condition),this.else&&ts(e,this.else.names),e}};Qn.kind="if";var es=class extends Dr{};es.kind="for";var Xf=class extends es{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=Gs(this.iteration,e,r),this}get names(){return ts(super.names,this.iteration.names)}},Qf=class extends es{constructor(e,r,n,s){super(),this.varKind=e,this.name=r,this.from=n,this.to=s}render(e){let r=e.es5?ir.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=Zc(super.names,this.from);return Zc(e,this.to)}},Hc=class extends es{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=Gs(this.iterable,e,r),this}get names(){return ts(super.names,this.iterable.names)}},fi=class extends Dr{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)}};fi.kind="func";var hi=class extends mi{render(e){return"return "+super.render(e)}};hi.kind="return";var eh=class extends Dr{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&&ts(e,this.catch.names),this.finally&&ts(e,this.finally.names),e}},gi=class extends Dr{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};gi.kind="catch";var yi=class extends Dr{render(e){return"finally"+super.render(e)}};yi.kind="finally";var th=class{constructor(e,r={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...r,_n:r.lines?`
65
+ `:""},this._extScope=e,this._scope=new ir.Scope({parent:e}),this._nodes=[new Yf]}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 qf(e,o,n)),o}const(e,r,n){return this._def(ir.varKinds.const,e,r,n)}let(e,r,n){return this._def(ir.varKinds.let,e,r,n)}var(e,r,n){return this._def(ir.varKinds.var,e,r,n)}assign(e,r,n){return this._leafNode(new Uc(e,r,n))}add(e,r){return this._leafNode(new Vf(e,re.operators.ADD,r))}code(e){return typeof e=="function"?e():e!==le.nil&&this._leafNode(new Jf(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,le.addCodeArg)(r,s));return r.push("}"),new le._Code(r)}if(e,r,n){if(this._blockNode(new Qn(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 Qn(e))}else(){return this._elseNode(new Ws)}endIf(){return this._endBlockNode(Qn,Ws)}_for(e,r){return this._blockNode(e),r&&this.code(r).endFor(),this}for(e,r){return this._for(new Xf(e),r)}forRange(e,r,n,s,o=this.opts.es5?ir.varKinds.var:ir.varKinds.let){let i=this._scope.toName(e);return this._for(new Qf(o,i,r,n),()=>s(i))}forOf(e,r,n,s=ir.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let i=r instanceof le.Name?r:this.var("_arr",r);return this.forRange("_i",0,(0,le._)`${i}.length`,a=>{this.var(o,(0,le._)`${i}[${a}]`),n(o)})}return this._for(new Hc("of",s,o,r),()=>n(o))}forIn(e,r,n,s=this.opts.es5?ir.varKinds.var:ir.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,le._)`Object.keys(${r})`,n);let o=this._scope.toName(e);return this._for(new Hc("in",s,o,r),()=>n(o))}endFor(){return this._endBlockNode(es)}label(e){return this._leafNode(new Wf(e))}break(e){return this._leafNode(new Gf(e))}return(e){let r=new hi;if(this._blockNode(r),this.code(e),r.nodes.length!==1)throw new Error('CodeGen: "return" should have one node');return this._endBlockNode(hi)}try(e,r,n){if(!r&&!n)throw new Error('CodeGen: "try" without "catch" and "finally"');let s=new eh;if(this._blockNode(s),this.code(e),r){let o=this.name("e");this._currNode=s.catch=new gi(o),r(o)}return n&&(this._currNode=s.finally=new yi,this.code(n)),this._endBlockNode(gi,yi)}throw(e){return this._leafNode(new Kf(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=le.nil,n,s){return this._blockNode(new fi(e,r,n)),s&&this.code(s).endFunc(),this}endFunc(){return this._endBlockNode(fi)}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 Qn))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}};re.CodeGen=th;function ts(t,e){for(let r in e)t[r]=(t[r]||0)+(e[r]||0);return t}function Zc(t,e){return e instanceof le._CodeOrName?ts(t,e.names):t}function Gs(t,e,r){if(t instanceof le.Name)return n(t);if(!s(t))return t;return new le._Code(t._items.reduce((o,i)=>(i instanceof le.Name&&(i=n(i)),i instanceof le._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 le._Code&&o._items.some(i=>i instanceof le.Name&&e[i.str]===1&&r[i.str]!==void 0)}}function s1(t,e){for(let r in e)t[r]=(t[r]||0)-(e[r]||0)}function AS(t){return typeof t=="boolean"||typeof t=="number"||t===null?!t:(0,le._)`!${rh(t)}`}re.not=AS;var o1=NS(re.operators.AND);function i1(...t){return t.reduce(o1)}re.and=i1;var a1=NS(re.operators.OR);function c1(...t){return t.reduce(a1)}re.or=c1;function NS(t){return(e,r)=>e===le.nil?r:r===le.nil?e:(0,le._)`${rh(e)} ${t} ${rh(r)}`}function rh(t){return t instanceof le.Name?t:(0,le._)`(${t})`}});var de=N(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.checkStrictMode=ne.getErrorPath=ne.Type=ne.useFunc=ne.setEvaluated=ne.evaluatedPropsToName=ne.mergeEvaluated=ne.eachItem=ne.unescapeJsonPointer=ne.escapeJsonPointer=ne.escapeFragment=ne.unescapeFragment=ne.schemaRefOrVal=ne.schemaHasRulesButRef=ne.schemaHasRules=ne.checkUnknownRules=ne.alwaysValidSchema=ne.toHash=void 0;var ve=te(),u1=pi();function l1(t){let e={};for(let r of t)e[r]=!0;return e}ne.toHash=l1;function d1(t,e){return typeof e=="boolean"?e:Object.keys(e).length===0?!0:(jS(t,e),!zS(e,t.self.RULES.all))}ne.alwaysValidSchema=d1;function jS(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]||US(t,`unknown keyword: "${o}"`)}ne.checkUnknownRules=jS;function zS(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(e[r])return!0;return!1}ne.schemaHasRules=zS;function p1(t,e){if(typeof t=="boolean")return!t;for(let r in t)if(r!=="$ref"&&e.all[r])return!0;return!1}ne.schemaHasRulesButRef=p1;function m1({topSchemaRef:t,schemaPath:e},r,n,s){if(!s){if(typeof r=="number"||typeof r=="boolean")return r;if(typeof r=="string")return(0,ve._)`${r}`}return(0,ve._)`${t}${e}${(0,ve.getProperty)(n)}`}ne.schemaRefOrVal=m1;function f1(t){return LS(decodeURIComponent(t))}ne.unescapeFragment=f1;function h1(t){return encodeURIComponent(sh(t))}ne.escapeFragment=h1;function sh(t){return typeof t=="number"?`${t}`:t.replace(/~/g,"~0").replace(/\//g,"~1")}ne.escapeJsonPointer=sh;function LS(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}ne.unescapeJsonPointer=LS;function g1(t,e){if(Array.isArray(t))for(let r of t)e(r);else e(t)}ne.eachItem=g1;function DS({mergeNames:t,mergeToName:e,mergeValues:r,resultToName:n}){return(s,o,i,a)=>{let c=i===void 0?o:i instanceof ve.Name?(o instanceof ve.Name?t(s,o,i):e(s,o,i),i):o instanceof ve.Name?(e(s,i,o),o):r(o,i);return a===ve.Name&&!(c instanceof ve.Name)?n(s,c):c}}ne.mergeEvaluated={props:DS({mergeNames:(t,e,r)=>t.if((0,ve._)`${r} !== true && ${e} !== undefined`,()=>{t.if((0,ve._)`${e} === true`,()=>t.assign(r,!0),()=>t.assign(r,(0,ve._)`${r} || {}`).code((0,ve._)`Object.assign(${r}, ${e})`))}),mergeToName:(t,e,r)=>t.if((0,ve._)`${r} !== true`,()=>{e===!0?t.assign(r,!0):(t.assign(r,(0,ve._)`${r} || {}`),oh(t,r,e))}),mergeValues:(t,e)=>t===!0?!0:{...t,...e},resultToName:FS}),items:DS({mergeNames:(t,e,r)=>t.if((0,ve._)`${r} !== true && ${e} !== undefined`,()=>t.assign(r,(0,ve._)`${e} === true ? true : ${r} > ${e} ? ${r} : ${e}`)),mergeToName:(t,e,r)=>t.if((0,ve._)`${r} !== true`,()=>t.assign(r,e===!0?!0:(0,ve._)`${r} > ${e} ? ${r} : ${e}`)),mergeValues:(t,e)=>t===!0?!0:Math.max(t,e),resultToName:(t,e)=>t.var("items",e)})};function FS(t,e){if(e===!0)return t.var("props",!0);let r=t.var("props",(0,ve._)`{}`);return e!==void 0&&oh(t,r,e),r}ne.evaluatedPropsToName=FS;function oh(t,e,r){Object.keys(r).forEach(n=>t.assign((0,ve._)`${e}${(0,ve.getProperty)(n)}`,!0))}ne.setEvaluated=oh;var MS={};function y1(t,e){return t.scopeValue("func",{ref:e,code:MS[e.code]||(MS[e.code]=new u1._Code(e.code))})}ne.useFunc=y1;var nh;(function(t){t[t.Num=0]="Num",t[t.Str=1]="Str"})(nh||(ne.Type=nh={}));function _1(t,e,r){if(t instanceof ve.Name){let n=e===nh.Num;return r?n?(0,ve._)`"[" + ${t} + "]"`:(0,ve._)`"['" + ${t} + "']"`:n?(0,ve._)`"/" + ${t}`:(0,ve._)`"/" + ${t}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,ve.getProperty)(t).toString():"/"+sh(t)}ne.getErrorPath=_1;function US(t,e,r=t.opts.strictSchema){if(r){if(e=`strict mode: ${e}`,r===!0)throw new Error(e);t.self.logger.warn(e)}}ne.checkStrictMode=US});var Mr=N(ih=>{"use strict";Object.defineProperty(ih,"__esModule",{value:!0});var st=te(),x1={data:new st.Name("data"),valCxt:new st.Name("valCxt"),instancePath:new st.Name("instancePath"),parentData:new st.Name("parentData"),parentDataProperty:new st.Name("parentDataProperty"),rootData:new st.Name("rootData"),dynamicAnchors:new st.Name("dynamicAnchors"),vErrors:new st.Name("vErrors"),errors:new st.Name("errors"),this:new st.Name("this"),self:new st.Name("self"),scope:new st.Name("scope"),json:new st.Name("json"),jsonPos:new st.Name("jsonPos"),jsonLen:new st.Name("jsonLen"),jsonPart:new st.Name("jsonPart")};ih.default=x1});var _i=N(ot=>{"use strict";Object.defineProperty(ot,"__esModule",{value:!0});ot.extendErrors=ot.resetErrorsCount=ot.reportExtraError=ot.reportError=ot.keyword$DataError=ot.keywordError=void 0;var pe=te(),qc=de(),mt=Mr();ot.keywordError={message:({keyword:t})=>(0,pe.str)`must pass "${t}" keyword validation`};ot.keyword$DataError={message:({keyword:t,schemaType:e})=>e?(0,pe.str)`"${t}" keyword must be ${e} ($data)`:(0,pe.str)`"${t}" keyword is invalid ($data)`};function v1(t,e=ot.keywordError,r,n){let{it:s}=t,{gen:o,compositeRule:i,allErrors:a}=s,c=BS(t,e,r);n??(i||a)?HS(o,c):ZS(s,(0,pe._)`[${c}]`)}ot.reportError=v1;function b1(t,e=ot.keywordError,r){let{it:n}=t,{gen:s,compositeRule:o,allErrors:i}=n,a=BS(t,e,r);HS(s,a),o||i||ZS(n,mt.default.vErrors)}ot.reportExtraError=b1;function S1(t,e){t.assign(mt.default.errors,e),t.if((0,pe._)`${mt.default.vErrors} !== null`,()=>t.if(e,()=>t.assign((0,pe._)`${mt.default.vErrors}.length`,e),()=>t.assign(mt.default.vErrors,null)))}ot.resetErrorsCount=S1;function k1({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,mt.default.errors,a=>{t.const(i,(0,pe._)`${mt.default.vErrors}[${a}]`),t.if((0,pe._)`${i}.instancePath === undefined`,()=>t.assign((0,pe._)`${i}.instancePath`,(0,pe.strConcat)(mt.default.instancePath,o.errorPath))),t.assign((0,pe._)`${i}.schemaPath`,(0,pe.str)`${o.errSchemaPath}/${e}`),o.opts.verbose&&(t.assign((0,pe._)`${i}.schema`,r),t.assign((0,pe._)`${i}.data`,n))})}ot.extendErrors=k1;function HS(t,e){let r=t.const("err",e);t.if((0,pe._)`${mt.default.vErrors} === null`,()=>t.assign(mt.default.vErrors,(0,pe._)`[${r}]`),(0,pe._)`${mt.default.vErrors}.push(${r})`),t.code((0,pe._)`${mt.default.errors}++`)}function ZS(t,e){let{gen:r,validateName:n,schemaEnv:s}=t;s.$async?r.throw((0,pe._)`new ${t.ValidationError}(${e})`):(r.assign((0,pe._)`${n}.errors`,e),r.return(!1))}var rs={keyword:new pe.Name("keyword"),schemaPath:new pe.Name("schemaPath"),params:new pe.Name("params"),propertyName:new pe.Name("propertyName"),message:new pe.Name("message"),schema:new pe.Name("schema"),parentSchema:new pe.Name("parentSchema")};function BS(t,e,r){let{createErrors:n}=t.it;return n===!1?(0,pe._)`{}`:w1(t,e,r)}function w1(t,e,r={}){let{gen:n,it:s}=t,o=[E1(s,r),$1(t,r)];return T1(t,e,o),n.object(...o)}function E1({errorPath:t},{instancePath:e}){let r=e?(0,pe.str)`${t}${(0,qc.getErrorPath)(e,qc.Type.Str)}`:t;return[mt.default.instancePath,(0,pe.strConcat)(mt.default.instancePath,r)]}function $1({keyword:t,it:{errSchemaPath:e}},{schemaPath:r,parentSchema:n}){let s=n?e:(0,pe.str)`${e}/${t}`;return r&&(s=(0,pe.str)`${s}${(0,qc.getErrorPath)(r,qc.Type.Str)}`),[rs.schemaPath,s]}function T1(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([rs.keyword,s],[rs.params,typeof e=="function"?e(t):e||(0,pe._)`{}`]),c.messages&&n.push([rs.message,typeof r=="function"?r(t):r]),c.verbose&&n.push([rs.schema,i],[rs.parentSchema,(0,pe._)`${d}${l}`],[mt.default.data,o]),u&&n.push([rs.propertyName,u])}});var VS=N(Ks=>{"use strict";Object.defineProperty(Ks,"__esModule",{value:!0});Ks.boolOrEmptySchema=Ks.topBoolOrEmptySchema=void 0;var P1=_i(),R1=te(),C1=Mr(),O1={message:"boolean schema is false"};function I1(t){let{gen:e,schema:r,validateName:n}=t;r===!1?qS(t,!1):typeof r=="object"&&r.$async===!0?e.return(C1.default.data):(e.assign((0,R1._)`${n}.errors`,null),e.return(!0))}Ks.topBoolOrEmptySchema=I1;function A1(t,e){let{gen:r,schema:n}=t;n===!1?(r.var(e,!1),qS(t)):r.var(e,!0)}Ks.boolOrEmptySchema=A1;function qS(t,e){let{gen:r,data:n}=t,s={gen:r,keyword:"false schema",data:n,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:t};(0,P1.reportError)(s,O1,void 0,e)}});var ah=N(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.getRules=Js.isJSONType=void 0;var N1=["string","number","integer","boolean","null","object","array"],D1=new Set(N1);function M1(t){return typeof t=="string"&&D1.has(t)}Js.isJSONType=M1;function j1(){let t={number:{type:"number",rules:[]},string:{type:"string",rules:[]},array:{type:"array",rules:[]},object:{type:"object",rules:[]}};return{types:{...t,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},t.number,t.string,t.array,t.object],post:{rules:[]},all:{},keywords:{}}}Js.getRules=j1});var ch=N(ln=>{"use strict";Object.defineProperty(ln,"__esModule",{value:!0});ln.shouldUseRule=ln.shouldUseGroup=ln.schemaHasRulesForType=void 0;function z1({schema:t,self:e},r){let n=e.RULES.types[r];return n&&n!==!0&&WS(t,n)}ln.schemaHasRulesForType=z1;function WS(t,e){return e.rules.some(r=>GS(t,r))}ln.shouldUseGroup=WS;function GS(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))}ln.shouldUseRule=GS});var xi=N(it=>{"use strict";Object.defineProperty(it,"__esModule",{value:!0});it.reportTypeError=it.checkDataTypes=it.checkDataType=it.coerceAndCheckDataType=it.getJSONTypes=it.getSchemaTypes=it.DataType=void 0;var L1=ah(),F1=ch(),U1=_i(),Q=te(),KS=de(),Ys;(function(t){t[t.Correct=0]="Correct",t[t.Wrong=1]="Wrong"})(Ys||(it.DataType=Ys={}));function H1(t){let e=JS(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}it.getSchemaTypes=H1;function JS(t){let e=Array.isArray(t)?t:t?[t]:[];if(e.every(L1.isJSONType))return e;throw new Error("type must be JSONType or JSONType[]: "+e.join(","))}it.getJSONTypes=JS;function Z1(t,e){let{gen:r,data:n,opts:s}=t,o=B1(e,s.coerceTypes),i=e.length>0&&!(o.length===0&&e.length===1&&(0,F1.schemaHasRulesForType)(t,e[0]));if(i){let a=lh(e,n,s.strictNumbers,Ys.Wrong);r.if(a,()=>{o.length?q1(t,e,o):dh(t)})}return i}it.coerceAndCheckDataType=Z1;var YS=new Set(["string","number","integer","boolean","null"]);function B1(t,e){return e?t.filter(r=>YS.has(r)||e==="array"&&r==="array"):[]}function q1(t,e,r){let{gen:n,data:s,opts:o}=t,i=n.let("dataType",(0,Q._)`typeof ${s}`),a=n.let("coerced",(0,Q._)`undefined`);o.coerceTypes==="array"&&n.if((0,Q._)`${i} == 'object' && Array.isArray(${s}) && ${s}.length == 1`,()=>n.assign(s,(0,Q._)`${s}[0]`).assign(i,(0,Q._)`typeof ${s}`).if(lh(e,s,o.strictNumbers),()=>n.assign(a,s))),n.if((0,Q._)`${a} !== undefined`);for(let u of r)(YS.has(u)||u==="array"&&o.coerceTypes==="array")&&c(u);n.else(),dh(t),n.endIf(),n.if((0,Q._)`${a} !== undefined`,()=>{n.assign(s,a),V1(t,a)});function c(u){switch(u){case"string":n.elseIf((0,Q._)`${i} == "number" || ${i} == "boolean"`).assign(a,(0,Q._)`"" + ${s}`).elseIf((0,Q._)`${s} === null`).assign(a,(0,Q._)`""`);return;case"number":n.elseIf((0,Q._)`${i} == "boolean" || ${s} === null
66
+ || (${i} == "string" && ${s} && ${s} == +${s})`).assign(a,(0,Q._)`+${s}`);return;case"integer":n.elseIf((0,Q._)`${i} === "boolean" || ${s} === null
67
+ || (${i} === "string" && ${s} && ${s} == +${s} && !(${s} % 1))`).assign(a,(0,Q._)`+${s}`);return;case"boolean":n.elseIf((0,Q._)`${s} === "false" || ${s} === 0 || ${s} === null`).assign(a,!1).elseIf((0,Q._)`${s} === "true" || ${s} === 1`).assign(a,!0);return;case"null":n.elseIf((0,Q._)`${s} === "" || ${s} === 0 || ${s} === false`),n.assign(a,null);return;case"array":n.elseIf((0,Q._)`${i} === "string" || ${i} === "number"
68
+ || ${i} === "boolean" || ${s} === null`).assign(a,(0,Q._)`[${s}]`)}}}function V1({gen:t,parentData:e,parentDataProperty:r},n){t.if((0,Q._)`${e} !== undefined`,()=>t.assign((0,Q._)`${e}[${r}]`,n))}function uh(t,e,r,n=Ys.Correct){let s=n===Ys.Correct?Q.operators.EQ:Q.operators.NEQ,o;switch(t){case"null":return(0,Q._)`${e} ${s} null`;case"array":o=(0,Q._)`Array.isArray(${e})`;break;case"object":o=(0,Q._)`${e} && typeof ${e} == "object" && !Array.isArray(${e})`;break;case"integer":o=i((0,Q._)`!(${e} % 1) && !isNaN(${e})`);break;case"number":o=i();break;default:return(0,Q._)`typeof ${e} ${s} ${t}`}return n===Ys.Correct?o:(0,Q.not)(o);function i(a=Q.nil){return(0,Q.and)((0,Q._)`typeof ${e} == "number"`,a,r?(0,Q._)`isFinite(${e})`:Q.nil)}}it.checkDataType=uh;function lh(t,e,r,n){if(t.length===1)return uh(t[0],e,r,n);let s,o=(0,KS.toHash)(t);if(o.array&&o.object){let i=(0,Q._)`typeof ${e} != "object"`;s=o.null?i:(0,Q._)`!${e} || ${i}`,delete o.null,delete o.array,delete o.object}else s=Q.nil;o.number&&delete o.integer;for(let i in o)s=(0,Q.and)(s,uh(i,e,r,n));return s}it.checkDataTypes=lh;var W1={message:({schema:t})=>`must be ${t}`,params:({schema:t,schemaValue:e})=>typeof t=="string"?(0,Q._)`{type: ${t}}`:(0,Q._)`{type: ${e}}`};function dh(t){let e=G1(t);(0,U1.reportError)(e,W1)}it.reportTypeError=dh;function G1(t){let{gen:e,data:r,schema:n}=t,s=(0,KS.schemaRefOrVal)(t,n,"type");return{gen:e,keyword:"type",data:r,schema:n.type,schemaCode:s,schemaValue:s,parentSchema:n,params:{},it:t}}});var QS=N(Vc=>{"use strict";Object.defineProperty(Vc,"__esModule",{value:!0});Vc.assignDefaults=void 0;var Xs=te(),K1=de();function J1(t,e){let{properties:r,items:n}=t.schema;if(e==="object"&&r)for(let s in r)XS(t,s,r[s].default);else e==="array"&&Array.isArray(n)&&n.forEach((s,o)=>XS(t,o,s.default))}Vc.assignDefaults=J1;function XS(t,e,r){let{gen:n,compositeRule:s,data:o,opts:i}=t;if(r===void 0)return;let a=(0,Xs._)`${o}${(0,Xs.getProperty)(e)}`;if(s){(0,K1.checkStrictMode)(t,`default is ignored for: ${a}`);return}let c=(0,Xs._)`${a} === undefined`;i.useDefaults==="empty"&&(c=(0,Xs._)`${c} || ${a} === null || ${a} === ""`),n.if(c,(0,Xs._)`${a} = ${(0,Xs.stringify)(r)}`)}});var Gt=N(xe=>{"use strict";Object.defineProperty(xe,"__esModule",{value:!0});xe.validateUnion=xe.validateArray=xe.usePattern=xe.callValidateCode=xe.schemaProperties=xe.allSchemaProperties=xe.noPropertyInData=xe.propertyInData=xe.isOwnProperty=xe.hasPropFunc=xe.reportMissingProp=xe.checkMissingProp=xe.checkReportMissingProp=void 0;var Pe=te(),ph=de(),dn=Mr(),Y1=de();function X1(t,e){let{gen:r,data:n,it:s}=t;r.if(fh(r,n,e,s.opts.ownProperties),()=>{t.setParams({missingProperty:(0,Pe._)`${e}`},!0),t.error()})}xe.checkReportMissingProp=X1;function Q1({gen:t,data:e,it:{opts:r}},n,s){return(0,Pe.or)(...n.map(o=>(0,Pe.and)(fh(t,e,o,r.ownProperties),(0,Pe._)`${s} = ${o}`)))}xe.checkMissingProp=Q1;function eN(t,e){t.setParams({missingProperty:e},!0),t.error()}xe.reportMissingProp=eN;function ek(t){return t.scopeValue("func",{ref:Object.prototype.hasOwnProperty,code:(0,Pe._)`Object.prototype.hasOwnProperty`})}xe.hasPropFunc=ek;function mh(t,e,r){return(0,Pe._)`${ek(t)}.call(${e}, ${r})`}xe.isOwnProperty=mh;function tN(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} !== undefined`;return n?(0,Pe._)`${s} && ${mh(t,e,r)}`:s}xe.propertyInData=tN;function fh(t,e,r,n){let s=(0,Pe._)`${e}${(0,Pe.getProperty)(r)} === undefined`;return n?(0,Pe.or)(s,(0,Pe.not)(mh(t,e,r))):s}xe.noPropertyInData=fh;function tk(t){return t?Object.keys(t).filter(e=>e!=="__proto__"):[]}xe.allSchemaProperties=tk;function rN(t,e){return tk(e).filter(r=>!(0,ph.alwaysValidSchema)(t,e[r]))}xe.schemaProperties=rN;function nN({schemaCode:t,data:e,it:{gen:r,topSchemaRef:n,schemaPath:s,errorPath:o},it:i},a,c,u){let d=u?(0,Pe._)`${t}, ${e}, ${n}${s}`:e,l=[[dn.default.instancePath,(0,Pe.strConcat)(dn.default.instancePath,o)],[dn.default.parentData,i.parentData],[dn.default.parentDataProperty,i.parentDataProperty],[dn.default.rootData,dn.default.rootData]];i.opts.dynamicRef&&l.push([dn.default.dynamicAnchors,dn.default.dynamicAnchors]);let m=(0,Pe._)`${d}, ${r.object(...l)}`;return c!==Pe.nil?(0,Pe._)`${a}.call(${c}, ${m})`:(0,Pe._)`${a}(${m})`}xe.callValidateCode=nN;var sN=(0,Pe._)`new RegExp`;function oN({gen:t,it:{opts:e}},r){let n=e.unicodeRegExp?"u":"",{regExp:s}=e.code,o=s(r,n);return t.scopeValue("pattern",{key:o.toString(),ref:o,code:(0,Pe._)`${s.code==="new RegExp"?sN:(0,Y1.useFunc)(t,s)}(${r}, ${n})`})}xe.usePattern=oN;function iN(t){let{gen:e,data:r,keyword:n,it:s}=t,o=e.name("valid");if(s.allErrors){let a=e.let("valid",!0);return i(()=>e.assign(a,!1)),a}return e.var(o,!0),i(()=>e.break()),o;function i(a){let c=e.const("len",(0,Pe._)`${r}.length`);e.forRange("i",0,c,u=>{t.subschema({keyword:n,dataProp:u,dataPropType:ph.Type.Num},o),e.if((0,Pe.not)(o),a)})}}xe.validateArray=iN;function aN(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,ph.alwaysValidSchema)(s,c))&&!s.opts.unevaluated)return;let i=e.let("valid",!1),a=e.name("_valid");e.block(()=>r.forEach((c,u)=>{let d=t.subschema({keyword:n,schemaProp:u,compositeRule:!0},a);e.assign(i,(0,Pe._)`${i} || ${a}`),t.mergeValidEvaluated(d,a)||e.if((0,Pe.not)(i))})),t.result(i,()=>t.reset(),()=>t.error(!0))}xe.validateUnion=aN});var sk=N(Sr=>{"use strict";Object.defineProperty(Sr,"__esModule",{value:!0});Sr.validateKeywordUsage=Sr.validSchemaType=Sr.funcKeywordCode=Sr.macroKeywordCode=void 0;var ft=te(),ns=Mr(),cN=Gt(),uN=_i();function lN(t,e){let{gen:r,keyword:n,schema:s,parentSchema:o,it:i}=t,a=e.macro.call(i.self,s,o,i),c=nk(r,n,a);i.opts.validateSchema!==!1&&i.self.validateSchema(a,!0);let u=r.name("valid");t.subschema({schema:a,schemaPath:ft.nil,errSchemaPath:`${i.errSchemaPath}/${n}`,topSchemaRef:c,compositeRule:!0},u),t.pass(u,()=>t.error(!0))}Sr.macroKeywordCode=lN;function dN(t,e){var r;let{gen:n,keyword:s,schema:o,parentSchema:i,$data:a,it:c}=t;mN(c,e);let u=!a&&e.compile?e.compile.call(c.self,o,i,c):e.validate,d=nk(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)h(),e.modifying&&rk(t),g(()=>t.error());else{let y=e.async?f():p();e.modifying&&rk(t),g(()=>pN(t,y))}}function f(){let y=n.let("ruleErrs",null);return n.try(()=>h((0,ft._)`await `),_=>n.assign(l,!1).if((0,ft._)`${_} instanceof ${c.ValidationError}`,()=>n.assign(y,(0,ft._)`${_}.errors`),()=>n.throw(_))),y}function p(){let y=(0,ft._)`${d}.errors`;return n.assign(y,null),h(ft.nil),y}function h(y=e.async?(0,ft._)`await `:ft.nil){let _=c.opts.passContext?ns.default.this:ns.default.self,x=!("compile"in e&&!a||e.schema===!1);n.assign(l,(0,ft._)`${y}${(0,cN.callValidateCode)(t,d,_,x)}`,e.modifying)}function g(y){var _;n.if((0,ft.not)((_=e.valid)!==null&&_!==void 0?_:l),y)}}Sr.funcKeywordCode=dN;function rk(t){let{gen:e,data:r,it:n}=t;e.if(n.parentData,()=>e.assign(r,(0,ft._)`${n.parentData}[${n.parentDataProperty}]`))}function pN(t,e){let{gen:r}=t;r.if((0,ft._)`Array.isArray(${e})`,()=>{r.assign(ns.default.vErrors,(0,ft._)`${ns.default.vErrors} === null ? ${e} : ${ns.default.vErrors}.concat(${e})`).assign(ns.default.errors,(0,ft._)`${ns.default.vErrors}.length`),(0,uN.extendErrors)(t)},()=>t.error())}function mN({schemaEnv:t},e){if(e.async&&!t.$async)throw new Error("async keyword in sync schema")}function nk(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,ft.stringify)(r)})}function fN(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")}Sr.validSchemaType=fN;function hN({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)}}Sr.validateKeywordUsage=hN});var ik=N(pn=>{"use strict";Object.defineProperty(pn,"__esModule",{value:!0});pn.extendSubschemaMode=pn.extendSubschemaData=pn.getSubschema=void 0;var kr=te(),ok=de();function gN(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,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}`,errSchemaPath:`${t.errSchemaPath}/${e}`}:{schema:a[r],schemaPath:(0,kr._)`${t.schemaPath}${(0,kr.getProperty)(e)}${(0,kr.getProperty)(r)}`,errSchemaPath:`${t.errSchemaPath}/${e}/${(0,ok.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')}pn.getSubschema=gN;function yN(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,kr._)`${e.data}${(0,kr.getProperty)(r)}`,!0);c(m),t.errorPath=(0,kr.str)`${u}${(0,ok.getErrorPath)(r,n,l.jsPropertySyntax)}`,t.parentDataProperty=(0,kr._)`${r}`,t.dataPathArr=[...d,t.parentDataProperty]}if(s!==void 0){let u=s instanceof kr.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]}}pn.extendSubschemaData=yN;function _N(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}pn.extendSubschemaMode=_N});var hh=N((z3,ak)=>{"use strict";ak.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 uk=N((L3,ck)=>{"use strict";var mn=ck.exports=function(t,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var n=typeof r=="function"?r:r.pre||function(){},s=r.post||function(){};Wc(e,n,s,t,"",t)};mn.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0};mn.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};mn.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};mn.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 Wc(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 mn.arrayKeywords)for(var m=0;m<l.length;m++)Wc(t,e,r,l[m],s+"/"+d+"/"+m,o,s,d,n,m)}else if(d in mn.propsKeywords){if(l&&typeof l=="object")for(var f in l)Wc(t,e,r,l[f],s+"/"+d+"/"+xN(f),o,s,d,n,f)}else(d in mn.keywords||t.allKeys&&!(d in mn.skipKeywords))&&Wc(t,e,r,l,s+"/"+d,o,s,d,n)}r(n,s,o,i,a,c,u)}}function xN(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}});var vi=N(wt=>{"use strict";Object.defineProperty(wt,"__esModule",{value:!0});wt.getSchemaRefs=wt.resolveUrl=wt.normalizeId=wt._getFullPath=wt.getFullPath=wt.inlineRef=void 0;var vN=de(),bN=hh(),SN=uk(),kN=new Set(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum","const"]);function wN(t,e=!0){return typeof t=="boolean"?!0:e===!0?!gh(t):e?lk(t)<=e:!1}wt.inlineRef=wN;var EN=new Set(["$ref","$recursiveRef","$recursiveAnchor","$dynamicRef","$dynamicAnchor"]);function gh(t){for(let e in t){if(EN.has(e))return!0;let r=t[e];if(Array.isArray(r)&&r.some(gh)||typeof r=="object"&&gh(r))return!0}return!1}function lk(t){let e=0;for(let r in t){if(r==="$ref")return 1/0;if(e++,!kN.has(r)&&(typeof t[r]=="object"&&(0,vN.eachItem)(t[r],n=>e+=lk(n)),e===1/0))return 1/0}return e}function dk(t,e="",r){r!==!1&&(e=Qs(e));let n=t.parse(e);return pk(t,n)}wt.getFullPath=dk;function pk(t,e){return t.serialize(e).split("#")[0]+"#"}wt._getFullPath=pk;var $N=/#\/?$/;function Qs(t){return t?t.replace($N,""):""}wt.normalizeId=Qs;function TN(t,e,r){return r=Qs(r),t.resolve(e,r)}wt.resolveUrl=TN;var PN=/^[a-z_][-a-z0-9._]*$/i;function RN(t,e){if(typeof t=="boolean")return{};let{schemaId:r,uriResolver:n}=this.opts,s=Qs(t[r]||e),o={"":s},i=dk(n,s,!1),a={},c=new Set;return SN(t,{allKeys:!0},(l,m,f,p)=>{if(p===void 0)return;let h=i+m,g=o[p];typeof l[r]=="string"&&(g=y.call(this,l[r])),_.call(this,l.$anchor),_.call(this,l.$dynamicAnchor),o[m]=g;function y(x){let S=this.opts.uriResolver.resolve;if(x=Qs(g?S(g,x):x),c.has(x))throw d(x);c.add(x);let w=this.refs[x];return typeof w=="string"&&(w=this.refs[w]),typeof w=="object"?u(l,w.schema,x):x!==Qs(h)&&(x[0]==="#"?(u(l,a[x],x),a[x]=l):this.refs[x]=h),x}function _(x){if(typeof x=="string"){if(!PN.test(x))throw new Error(`invalid anchor "${x}"`);y.call(this,`#${x}`)}}}),a;function u(l,m,f){if(m!==void 0&&!bN(l,m))throw d(f)}function d(l){return new Error(`reference "${l}" resolves to more than one schema`)}}wt.getSchemaRefs=RN});var ki=N(fn=>{"use strict";Object.defineProperty(fn,"__esModule",{value:!0});fn.getData=fn.KeywordCxt=fn.validateFunctionCode=void 0;var yk=VS(),mk=xi(),_h=ch(),Gc=xi(),CN=QS(),Si=sk(),yh=ik(),Z=te(),Y=Mr(),ON=vi(),jr=de(),bi=_i();function IN(t){if(vk(t)&&(bk(t),xk(t))){DN(t);return}_k(t,()=>(0,yk.topBoolOrEmptySchema)(t))}fn.validateFunctionCode=IN;function _k({gen:t,validateName:e,schema:r,schemaEnv:n,opts:s},o){s.code.es5?t.func(e,(0,Z._)`${Y.default.data}, ${Y.default.valCxt}`,n.$async,()=>{t.code((0,Z._)`"use strict"; ${fk(r,s)}`),NN(t,s),t.code(o)}):t.func(e,(0,Z._)`${Y.default.data}, ${AN(s)}`,n.$async,()=>t.code(fk(r,s)).code(o))}function AN(t){return(0,Z._)`{${Y.default.instancePath}="", ${Y.default.parentData}, ${Y.default.parentDataProperty}, ${Y.default.rootData}=${Y.default.data}${t.dynamicRef?(0,Z._)`, ${Y.default.dynamicAnchors}={}`:Z.nil}}={}`}function NN(t,e){t.if(Y.default.valCxt,()=>{t.var(Y.default.instancePath,(0,Z._)`${Y.default.valCxt}.${Y.default.instancePath}`),t.var(Y.default.parentData,(0,Z._)`${Y.default.valCxt}.${Y.default.parentData}`),t.var(Y.default.parentDataProperty,(0,Z._)`${Y.default.valCxt}.${Y.default.parentDataProperty}`),t.var(Y.default.rootData,(0,Z._)`${Y.default.valCxt}.${Y.default.rootData}`),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,Z._)`${Y.default.valCxt}.${Y.default.dynamicAnchors}`)},()=>{t.var(Y.default.instancePath,(0,Z._)`""`),t.var(Y.default.parentData,(0,Z._)`undefined`),t.var(Y.default.parentDataProperty,(0,Z._)`undefined`),t.var(Y.default.rootData,Y.default.data),e.dynamicRef&&t.var(Y.default.dynamicAnchors,(0,Z._)`{}`)})}function DN(t){let{schema:e,opts:r,gen:n}=t;_k(t,()=>{r.$comment&&e.$comment&&kk(t),FN(t),n.let(Y.default.vErrors,null),n.let(Y.default.errors,0),r.unevaluated&&MN(t),Sk(t),ZN(t)})}function MN(t){let{gen:e,validateName:r}=t;t.evaluated=e.const("evaluated",(0,Z._)`${r}.evaluated`),e.if((0,Z._)`${t.evaluated}.dynamicProps`,()=>e.assign((0,Z._)`${t.evaluated}.props`,(0,Z._)`undefined`)),e.if((0,Z._)`${t.evaluated}.dynamicItems`,()=>e.assign((0,Z._)`${t.evaluated}.items`,(0,Z._)`undefined`))}function fk(t,e){let r=typeof t=="object"&&t[e.schemaId];return r&&(e.code.source||e.code.process)?(0,Z._)`/*# sourceURL=${r} */`:Z.nil}function jN(t,e){if(vk(t)&&(bk(t),xk(t))){zN(t,e);return}(0,yk.boolOrEmptySchema)(t,e)}function xk({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 vk(t){return typeof t.schema!="boolean"}function zN(t,e){let{schema:r,gen:n,opts:s}=t;s.$comment&&r.$comment&&kk(t),UN(t),HN(t);let o=n.const("_errs",Y.default.errors);Sk(t,o),n.var(e,(0,Z._)`${o} === ${Y.default.errors}`)}function bk(t){(0,jr.checkUnknownRules)(t),LN(t)}function Sk(t,e){if(t.opts.jtd)return hk(t,[],!1,e);let r=(0,mk.getSchemaTypes)(t.schema),n=(0,mk.coerceAndCheckDataType)(t,r);hk(t,r,!n,e)}function LN(t){let{schema:e,errSchemaPath:r,opts:n,self:s}=t;e.$ref&&n.ignoreKeywordsWithRef&&(0,jr.schemaHasRulesButRef)(e,s.RULES)&&s.logger.warn(`$ref: keywords ignored in schema at path "${r}"`)}function FN(t){let{schema:e,opts:r}=t;e.default!==void 0&&r.useDefaults&&r.strictSchema&&(0,jr.checkStrictMode)(t,"default is ignored in the schema root")}function UN(t){let e=t.schema[t.opts.schemaId];e&&(t.baseId=(0,ON.resolveUrl)(t.opts.uriResolver,t.baseId,e))}function HN(t){if(t.schema.$async&&!t.schemaEnv.$async)throw new Error("async schema in sync schema")}function kk({gen:t,schemaEnv:e,schema:r,errSchemaPath:n,opts:s}){let o=r.$comment;if(s.$comment===!0)t.code((0,Z._)`${Y.default.self}.logger.log(${o})`);else if(typeof s.$comment=="function"){let i=(0,Z.str)`${n}/$comment`,a=t.scopeValue("root",{ref:e.root});t.code((0,Z._)`${Y.default.self}.opts.$comment(${o}, ${i}, ${a}.schema)`)}}function ZN(t){let{gen:e,schemaEnv:r,validateName:n,ValidationError:s,opts:o}=t;r.$async?e.if((0,Z._)`${Y.default.errors} === 0`,()=>e.return(Y.default.data),()=>e.throw((0,Z._)`new ${s}(${Y.default.vErrors})`)):(e.assign((0,Z._)`${n}.errors`,Y.default.vErrors),o.unevaluated&&BN(t),e.return((0,Z._)`${Y.default.errors} === 0`))}function BN({gen:t,evaluated:e,props:r,items:n}){r instanceof Z.Name&&t.assign((0,Z._)`${e}.props`,r),n instanceof Z.Name&&t.assign((0,Z._)`${e}.items`,n)}function hk(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,jr.schemaHasRulesButRef)(o,d))){s.block(()=>Ek(t,"$ref",d.all.$ref.definition));return}c.jtd||qN(t,e),s.block(()=>{for(let m of d.rules)l(m);l(d.post)});function l(m){(0,_h.shouldUseGroup)(o,m)&&(m.type?(s.if((0,Gc.checkDataType)(m.type,i,c.strictNumbers)),gk(t,m),e.length===1&&e[0]===m.type&&r&&(s.else(),(0,Gc.reportTypeError)(t)),s.endIf()):gk(t,m),a||s.if((0,Z._)`${Y.default.errors} === ${n||0}`))}}function gk(t,e){let{gen:r,schema:n,opts:{useDefaults:s}}=t;s&&(0,CN.assignDefaults)(t,e.type),r.block(()=>{for(let o of e.rules)(0,_h.shouldUseRule)(n,o)&&Ek(t,o.keyword,o.definition,e.type)})}function qN(t,e){t.schemaEnv.meta||!t.opts.strictTypes||(VN(t,e),t.opts.allowUnionTypes||WN(t,e),GN(t,t.dataTypes))}function VN(t,e){if(e.length){if(!t.dataTypes.length){t.dataTypes=e;return}e.forEach(r=>{wk(t.dataTypes,r)||xh(t,`type "${r}" not allowed by context "${t.dataTypes.join(",")}"`)}),JN(t,e)}}function WN(t,e){e.length>1&&!(e.length===2&&e.includes("null"))&&xh(t,"use allowUnionTypes to allow union type keyword")}function GN(t,e){let r=t.self.RULES.all;for(let n in r){let s=r[n];if(typeof s=="object"&&(0,_h.shouldUseRule)(t.schema,s)){let{type:o}=s.definition;o.length&&!o.some(i=>KN(e,i))&&xh(t,`missing type "${o.join(",")}" for keyword "${n}"`)}}}function KN(t,e){return t.includes(e)||e==="number"&&t.includes("integer")}function wk(t,e){return t.includes(e)||e==="integer"&&t.includes("number")}function JN(t,e){let r=[];for(let n of t.dataTypes)wk(e,n)?r.push(n):e.includes("integer")&&n==="number"&&r.push("integer");t.dataTypes=r}function xh(t,e){let r=t.schemaEnv.baseId+t.errSchemaPath;e+=` at "${r}" (strictTypes)`,(0,jr.checkStrictMode)(t,e,t.opts.strictTypes)}var Kc=class{constructor(e,r,n){if((0,Si.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,jr.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",$k(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,Si.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,Z.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,Z.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,Z._)`${r} !== undefined && (${(0,Z.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?bi.reportExtraError:bi.reportError)(this,this.def.error,r)}$dataError(){(0,bi.reportError)(this,this.def.$dataError||bi.keyword$DataError)}reset(){if(this.errsCount===void 0)throw new Error('add "trackErrors" to keyword definition');(0,bi.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=Z.nil){this.gen.block(()=>{this.check$data(e,n),r()})}check$data(e=Z.nil,r=Z.nil){if(!this.$data)return;let{gen:n,schemaCode:s,schemaType:o,def:i}=this;n.if((0,Z.or)((0,Z._)`${s} === undefined`,r)),e!==Z.nil&&n.assign(e,!0),(o.length||i.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==Z.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:r,schemaType:n,def:s,it:o}=this;return(0,Z.or)(i(),a());function i(){if(n.length){if(!(r instanceof Z.Name))throw new Error("ajv implementation error");let c=Array.isArray(n)?n:[n];return(0,Z._)`${(0,Gc.checkDataTypes)(c,r,o.opts.strictNumbers,Gc.DataType.Wrong)}`}return Z.nil}function a(){if(s.validateSchema){let c=e.scopeValue("validate$data",{ref:s.validateSchema});return(0,Z._)`!${c}(${r})`}return Z.nil}}subschema(e,r){let n=(0,yh.getSubschema)(this.it,e);(0,yh.extendSubschemaData)(n,this.it,e),(0,yh.extendSubschemaMode)(n,e);let s={...this.it,...n,items:void 0,props:void 0};return jN(s,r),s}mergeEvaluated(e,r){let{it:n,gen:s}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=jr.mergeEvaluated.props(s,e.props,n.props,r)),n.items!==!0&&e.items!==void 0&&(n.items=jr.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,Z.Name)),!0}};fn.KeywordCxt=Kc;function Ek(t,e,r,n){let s=new Kc(t,r,e);"code"in r?r.code(s,n):s.$data&&r.validate?(0,Si.funcKeywordCode)(s,r):"macro"in r?(0,Si.macroKeywordCode)(s,r):(r.compile||r.validate)&&(0,Si.funcKeywordCode)(s,r)}var YN=/^\/(?:[^~]|~0|~1)*$/,XN=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function $k(t,{dataLevel:e,dataNames:r,dataPathArr:n}){let s,o;if(t==="")return Y.default.rootData;if(t[0]==="/"){if(!YN.test(t))throw new Error(`Invalid JSON-pointer: ${t}`);s=t,o=Y.default.rootData}else{let u=XN.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,Z._)`${o}${(0,Z.getProperty)((0,jr.unescapeJsonPointer)(u))}`,i=(0,Z._)`${i} && ${o}`);return i;function c(u,d){return`Cannot access ${u} ${d} levels up, current level is ${e}`}}fn.getData=$k});var Jc=N(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var vh=class extends Error{constructor(e){super("validation failed"),this.errors=e,this.ajv=this.validation=!0}};bh.default=vh});var wi=N(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});var Sh=vi(),kh=class extends Error{constructor(e,r,n,s){super(s||`can't resolve reference ${n} from id ${r}`),this.missingRef=(0,Sh.resolveUrl)(e,r,n),this.missingSchema=(0,Sh.normalizeId)((0,Sh.getFullPath)(e,this.missingRef))}};wh.default=kh});var Xc=N(Kt=>{"use strict";Object.defineProperty(Kt,"__esModule",{value:!0});Kt.resolveSchema=Kt.getCompilingSchema=Kt.resolveRef=Kt.compileSchema=Kt.SchemaEnv=void 0;var ar=te(),QN=Jc(),ss=Mr(),cr=vi(),Tk=de(),eD=ki(),eo=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,cr.normalizeId)(n?.[e.schemaId||"$id"]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=n?.$async,this.refs={}}};Kt.SchemaEnv=eo;function $h(t){let e=Pk.call(this,t);if(e)return e;let r=(0,cr.getFullPath)(this.opts.uriResolver,t.root.baseId),{es5:n,lines:s}=this.opts.code,{ownProperties:o}=this.opts,i=new ar.CodeGen(this.scope,{es5:n,lines:s,ownProperties:o}),a;t.$async&&(a=i.scopeValue("Error",{ref:QN.default,code:(0,ar._)`require("ajv/dist/runtime/validation_error").default`}));let c=i.scopeName("validate");t.validateName=c;let u={gen:i,allErrors:this.opts.allErrors,data:ss.default.data,parentData:ss.default.parentData,parentDataProperty:ss.default.parentDataProperty,dataNames:[ss.default.data],dataPathArr:[ar.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:i.scopeValue("schema",this.opts.code.source===!0?{ref:t.schema,code:(0,ar.stringify)(t.schema)}:{ref:t.schema}),validateName:c,ValidationError:a,schema:t.schema,schemaEnv:t,rootId:r,baseId:t.baseId||r,schemaPath:ar.nil,errSchemaPath:t.schemaPath||(this.opts.jtd?"":"#"),errorPath:(0,ar._)`""`,opts:this.opts,self:this},d;try{this._compilations.add(t),(0,eD.validateFunctionCode)(u),i.optimize(this.opts.code.optimize);let l=i.toString();d=`${i.scopeRefs(ss.default.scope)}return ${l}`,this.opts.code.process&&(d=this.opts.code.process(d,t));let f=new Function(`${ss.default.self}`,`${ss.default.scope}`,d)(this,this.scope.get());if(this.scope.value(c,{ref:f}),f.errors=null,f.schema=t.schema,f.schemaEnv=t,t.$async&&(f.$async=!0),this.opts.code.source===!0&&(f.source={validateName:c,validateCode:l,scopeValues:i._values}),this.opts.unevaluated){let{props:p,items:h}=u;f.evaluated={props:p instanceof ar.Name?void 0:p,items:h instanceof ar.Name?void 0:h,dynamicProps:p instanceof ar.Name,dynamicItems:h instanceof ar.Name},f.source&&(f.source.evaluated=(0,ar.stringify)(f.evaluated))}return t.validate=f,t}catch(l){throw delete t.validate,delete t.validateName,d&&this.logger.error("Error compiling schema, function code:",d),l}finally{this._compilations.delete(t)}}Kt.compileSchema=$h;function tD(t,e,r){var n;r=(0,cr.resolveUrl)(this.opts.uriResolver,e,r);let s=t.refs[r];if(s)return s;let o=sD.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 eo({schema:i,schemaId:a,root:t,baseId:e}))}if(o!==void 0)return t.refs[r]=rD.call(this,o)}Kt.resolveRef=tD;function rD(t){return(0,cr.inlineRef)(t.schema,this.opts.inlineRefs)?t.schema:t.validate?t:$h.call(this,t)}function Pk(t){for(let e of this._compilations)if(nD(e,t))return e}Kt.getCompilingSchema=Pk;function nD(t,e){return t.schema===e.schema&&t.root===e.root&&t.baseId===e.baseId}function sD(t,e){let r;for(;typeof(r=this.refs[e])=="string";)e=r;return r||this.schemas[e]||Yc.call(this,t,e)}function Yc(t,e){let r=this.opts.uriResolver.parse(e),n=(0,cr._getFullPath)(this.opts.uriResolver,r),s=(0,cr.getFullPath)(this.opts.uriResolver,t.baseId,void 0);if(Object.keys(t.schema).length>0&&n===s)return Eh.call(this,r,t);let o=(0,cr.normalizeId)(n),i=this.refs[o]||this.schemas[o];if(typeof i=="string"){let a=Yc.call(this,t,i);return typeof a?.schema!="object"?void 0:Eh.call(this,r,a)}if(typeof i?.schema=="object"){if(i.validate||$h.call(this,i),o===(0,cr.normalizeId)(e)){let{schema:a}=i,{schemaId:c}=this.opts,u=a[c];return u&&(s=(0,cr.resolveUrl)(this.opts.uriResolver,s,u)),new eo({schema:a,schemaId:c,root:t,baseId:s})}return Eh.call(this,r,i)}}Kt.resolveSchema=Yc;var oD=new Set(["properties","patternProperties","enum","dependencies","definitions"]);function Eh(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,Tk.unescapeFragment)(a)];if(c===void 0)return;r=c;let u=typeof r=="object"&&r[this.opts.schemaId];!oD.has(a)&&u&&(e=(0,cr.resolveUrl)(this.opts.uriResolver,e,u))}let o;if(typeof r!="boolean"&&r.$ref&&!(0,Tk.schemaHasRulesButRef)(r,this.RULES)){let a=(0,cr.resolveUrl)(this.opts.uriResolver,e,r.$ref);o=Yc.call(this,n,a)}let{schemaId:i}=this.opts;if(o=o||new eo({schema:r,schemaId:i,root:n,baseId:e}),o.schema!==o.root.schema)return o}});var Rk=N((q3,iD)=>{iD.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 Ph=N((V3,Ak)=>{"use strict";var aD=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),Ok=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 Th(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 cD=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function Ck(t){return t.length=0,!0}function uD(t,e,r){if(t.length){let n=Th(t);if(n!=="")e.push(n);else return r.error=!0,!1;t.length=0}return!0}function lD(t){let e=0,r={error:!1,address:"",zone:""},n=[],s=[],o=!1,i=!1,a=uD;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=Ck}else{s.push(u);continue}}return s.length&&(a===Ck?r.zone=s.join(""):i?n.push(s.join("")):n.push(Th(s))),r.address=n.join(""),r}function Ik(t){if(dD(t,":")<2)return{host:t,isIPV6:!1};let e=lD(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 dD(t,e){let r=0;for(let n=0;n<t.length;n++)t[n]===e&&r++;return r}function pD(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 mD(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 fD(t){let e=[];if(t.userinfo!==void 0&&(e.push(t.userinfo),e.push("@")),t.host!==void 0){let r=unescape(t.host);if(!Ok(r)){let n=Ik(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}Ak.exports={nonSimpleDomain:cD,recomposeAuthority:fD,normalizeComponentEncoding:mD,removeDotSegments:pD,isIPv4:Ok,isUUID:aD,normalizeIPv6:Ik,stringArrayToHexStripped:Th}});var zk=N((W3,jk)=>{"use strict";var{isUUID:hD}=Ph(),gD=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,yD=["http","https","ws","wss","urn","urn:uuid"];function _D(t){return yD.indexOf(t)!==-1}function Rh(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 Nk(t){return t.host||(t.error=t.error||"HTTP URIs must have a host."),t}function Dk(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 xD(t){return t.secure=Rh(t),t.resourceName=(t.path||"/")+(t.query?"?"+t.query:""),t.path=void 0,t.query=void 0,t}function vD(t){if((t.port===(Rh(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 bD(t,e){if(!t.path)return t.error="URN can not be parsed",t;let r=t.path.match(gD);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=Ch(s);t.path=void 0,o&&(t=o.parse(t,e))}else t.error=t.error||"URN can not be parsed.";return t}function SD(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=Ch(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 kD(t,e){let r=t;return r.uuid=r.nss,r.nss=void 0,!e.tolerant&&(!r.uuid||!hD(r.uuid))&&(r.error=r.error||"UUID is not valid."),r}function wD(t){let e=t;return e.nss=(t.uuid||"").toLowerCase(),e}var Mk={scheme:"http",domainHost:!0,parse:Nk,serialize:Dk},ED={scheme:"https",domainHost:Mk.domainHost,parse:Nk,serialize:Dk},Qc={scheme:"ws",domainHost:!0,parse:xD,serialize:vD},$D={scheme:"wss",domainHost:Qc.domainHost,parse:Qc.parse,serialize:Qc.serialize},TD={scheme:"urn",parse:bD,serialize:SD,skipNormalize:!0},PD={scheme:"urn:uuid",parse:kD,serialize:wD,skipNormalize:!0},eu={http:Mk,https:ED,ws:Qc,wss:$D,urn:TD,"urn:uuid":PD};Object.setPrototypeOf(eu,null);function Ch(t){return t&&(eu[t]||eu[t.toLowerCase()])||void 0}jk.exports={wsIsSecure:Rh,SCHEMES:eu,isValidSchemeName:_D,getSchemeHandler:Ch}});var Uk=N((G3,ru)=>{"use strict";var{normalizeIPv6:RD,removeDotSegments:Ei,recomposeAuthority:CD,normalizeComponentEncoding:tu,isIPv4:OD,nonSimpleDomain:ID}=Ph(),{SCHEMES:AD,getSchemeHandler:Lk}=zk();function ND(t,e){return typeof t=="string"?t=wr(zr(t,e),e):typeof t=="object"&&(t=zr(wr(t,e),e)),t}function DD(t,e,r){let n=r?Object.assign({scheme:"null"},r):{scheme:"null"},s=Fk(zr(t,n),zr(e,n),n,!0);return n.skipEscape=!0,wr(s,n)}function Fk(t,e,r,n){let s={};return n||(t=zr(wr(t,r),r),e=zr(wr(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=Ei(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=Ei(e.path||""),s.query=e.query):(e.path?(e.path[0]==="/"?s.path=Ei(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=Ei(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 MD(t,e,r){return typeof t=="string"?(t=unescape(t),t=wr(tu(zr(t,r),!0),{...r,skipEscape:!0})):typeof t=="object"&&(t=wr(tu(t,!0),{...r,skipEscape:!0})),typeof e=="string"?(e=unescape(e),e=wr(tu(zr(e,r),!0),{...r,skipEscape:!0})):typeof e=="object"&&(e=wr(tu(e,!0),{...r,skipEscape:!0})),t.toLowerCase()===e.toLowerCase()}function wr(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=Lk(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=CD(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=Ei(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 jD=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function zr(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(jD);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(OD(n.host)===!1){let c=RD(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=Lk(r.scheme||n.scheme);if(!r.unicodeSupport&&(!i||!i.unicodeSupport)&&n.host&&(r.domainHost||i&&i.domainHost)&&s===!1&&ID(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 Oh={SCHEMES:AD,normalize:ND,resolve:DD,resolveComponent:Fk,equal:MD,serialize:wr,parse:zr};ru.exports=Oh;ru.exports.default=Oh;ru.exports.fastUri=Oh});var Zk=N(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});var Hk=Uk();Hk.code='require("ajv/dist/runtime/uri").default';Ih.default=Hk});var Yk=N(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.CodeGen=Xe.Name=Xe.nil=Xe.stringify=Xe.str=Xe._=Xe.KeywordCxt=void 0;var zD=ki();Object.defineProperty(Xe,"KeywordCxt",{enumerable:!0,get:function(){return zD.KeywordCxt}});var to=te();Object.defineProperty(Xe,"_",{enumerable:!0,get:function(){return to._}});Object.defineProperty(Xe,"str",{enumerable:!0,get:function(){return to.str}});Object.defineProperty(Xe,"stringify",{enumerable:!0,get:function(){return to.stringify}});Object.defineProperty(Xe,"nil",{enumerable:!0,get:function(){return to.nil}});Object.defineProperty(Xe,"Name",{enumerable:!0,get:function(){return to.Name}});Object.defineProperty(Xe,"CodeGen",{enumerable:!0,get:function(){return to.CodeGen}});var LD=Jc(),Gk=wi(),FD=ah(),$i=Xc(),UD=te(),Ti=vi(),nu=xi(),Nh=de(),Bk=Rk(),HD=Zk(),Kk=(t,e)=>new RegExp(t,e);Kk.code="new RegExp";var ZD=["removeAdditional","useDefaults","coerceTypes"],BD=new Set(["validate","serialize","parse","wrapper","root","schema","keyword","pattern","formats","validate$data","func","obj","Error"]),qD={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."},VD={ignoreKeywordsWithRef:"",jsPropertySyntax:"",unicode:'"minLength"/"maxLength" account for unicode characters by default.'},qk=200;function WD(t){var e,r,n,s,o,i,a,c,u,d,l,m,f,p,h,g,y,_,x,S,w,I,O,C,F;let T=t.strict,R=(e=t.code)===null||e===void 0?void 0:e.optimize,V=R===!0||R===void 0?1:R||0,oe=(n=(r=t.code)===null||r===void 0?void 0:r.regExp)!==null&&n!==void 0?n:Kk,fe=(s=t.uriResolver)!==null&&s!==void 0?s:HD.default;return{strictSchema:(i=(o=t.strictSchema)!==null&&o!==void 0?o:T)!==null&&i!==void 0?i:!0,strictNumbers:(c=(a=t.strictNumbers)!==null&&a!==void 0?a:T)!==null&&c!==void 0?c:!0,strictTypes:(d=(u=t.strictTypes)!==null&&u!==void 0?u:T)!==null&&d!==void 0?d:"log",strictTuples:(m=(l=t.strictTuples)!==null&&l!==void 0?l:T)!==null&&m!==void 0?m:"log",strictRequired:(p=(f=t.strictRequired)!==null&&f!==void 0?f:T)!==null&&p!==void 0?p:!1,code:t.code?{...t.code,optimize:V,regExp:oe}:{optimize:V,regExp:oe},loopRequired:(h=t.loopRequired)!==null&&h!==void 0?h:qk,loopEnum:(g=t.loopEnum)!==null&&g!==void 0?g:qk,meta:(y=t.meta)!==null&&y!==void 0?y:!0,messages:(_=t.messages)!==null&&_!==void 0?_:!0,inlineRefs:(x=t.inlineRefs)!==null&&x!==void 0?x:!0,schemaId:(S=t.schemaId)!==null&&S!==void 0?S:"$id",addUsedSchema:(w=t.addUsedSchema)!==null&&w!==void 0?w:!0,validateSchema:(I=t.validateSchema)!==null&&I!==void 0?I:!0,validateFormats:(O=t.validateFormats)!==null&&O!==void 0?O:!0,unicodeRegExp:(C=t.unicodeRegExp)!==null&&C!==void 0?C:!0,int32range:(F=t.int32range)!==null&&F!==void 0?F:!0,uriResolver:fe}}var Pi=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...WD(e)};let{es5:r,lines:n}=this.opts.code;this.scope=new UD.ValueScope({scope:{},prefixes:BD,es5:r,lines:n}),this.logger=QD(e.logger);let s=e.validateFormats;e.validateFormats=!1,this.RULES=(0,FD.getRules)(),Vk.call(this,qD,e,"NOT SUPPORTED"),Vk.call(this,VD,e,"DEPRECATED","warn"),this._metaOpts=YD.call(this),e.formats&&KD.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&JD.call(this,e.keywords),typeof e.meta=="object"&&this.addMetaSchema(e.meta),GD.call(this),e.validateFormats=s}_addVocabularies(){this.addKeyword("$async")}_addDefaultMetaSchema(){let{$data:e,meta:r,schemaId:n}=this.opts,s=Bk;n==="id"&&(s={...Bk},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 Gk.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,Ti.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=Wk.call(this,e))=="string";)e=r;if(r===void 0){let{schemaId:n}=this.opts,s=new $i.SchemaEnv({schema:{},schemaId:n});if(r=$i.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=Wk.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,Ti.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(tM.call(this,n,r),!r)return(0,Nh.eachItem)(n,o=>Ah.call(this,o)),this;nM.call(this,r);let s={...r,type:(0,nu.getJSONTypes)(r.type),schemaType:(0,nu.getJSONTypes)(r.schemaType)};return(0,Nh.eachItem)(n,s.type.length===0?o=>Ah.call(this,o,s):o=>s.type.forEach(i=>Ah.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]=Jk(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,Ti.normalizeId)(i||n);let u=Ti.getSchemaRefs.call(this,e,n);return c=new $i.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):$i.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{$i.compileSchema.call(this,e)}finally{this.opts=r}}};Pi.ValidationError=LD.default;Pi.MissingRefError=Gk.default;Xe.default=Pi;function Vk(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 Wk(t){return t=(0,Ti.normalizeId)(t),this.schemas[t]||this.refs[t]}function GD(){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 KD(){for(let t in this.opts.formats){let e=this.opts.formats[t];e&&this.addFormat(t,e)}}function JD(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 YD(){let t={...this.opts};for(let e of ZD)delete t[e];return t}var XD={log(){},warn(){},error(){}};function QD(t){if(t===!1)return XD;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 eM=/^[a-z_$][a-z0-9_$:-]*$/i;function tM(t,e){let{RULES:r}=this;if((0,Nh.eachItem)(t,n=>{if(r.keywords[n])throw new Error(`Keyword ${n} is already defined`);if(!eM.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 Ah(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,nu.getJSONTypes)(e.type),schemaType:(0,nu.getJSONTypes)(e.schemaType)}};e.before?rM.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 rM(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 nM(t){let{metaSchema:e}=t;e!==void 0&&(t.$data&&this.opts.$data&&(e=Jk(e)),t.validateSchema=this.compile(e,!0))}var sM={$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"};function Jk(t){return{anyOf:[t,sM]}}});var Xk=N(Dh=>{"use strict";Object.defineProperty(Dh,"__esModule",{value:!0});var oM={keyword:"id",code(){throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID')}};Dh.default=oM});var r0=N(os=>{"use strict";Object.defineProperty(os,"__esModule",{value:!0});os.callRef=os.getValidate=void 0;var iM=wi(),Qk=Gt(),Et=te(),ro=Mr(),e0=Xc(),su=de(),aM={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=e0.resolveRef.call(c,u,s,r);if(d===void 0)throw new iM.default(n.opts.uriResolver,s,r);if(d instanceof e0.SchemaEnv)return m(d);return f(d);function l(){if(o===u)return ou(t,i,o,o.$async);let p=e.scopeValue("root",{ref:u});return ou(t,(0,Et._)`${p}.validate`,u,u.$async)}function m(p){let h=t0(t,p);ou(t,h,p,p.$async)}function f(p){let h=e.scopeValue("schema",a.code.source===!0?{ref:p,code:(0,Et.stringify)(p)}:{ref:p}),g=e.name("valid"),y=t.subschema({schema:p,dataTypes:[],schemaPath:Et.nil,topSchemaRef:h,errSchemaPath:r},g);t.mergeEvaluated(y),t.ok(g)}}};function t0(t,e){let{gen:r}=t;return e.validate?r.scopeValue("validate",{ref:e.validate}):(0,Et._)`${r.scopeValue("wrapper",{ref:e})}.validate`}os.getValidate=t0;function ou(t,e,r,n){let{gen:s,it:o}=t,{allErrors:i,schemaEnv:a,opts:c}=o,u=c.passContext?ro.default.this:Et.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,Et._)`await ${(0,Qk.callValidateCode)(t,e,u)}`),f(e),i||s.assign(p,!0)},h=>{s.if((0,Et._)`!(${h} instanceof ${o.ValidationError})`,()=>s.throw(h)),m(h),i||s.assign(p,!1)}),t.ok(p)}function l(){t.result((0,Qk.callValidateCode)(t,e,u),()=>f(e),()=>m(e))}function m(p){let h=(0,Et._)`${p}.errors`;s.assign(ro.default.vErrors,(0,Et._)`${ro.default.vErrors} === null ? ${h} : ${ro.default.vErrors}.concat(${h})`),s.assign(ro.default.errors,(0,Et._)`${ro.default.vErrors}.length`)}function f(p){var h;if(!o.opts.unevaluated)return;let g=(h=r?.validate)===null||h===void 0?void 0:h.evaluated;if(o.props!==!0)if(g&&!g.dynamicProps)g.props!==void 0&&(o.props=su.mergeEvaluated.props(s,g.props,o.props));else{let y=s.var("props",(0,Et._)`${p}.evaluated.props`);o.props=su.mergeEvaluated.props(s,y,o.props,Et.Name)}if(o.items!==!0)if(g&&!g.dynamicItems)g.items!==void 0&&(o.items=su.mergeEvaluated.items(s,g.items,o.items));else{let y=s.var("items",(0,Et._)`${p}.evaluated.items`);o.items=su.mergeEvaluated.items(s,y,o.items,Et.Name)}}}os.callRef=ou;os.default=aM});var n0=N(Mh=>{"use strict";Object.defineProperty(Mh,"__esModule",{value:!0});var cM=Xk(),uM=r0(),lM=["$schema","$id","$defs","$vocabulary",{keyword:"$comment"},"definitions",cM.default,uM.default];Mh.default=lM});var s0=N(jh=>{"use strict";Object.defineProperty(jh,"__esModule",{value:!0});var iu=te(),hn=iu.operators,au={maximum:{okStr:"<=",ok:hn.LTE,fail:hn.GT},minimum:{okStr:">=",ok:hn.GTE,fail:hn.LT},exclusiveMaximum:{okStr:"<",ok:hn.LT,fail:hn.GTE},exclusiveMinimum:{okStr:">",ok:hn.GT,fail:hn.LTE}},dM={message:({keyword:t,schemaCode:e})=>(0,iu.str)`must be ${au[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,iu._)`{comparison: ${au[t].okStr}, limit: ${e}}`},pM={keyword:Object.keys(au),type:"number",schemaType:"number",$data:!0,error:dM,code(t){let{keyword:e,data:r,schemaCode:n}=t;t.fail$data((0,iu._)`${r} ${au[e].fail} ${n} || isNaN(${r})`)}};jh.default=pM});var o0=N(zh=>{"use strict";Object.defineProperty(zh,"__esModule",{value:!0});var Ri=te(),mM={message:({schemaCode:t})=>(0,Ri.str)`must be multiple of ${t}`,params:({schemaCode:t})=>(0,Ri._)`{multipleOf: ${t}}`},fM={keyword:"multipleOf",type:"number",schemaType:"number",$data:!0,error:mM,code(t){let{gen:e,data:r,schemaCode:n,it:s}=t,o=s.opts.multipleOfPrecision,i=e.let("res"),a=o?(0,Ri._)`Math.abs(Math.round(${i}) - ${i}) > 1e-${o}`:(0,Ri._)`${i} !== parseInt(${i})`;t.fail$data((0,Ri._)`(${n} === 0 || (${i} = ${r}/${n}, ${a}))`)}};zh.default=fM});var a0=N(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});function i0(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}Lh.default=i0;i0.code='require("ajv/dist/runtime/ucs2length").default'});var c0=N(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var is=te(),hM=de(),gM=a0(),yM={message({keyword:t,schemaCode:e}){let r=t==="maxLength"?"more":"fewer";return(0,is.str)`must NOT have ${r} than ${e} characters`},params:({schemaCode:t})=>(0,is._)`{limit: ${t}}`},_M={keyword:["maxLength","minLength"],type:"string",schemaType:"number",$data:!0,error:yM,code(t){let{keyword:e,data:r,schemaCode:n,it:s}=t,o=e==="maxLength"?is.operators.GT:is.operators.LT,i=s.opts.unicode===!1?(0,is._)`${r}.length`:(0,is._)`${(0,hM.useFunc)(t.gen,gM.default)}(${r})`;t.fail$data((0,is._)`${i} ${o} ${n}`)}};Fh.default=_M});var u0=N(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var xM=Gt(),vM=de(),no=te(),bM={message:({schemaCode:t})=>(0,no.str)`must match pattern "${t}"`,params:({schemaCode:t})=>(0,no._)`{pattern: ${t}}`},SM={keyword:"pattern",type:"string",schemaType:"string",$data:!0,error:bM,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,no._)`new RegExp`:(0,vM.useFunc)(e,c),d=e.let("valid");e.try(()=>e.assign(d,(0,no._)`${u}(${o}, ${a}).test(${r})`),()=>e.assign(d,!1)),t.fail$data((0,no._)`!${d}`)}else{let c=(0,xM.usePattern)(t,s);t.fail$data((0,no._)`!${c}.test(${r})`)}}};Uh.default=SM});var l0=N(Hh=>{"use strict";Object.defineProperty(Hh,"__esModule",{value:!0});var Ci=te(),kM={message({keyword:t,schemaCode:e}){let r=t==="maxProperties"?"more":"fewer";return(0,Ci.str)`must NOT have ${r} than ${e} properties`},params:({schemaCode:t})=>(0,Ci._)`{limit: ${t}}`},wM={keyword:["maxProperties","minProperties"],type:"object",schemaType:"number",$data:!0,error:kM,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxProperties"?Ci.operators.GT:Ci.operators.LT;t.fail$data((0,Ci._)`Object.keys(${r}).length ${s} ${n}`)}};Hh.default=wM});var d0=N(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});var Oi=Gt(),Ii=te(),EM=de(),$M={message:({params:{missingProperty:t}})=>(0,Ii.str)`must have required property '${t}'`,params:({params:{missingProperty:t}})=>(0,Ii._)`{missingProperty: ${t}}`},TM={keyword:"required",type:"object",schemaType:"array",$data:!0,error:$M,code(t){let{gen:e,schema:r,schemaCode:n,data:s,$data:o,it:i}=t,{opts:a}=i;if(!o&&r.length===0)return;let c=r.length>=a.loopRequired;if(i.allErrors?u():d(),a.strictRequired){let f=t.parentSchema.properties,{definedProperties:p}=t.it;for(let h of r)if(f?.[h]===void 0&&!p.has(h)){let g=i.schemaEnv.baseId+i.errSchemaPath,y=`required property "${h}" is not defined at "${g}" (strictRequired)`;(0,EM.checkStrictMode)(i,y,i.opts.strictRequired)}}function u(){if(c||o)t.block$data(Ii.nil,l);else for(let f of r)(0,Oi.checkReportMissingProp)(t,f)}function d(){let f=e.let("missing");if(c||o){let p=e.let("valid",!0);t.block$data(p,()=>m(f,p)),t.ok(p)}else e.if((0,Oi.checkMissingProp)(t,r,f)),(0,Oi.reportMissingProp)(t,f),e.else()}function l(){e.forOf("prop",n,f=>{t.setParams({missingProperty:f}),e.if((0,Oi.noPropertyInData)(e,s,f,a.ownProperties),()=>t.error())})}function m(f,p){t.setParams({missingProperty:f}),e.forOf(f,n,()=>{e.assign(p,(0,Oi.propertyInData)(e,s,f,a.ownProperties)),e.if((0,Ii.not)(p),()=>{t.error(),e.break()})},Ii.nil)}}};Zh.default=TM});var p0=N(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var Ai=te(),PM={message({keyword:t,schemaCode:e}){let r=t==="maxItems"?"more":"fewer";return(0,Ai.str)`must NOT have ${r} than ${e} items`},params:({schemaCode:t})=>(0,Ai._)`{limit: ${t}}`},RM={keyword:["maxItems","minItems"],type:"array",schemaType:"number",$data:!0,error:PM,code(t){let{keyword:e,data:r,schemaCode:n}=t,s=e==="maxItems"?Ai.operators.GT:Ai.operators.LT;t.fail$data((0,Ai._)`${r}.length ${s} ${n}`)}};Bh.default=RM});var cu=N(qh=>{"use strict";Object.defineProperty(qh,"__esModule",{value:!0});var m0=hh();m0.code='require("ajv/dist/runtime/equal").default';qh.default=m0});var f0=N(Wh=>{"use strict";Object.defineProperty(Wh,"__esModule",{value:!0});var Vh=xi(),Qe=te(),CM=de(),OM=cu(),IM={message:({params:{i:t,j:e}})=>(0,Qe.str)`must NOT have duplicate items (items ## ${e} and ${t} are identical)`,params:({params:{i:t,j:e}})=>(0,Qe._)`{i: ${t}, j: ${e}}`},AM={keyword:"uniqueItems",type:"array",schemaType:"boolean",$data:!0,error:IM,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,Vh.getSchemaTypes)(o.items):[];t.block$data(c,d,(0,Qe._)`${i} === false`),t.ok(c);function d(){let p=e.let("i",(0,Qe._)`${r}.length`),h=e.let("j");t.setParams({i:p,j:h}),e.assign(c,!0),e.if((0,Qe._)`${p} > 1`,()=>(l()?m:f)(p,h))}function l(){return u.length>0&&!u.some(p=>p==="object"||p==="array")}function m(p,h){let g=e.name("item"),y=(0,Vh.checkDataTypes)(u,g,a.opts.strictNumbers,Vh.DataType.Wrong),_=e.const("indices",(0,Qe._)`{}`);e.for((0,Qe._)`;${p}--;`,()=>{e.let(g,(0,Qe._)`${r}[${p}]`),e.if(y,(0,Qe._)`continue`),u.length>1&&e.if((0,Qe._)`typeof ${g} == "string"`,(0,Qe._)`${g} += "_"`),e.if((0,Qe._)`typeof ${_}[${g}] == "number"`,()=>{e.assign(h,(0,Qe._)`${_}[${g}]`),t.error(),e.assign(c,!1).break()}).code((0,Qe._)`${_}[${g}] = ${p}`)})}function f(p,h){let g=(0,CM.useFunc)(e,OM.default),y=e.name("outer");e.label(y).for((0,Qe._)`;${p}--;`,()=>e.for((0,Qe._)`${h} = ${p}; ${h}--;`,()=>e.if((0,Qe._)`${g}(${r}[${p}], ${r}[${h}])`,()=>{t.error(),e.assign(c,!1).break(y)})))}}};Wh.default=AM});var h0=N(Kh=>{"use strict";Object.defineProperty(Kh,"__esModule",{value:!0});var Gh=te(),NM=de(),DM=cu(),MM={message:"must be equal to constant",params:({schemaCode:t})=>(0,Gh._)`{allowedValue: ${t}}`},jM={keyword:"const",$data:!0,error:MM,code(t){let{gen:e,data:r,$data:n,schemaCode:s,schema:o}=t;n||o&&typeof o=="object"?t.fail$data((0,Gh._)`!${(0,NM.useFunc)(e,DM.default)}(${r}, ${s})`):t.fail((0,Gh._)`${o} !== ${r}`)}};Kh.default=jM});var g0=N(Jh=>{"use strict";Object.defineProperty(Jh,"__esModule",{value:!0});var Ni=te(),zM=de(),LM=cu(),FM={message:"must be equal to one of the allowed values",params:({schemaCode:t})=>(0,Ni._)`{allowedValues: ${t}}`},UM={keyword:"enum",schemaType:"array",$data:!0,error:FM,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,zM.useFunc)(e,LM.default)),d;if(a||n)d=e.let("valid"),t.block$data(d,l);else{if(!Array.isArray(s))throw new Error("ajv implementation error");let f=e.const("vSchema",o);d=(0,Ni.or)(...s.map((p,h)=>m(f,h)))}t.pass(d);function l(){e.assign(d,!1),e.forOf("v",o,f=>e.if((0,Ni._)`${u()}(${r}, ${f})`,()=>e.assign(d,!0).break()))}function m(f,p){let h=s[p];return typeof h=="object"&&h!==null?(0,Ni._)`${u()}(${r}, ${f}[${p}])`:(0,Ni._)`${r} === ${h}`}}};Jh.default=UM});var y0=N(Yh=>{"use strict";Object.defineProperty(Yh,"__esModule",{value:!0});var HM=s0(),ZM=o0(),BM=c0(),qM=u0(),VM=l0(),WM=d0(),GM=p0(),KM=f0(),JM=h0(),YM=g0(),XM=[HM.default,ZM.default,BM.default,qM.default,VM.default,WM.default,GM.default,KM.default,{keyword:"type",schemaType:["string","array"]},{keyword:"nullable",schemaType:"boolean"},JM.default,YM.default];Yh.default=XM});var Qh=N(Di=>{"use strict";Object.defineProperty(Di,"__esModule",{value:!0});Di.validateAdditionalItems=void 0;var as=te(),Xh=de(),QM={message:({params:{len:t}})=>(0,as.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,as._)`{limit: ${t}}`},ej={keyword:"additionalItems",type:"array",schemaType:["boolean","object"],before:"uniqueItems",error:QM,code(t){let{parentSchema:e,it:r}=t,{items:n}=e;if(!Array.isArray(n)){(0,Xh.checkStrictMode)(r,'"additionalItems" is ignored when "items" is not an array of schemas');return}_0(t,n)}};function _0(t,e){let{gen:r,schema:n,data:s,keyword:o,it:i}=t;i.items=!0;let a=r.const("len",(0,as._)`${s}.length`);if(n===!1)t.setParams({len:e.length}),t.pass((0,as._)`${a} <= ${e.length}`);else if(typeof n=="object"&&!(0,Xh.alwaysValidSchema)(i,n)){let u=r.var("valid",(0,as._)`${a} <= ${e.length}`);r.if((0,as.not)(u),()=>c(u)),t.ok(u)}function c(u){r.forRange("i",e.length,a,d=>{t.subschema({keyword:o,dataProp:d,dataPropType:Xh.Type.Num},u),i.allErrors||r.if((0,as.not)(u),()=>r.break())})}}Di.validateAdditionalItems=_0;Di.default=ej});var eg=N(Mi=>{"use strict";Object.defineProperty(Mi,"__esModule",{value:!0});Mi.validateTuple=void 0;var x0=te(),uu=de(),tj=Gt(),rj={keyword:"items",type:"array",schemaType:["object","array","boolean"],before:"uniqueItems",code(t){let{schema:e,it:r}=t;if(Array.isArray(e))return v0(t,"additionalItems",e);r.items=!0,!(0,uu.alwaysValidSchema)(r,e)&&t.ok((0,tj.validateArray)(t))}};function v0(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=uu.mergeEvaluated.items(n,r.length,a.items));let c=n.name("valid"),u=n.const("len",(0,x0._)`${o}.length`);r.forEach((l,m)=>{(0,uu.alwaysValidSchema)(a,l)||(n.if((0,x0._)`${u} > ${m}`,()=>t.subschema({keyword:i,schemaProp:m,dataProp:m},c)),t.ok(c))});function d(l){let{opts:m,errSchemaPath:f}=a,p=r.length,h=p===l.minItems&&(p===l.maxItems||l[e]===!1);if(m.strictTuples&&!h){let g=`"${i}" is ${p}-tuple, but minItems or maxItems/${e} are not specified or different at path "${f}"`;(0,uu.checkStrictMode)(a,g,m.strictTuples)}}}Mi.validateTuple=v0;Mi.default=rj});var b0=N(tg=>{"use strict";Object.defineProperty(tg,"__esModule",{value:!0});var nj=eg(),sj={keyword:"prefixItems",type:"array",schemaType:["array"],before:"uniqueItems",code:t=>(0,nj.validateTuple)(t,"items")};tg.default=sj});var k0=N(rg=>{"use strict";Object.defineProperty(rg,"__esModule",{value:!0});var S0=te(),oj=de(),ij=Gt(),aj=Qh(),cj={message:({params:{len:t}})=>(0,S0.str)`must NOT have more than ${t} items`,params:({params:{len:t}})=>(0,S0._)`{limit: ${t}}`},uj={keyword:"items",type:"array",schemaType:["object","boolean"],before:"uniqueItems",error:cj,code(t){let{schema:e,parentSchema:r,it:n}=t,{prefixItems:s}=r;n.items=!0,!(0,oj.alwaysValidSchema)(n,e)&&(s?(0,aj.validateAdditionalItems)(t,s):t.ok((0,ij.validateArray)(t)))}};rg.default=uj});var w0=N(ng=>{"use strict";Object.defineProperty(ng,"__esModule",{value:!0});var Jt=te(),lu=de(),lj={message:({params:{min:t,max:e}})=>e===void 0?(0,Jt.str)`must contain at least ${t} valid item(s)`:(0,Jt.str)`must contain at least ${t} and no more than ${e} valid item(s)`,params:({params:{min:t,max:e}})=>e===void 0?(0,Jt._)`{minContains: ${t}}`:(0,Jt._)`{minContains: ${t}, maxContains: ${e}}`},dj={keyword:"contains",type:"array",schemaType:["object","boolean"],before:"uniqueItems",trackErrors:!0,error:lj,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,Jt._)`${s}.length`);if(t.setParams({min:i,max:a}),a===void 0&&i===0){(0,lu.checkStrictMode)(o,'"minContains" == 0 without "maxContains": "contains" keyword ignored');return}if(a!==void 0&&i>a){(0,lu.checkStrictMode)(o,'"minContains" > "maxContains" is always invalid'),t.fail();return}if((0,lu.alwaysValidSchema)(o,r)){let h=(0,Jt._)`${d} >= ${i}`;a!==void 0&&(h=(0,Jt._)`${h} && ${d} <= ${a}`),t.pass(h);return}o.items=!0;let l=e.name("valid");a===void 0&&i===1?f(l,()=>e.if(l,()=>e.break())):i===0?(e.let(l,!0),a!==void 0&&e.if((0,Jt._)`${s}.length > 0`,m)):(e.let(l,!1),m()),t.result(l,()=>t.reset());function m(){let h=e.name("_valid"),g=e.let("count",0);f(h,()=>e.if(h,()=>p(g)))}function f(h,g){e.forRange("i",0,d,y=>{t.subschema({keyword:"contains",dataProp:y,dataPropType:lu.Type.Num,compositeRule:!0},h),g()})}function p(h){e.code((0,Jt._)`${h}++`),a===void 0?e.if((0,Jt._)`${h} >= ${i}`,()=>e.assign(l,!0).break()):(e.if((0,Jt._)`${h} > ${a}`,()=>e.assign(l,!1).break()),i===1?e.assign(l,!0):e.if((0,Jt._)`${h} >= ${i}`,()=>e.assign(l,!0)))}}};ng.default=dj});var T0=N(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.validateSchemaDeps=Er.validatePropertyDeps=Er.error=void 0;var sg=te(),pj=de(),ji=Gt();Er.error={message:({params:{property:t,depsCount:e,deps:r}})=>{let n=e===1?"property":"properties";return(0,sg.str)`must have ${n} ${r} when property ${t} is present`},params:({params:{property:t,depsCount:e,deps:r,missingProperty:n}})=>(0,sg._)`{property: ${t},
55
69
  missingProperty: ${n},
56
70
  depsCount: ${e},
57
- deps: ${r}}`};var vz={keyword:"dependencies",type:"object",schemaType:"object",error:fr.error,code(t){let[e,r]=bz(t);v0(t,e),b0(t,r)}};function bz({schema:t}){let e={},r={};for(let n in t){if(n==="__proto__")continue;let o=Array.isArray(t[n])?e:r;o[n]=t[n]}return[e,r]}function v0(t,e=t.schema){let{gen:r,data:n,it:o}=t;if(Object.keys(e).length===0)return;let s=r.let("missing");for(let i in e){let a=e[i];if(a.length===0)continue;let c=(0,Ei.propertyInData)(r,n,i,o.opts.ownProperties);t.setParams({property:i,depsCount:a.length,deps:a.join(", ")}),o.allErrors?r.if(c,()=>{for(let u of a)(0,Ei.checkReportMissingProp)(t,u)}):(r.if((0,fh._)`${c} && (${(0,Ei.checkMissingProp)(t,a,s)})`),(0,Ei.reportMissingProp)(t,s),r.else())}}fr.validatePropertyDeps=v0;function b0(t,e=t.schema){let{gen:r,data:n,keyword:o,it:s}=t,i=r.name("valid");for(let a in e)(0,xz.alwaysValidSchema)(s,e[a])||(r.if((0,Ei.propertyInData)(r,n,a,s.opts.ownProperties),()=>{let c=t.subschema({keyword:o,schemaProp:a},i);t.mergeValidEvaluated(c,i)},()=>r.var(i,!0)),t.ok(i))}fr.validateSchemaDeps=b0;fr.default=vz});var w0=C(hh=>{"use strict";Object.defineProperty(hh,"__esModule",{value:!0});var k0=Q(),Sz=ue(),kz={message:"property name must be valid",params:({params:t})=>(0,k0._)`{propertyName: ${t.propertyName}}`},wz={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:kz,code(t){let{gen:e,schema:r,data:n,it:o}=t;if((0,Sz.alwaysValidSchema)(o,r))return;let s=e.name("valid");e.forIn("key",n,i=>{t.setParams({propertyName:i}),t.subschema({keyword:"propertyNames",data:i,dataTypes:["string"],propertyName:i,compositeRule:!0},s),e.if((0,k0.not)(s),()=>{t.error(!0),o.allErrors||e.break()})}),t.ok(s)}};hh.default=wz});var _h=C(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});var Bc=Ft(),tr=Q(),$z=Ir(),Vc=ue(),Ez={message:"must NOT have additional properties",params:({params:t})=>(0,tr._)`{additionalProperty: ${t.additionalProperty}}`},Tz={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:Ez,code(t){let{gen:e,schema:r,parentSchema:n,data:o,errsCount:s,it:i}=t;if(!s)throw new Error("ajv implementation error");let{allErrors:a,opts:c}=i;if(i.props=!0,c.removeAdditional!=="all"&&(0,Vc.alwaysValidSchema)(i,r))return;let u=(0,Bc.allSchemaProperties)(n.properties),l=(0,Bc.allSchemaProperties)(n.patternProperties);d(),t.ok((0,tr._)`${s} === ${$z.default.errors}`);function d(){e.forIn("key",o,g=>{!u.length&&!l.length?m(g):e.if(p(g),()=>m(g))})}function p(g){let y;if(u.length>8){let _=(0,Vc.schemaRefOrVal)(i,n.properties,"properties");y=(0,Bc.isOwnProperty)(e,_,g)}else u.length?y=(0,tr.or)(...u.map(_=>(0,tr._)`${g} === ${_}`)):y=tr.nil;return l.length&&(y=(0,tr.or)(y,...l.map(_=>(0,tr._)`${(0,Bc.usePattern)(t,_)}.test(${g})`))),(0,tr.not)(y)}function f(g){e.code((0,tr._)`delete ${o}[${g}]`)}function m(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,Vc.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,tr.not)(y),()=>{t.reset(),f(g)})):(h(g,y),a||e.if((0,tr.not)(y),()=>e.break()))}}function h(g,y,_){let x={keyword:"additionalProperties",dataProp:g,dataPropType:Vc.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};gh.default=Tz});var T0=C(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});var Pz=pi(),$0=Ft(),yh=ue(),E0=_h(),Rz={keyword:"properties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,parentSchema:n,data:o,it:s}=t;s.opts.removeAdditional==="all"&&n.additionalProperties===void 0&&E0.default.code(new Pz.KeywordCxt(s,E0.default,"additionalProperties"));let i=(0,$0.allSchemaProperties)(r);for(let d of i)s.definedProperties.add(d);s.opts.unevaluated&&i.length&&s.props!==!0&&(s.props=yh.mergeEvaluated.props(e,(0,yh.toHash)(i),s.props));let a=i.filter(d=>!(0,yh.alwaysValidSchema)(s,r[d]));if(a.length===0)return;let c=e.name("valid");for(let d of a)u(d)?l(d):(e.if((0,$0.propertyInData)(e,o,d,s.opts.ownProperties)),l(d),s.allErrors||e.else().var(c,!0),e.endIf()),t.it.definedProperties.add(d),t.ok(c);function u(d){return s.opts.useDefaults&&!s.compositeRule&&r[d].default!==void 0}function l(d){t.subschema({keyword:"properties",schemaProp:d,dataProp:d},c)}}};xh.default=Rz});var O0=C(vh=>{"use strict";Object.defineProperty(vh,"__esModule",{value:!0});var P0=Ft(),Wc=Q(),R0=ue(),C0=ue(),Cz={keyword:"patternProperties",type:"object",schemaType:"object",code(t){let{gen:e,schema:r,data:n,parentSchema:o,it:s}=t,{opts:i}=s,a=(0,P0.allSchemaProperties)(r),c=a.filter(h=>(0,R0.alwaysValidSchema)(s,r[h]));if(a.length===0||c.length===a.length&&(!s.opts.unevaluated||s.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&o.properties,l=e.name("valid");s.props!==!0&&!(s.props instanceof Wc.Name)&&(s.props=(0,C0.evaluatedPropsToName)(e,s.props));let{props:d}=s;p();function p(){for(let h of a)u&&f(h),s.allErrors?m(h):(e.var(l,!0),m(h),e.if(l))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,R0.checkStrictMode)(s,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function m(h){e.forIn("key",n,g=>{e.if((0,Wc._)`${(0,P0.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:C0.Type.Str},l),s.opts.unevaluated&&d!==!0?e.assign((0,Wc._)`${d}[${g}]`,!0):!y&&!s.allErrors&&e.if((0,Wc.not)(l),()=>e.break())})})}}};vh.default=Cz});var I0=C(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var Oz=ue(),Iz={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,Oz.alwaysValidSchema)(n,r)){t.fail();return}let o=e.name("valid");t.subschema({keyword:"not",compositeRule:!0,createErrors:!1,allErrors:!1},o),t.failResult(o,()=>t.reset(),()=>t.error())},error:{message:"must NOT be valid"}};bh.default=Iz});var A0=C(Sh=>{"use strict";Object.defineProperty(Sh,"__esModule",{value:!0});var Az=Ft(),Nz={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:Az.validateUnion,error:{message:"must match a schema in anyOf"}};Sh.default=Nz});var N0=C(kh=>{"use strict";Object.defineProperty(kh,"__esModule",{value:!0});var Gc=Q(),zz=ue(),jz={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,Gc._)`{passingSchemas: ${t.passing}}`},Dz={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:jz,code(t){let{gen:e,schema:r,parentSchema:n,it:o}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");if(o.opts.discriminator&&n.discriminator)return;let s=r,i=e.let("valid",!1),a=e.let("passing",null),c=e.name("_valid");t.setParams({passing:a}),e.block(u),t.result(i,()=>t.reset(),()=>t.error(!0));function u(){s.forEach((l,d)=>{let p;(0,zz.alwaysValidSchema)(o,l)?e.var(c,!0):p=t.subschema({keyword:"oneOf",schemaProp:d,compositeRule:!0},c),d>0&&e.if((0,Gc._)`${c} && ${i}`).assign(i,!1).assign(a,(0,Gc._)`[${a}, ${d}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,d),p&&t.mergeEvaluated(p,Gc.Name)})})}}};kh.default=Dz});var z0=C(wh=>{"use strict";Object.defineProperty(wh,"__esModule",{value:!0});var Mz=ue(),Lz={keyword:"allOf",schemaType:"array",code(t){let{gen:e,schema:r,it:n}=t;if(!Array.isArray(r))throw new Error("ajv implementation error");let o=e.name("valid");r.forEach((s,i)=>{if((0,Mz.alwaysValidSchema)(n,s))return;let a=t.subschema({keyword:"allOf",schemaProp:i},o);t.ok(o),t.mergeEvaluated(a)})}};wh.default=Lz});var M0=C($h=>{"use strict";Object.defineProperty($h,"__esModule",{value:!0});var Kc=Q(),D0=ue(),Fz={message:({params:t})=>(0,Kc.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,Kc._)`{failingKeyword: ${t.ifClause}}`},Uz={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Fz,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,D0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let o=j0(n,"then"),s=j0(n,"else");if(!o&&!s)return;let i=e.let("valid",!0),a=e.name("_valid");if(c(),t.reset(),o&&s){let l=e.let("ifClause");t.setParams({ifClause:l}),e.if(a,u("then",l),u("else",l))}else o?e.if(a,u("then")):e.if((0,Kc.not)(a),u("else"));t.pass(i,()=>t.error(!0));function c(){let l=t.subschema({keyword:"if",compositeRule:!0,createErrors:!1,allErrors:!1},a);t.mergeEvaluated(l)}function u(l,d){return()=>{let p=t.subschema({keyword:l},a);e.assign(i,a),t.mergeValidEvaluated(p,i),d?e.assign(d,(0,Kc._)`${l}`):t.setParams({ifClause:l})}}}};function j0(t,e){let r=t.schema[e];return r!==void 0&&!(0,D0.alwaysValidSchema)(t,r)}$h.default=Uz});var L0=C(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var Zz=ue(),Hz={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Zz.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};Eh.default=Hz});var F0=C(Th=>{"use strict";Object.defineProperty(Th,"__esModule",{value:!0});var qz=uh(),Bz=g0(),Vz=lh(),Wz=y0(),Gz=x0(),Kz=S0(),Jz=w0(),Yz=_h(),Xz=T0(),Qz=O0(),ej=I0(),tj=A0(),rj=N0(),nj=z0(),oj=M0(),sj=L0();function ij(t=!1){let e=[ej.default,tj.default,rj.default,nj.default,oj.default,sj.default,Jz.default,Yz.default,Kz.default,Xz.default,Qz.default];return t?e.push(Bz.default,Wz.default):e.push(qz.default,Vz.default),e.push(Gz.default),e}Th.default=ij});var U0=C(Ph=>{"use strict";Object.defineProperty(Ph,"__esModule",{value:!0});var Fe=Q(),aj={message:({schemaCode:t})=>(0,Fe.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Fe._)`{format: ${t}}`},cj={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:aj,code(t,e){let{gen:r,data:n,$data:o,schema:s,schemaCode:i,it:a}=t,{opts:c,errSchemaPath:u,schemaEnv:l,self:d}=a;if(!c.validateFormats)return;o?p():f();function p(){let m=r.scopeValue("formats",{ref:d.formats,code:c.code.formats}),h=r.const("fDef",(0,Fe._)`${m}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Fe._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Fe._)`${h}.type || "string"`).assign(y,(0,Fe._)`${h}.validate`),()=>r.assign(g,(0,Fe._)`"string"`).assign(y,h)),t.fail$data((0,Fe.or)(_(),x()));function _(){return c.strictSchema===!1?Fe.nil:(0,Fe._)`${i} && !${y}`}function x(){let k=l.$async?(0,Fe._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Fe._)`${y}(${n})`,E=(0,Fe._)`(typeof ${y} == "function" ? ${k} : ${y}.test(${n}))`;return(0,Fe._)`${y} && ${y} !== true && ${g} === ${e} && !${E}`}}function f(){let m=d.formats[s];if(!m){_();return}if(m===!0)return;let[h,g,y]=x(m);h===e&&t.pass(k());function _(){if(c.strictSchema===!1){d.logger.warn(E());return}throw new Error(E());function E(){return`unknown format "${s}" ignored in schema at path "${u}"`}}function x(E){let H=E instanceof RegExp?(0,Fe.regexpCode)(E):c.code.formats?(0,Fe._)`${c.code.formats}${(0,Fe.getProperty)(s)}`:void 0,z=r.scopeValue("formats",{key:s,ref:E,code:H});return typeof E=="object"&&!(E instanceof RegExp)?[E.type||"string",E.validate,(0,Fe._)`${z}.validate`]:["string",E,z]}function k(){if(typeof m=="object"&&!(m instanceof RegExp)&&m.async){if(!l.$async)throw new Error("async format in sync schema");return(0,Fe._)`await ${y}(${n})`}return typeof g=="function"?(0,Fe._)`${y}(${n})`:(0,Fe._)`${y}.test(${n})`}}}};Ph.default=cj});var Z0=C(Rh=>{"use strict";Object.defineProperty(Rh,"__esModule",{value:!0});var uj=U0(),lj=[uj.default];Rh.default=lj});var H0=C(Vo=>{"use strict";Object.defineProperty(Vo,"__esModule",{value:!0});Vo.contentVocabulary=Vo.metadataVocabulary=void 0;Vo.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];Vo.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var B0=C(Ch=>{"use strict";Object.defineProperty(Ch,"__esModule",{value:!0});var dj=XS(),pj=p0(),mj=F0(),fj=Z0(),q0=H0(),hj=[dj.default,pj.default,(0,mj.default)(),fj.default,q0.metadataVocabulary,q0.contentVocabulary];Ch.default=hj});var W0=C(Jc=>{"use strict";Object.defineProperty(Jc,"__esModule",{value:!0});Jc.DiscrError=void 0;var V0;(function(t){t.Tag="tag",t.Mapping="mapping"})(V0||(Jc.DiscrError=V0={}))});var K0=C(Ih=>{"use strict";Object.defineProperty(Ih,"__esModule",{value:!0});var Wo=Q(),Oh=W0(),G0=Ic(),gj=mi(),_j=ue(),yj={message:({params:{discrError:t,tagName:e}})=>t===Oh.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,Wo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},xj={keyword:"discriminator",type:"object",schemaType:"object",error:yj,code(t){let{gen:e,data:r,schema:n,parentSchema:o,it:s}=t,{oneOf:i}=o;if(!s.opts.discriminator)throw new Error("discriminator: requires discriminator option");let a=n.propertyName;if(typeof a!="string")throw new Error("discriminator: requires propertyName");if(n.mapping)throw new Error("discriminator: mapping is not supported");if(!i)throw new Error("discriminator: requires oneOf keyword");let c=e.let("valid",!1),u=e.const("tag",(0,Wo._)`${r}${(0,Wo.getProperty)(a)}`);e.if((0,Wo._)`typeof ${u} == "string"`,()=>l(),()=>t.error(!1,{discrError:Oh.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function l(){let f=p();e.if(!1);for(let m in f)e.elseIf((0,Wo._)`${u} === ${m}`),e.assign(c,d(f[m]));e.else(),t.error(!1,{discrError:Oh.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function d(f){let m=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},m);return t.mergeEvaluated(h,Wo.Name),m}function p(){var f;let m={},h=y(o),g=!0;for(let k=0;k<i.length;k++){let E=i[k];if(E?.$ref&&!(0,_j.schemaHasRulesButRef)(E,s.self.RULES)){let z=E.$ref;if(E=G0.resolveRef.call(s.self,s.schemaEnv.root,s.baseId,z),E instanceof G0.SchemaEnv&&(E=E.schema),E===void 0)throw new gj.default(s.opts.uriResolver,s.baseId,z)}let H=(f=E?.properties)===null||f===void 0?void 0:f[a];if(typeof H!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(E)),_(H,k)}if(!g)throw new Error(`discriminator: "${a}" must be required`);return m;function y({required:k}){return Array.isArray(k)&&k.includes(a)}function _(k,E){if(k.const)x(k.const,E);else if(k.enum)for(let H of k.enum)x(H,E);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(k,E){if(typeof k!="string"||k in m)throw new Error(`discriminator: "${a}" values must be unique strings`);m[k]=E}}}};Ih.default=xj});var J0=C((l9,vj)=>{vj.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 Nh=C((Te,Ah)=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.MissingRefError=Te.ValidationError=Te.CodeGen=Te.Name=Te.nil=Te.stringify=Te.str=Te._=Te.KeywordCxt=Te.Ajv=void 0;var bj=VS(),Sj=B0(),kj=K0(),Y0=J0(),wj=["/properties"],Yc="http://json-schema.org/draft-07/schema",Go=class extends bj.default{_addVocabularies(){super._addVocabularies(),Sj.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(kj.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(Y0,wj):Y0;this.addMetaSchema(e,Yc,!1),this.refs["http://json-schema.org/schema"]=Yc}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(Yc)?Yc:void 0)}};Te.Ajv=Go;Ah.exports=Te=Go;Ah.exports.Ajv=Go;Object.defineProperty(Te,"__esModule",{value:!0});Te.default=Go;var $j=pi();Object.defineProperty(Te,"KeywordCxt",{enumerable:!0,get:function(){return $j.KeywordCxt}});var Ko=Q();Object.defineProperty(Te,"_",{enumerable:!0,get:function(){return Ko._}});Object.defineProperty(Te,"str",{enumerable:!0,get:function(){return Ko.str}});Object.defineProperty(Te,"stringify",{enumerable:!0,get:function(){return Ko.stringify}});Object.defineProperty(Te,"nil",{enumerable:!0,get:function(){return Ko.nil}});Object.defineProperty(Te,"Name",{enumerable:!0,get:function(){return Ko.Name}});Object.defineProperty(Te,"CodeGen",{enumerable:!0,get:function(){return Ko.CodeGen}});var Ej=Cc();Object.defineProperty(Te,"ValidationError",{enumerable:!0,get:function(){return Ej.default}});var Tj=mi();Object.defineProperty(Te,"MissingRefError",{enumerable:!0,get:function(){return Tj.default}})});var sk=C(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.formatNames=gr.fastFormats=gr.fullFormats=void 0;function hr(t,e){return{validate:t,compare:e}}gr.fullFormats={date:hr(tk,Mh),time:hr(jh(!0),Lh),"date-time":hr(X0(!0),nk),"iso-time":hr(jh(),rk),"iso-date-time":hr(X0(),ok),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:Aj,"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:Fj,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:Nj,int32:{type:"number",validate:Dj},int64:{type:"number",validate:Mj},float:{type:"number",validate:ek},double:{type:"number",validate:ek},password:!0,binary:!0};gr.fastFormats={...gr.fullFormats,date:hr(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Mh),time:hr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Lh),"date-time":hr(/^\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,nk),"iso-time":hr(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,rk),"iso-date-time":hr(/^\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,ok),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};gr.formatNames=Object.keys(gr.fullFormats);function Pj(t){return t%4===0&&(t%100!==0||t%400===0)}var Rj=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Cj=[0,31,28,31,30,31,30,31,31,30,31,30,31];function tk(t){let e=Rj.exec(t);if(!e)return!1;let r=+e[1],n=+e[2],o=+e[3];return n>=1&&n<=12&&o>=1&&o<=(n===2&&Pj(r)?29:Cj[n])}function Mh(t,e){if(t&&e)return t>e?1:t<e?-1:0}var zh=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function jh(t){return function(r){let n=zh.exec(r);if(!n)return!1;let o=+n[1],s=+n[2],i=+n[3],a=n[4],c=n[5]==="-"?-1:1,u=+(n[6]||0),l=+(n[7]||0);if(u>23||l>59||t&&!a)return!1;if(o<=23&&s<=59&&i<60)return!0;let d=s-l*c,p=o-u*c-(d<0?1:0);return(p===23||p===-1)&&(d===59||d===-1)&&i<61}}function Lh(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 rk(t,e){if(!(t&&e))return;let r=zh.exec(t),n=zh.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 Dh=/t|\s/i;function X0(t){let e=jh(t);return function(n){let o=n.split(Dh);return o.length===2&&tk(o[0])&&e(o[1])}}function nk(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function ok(t,e){if(!(t&&e))return;let[r,n]=t.split(Dh),[o,s]=e.split(Dh),i=Mh(r,o);if(i!==void 0)return i||Lh(n,s)}var Oj=/\/|:/,Ij=/^(?:[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 Aj(t){return Oj.test(t)&&Ij.test(t)}var Q0=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Nj(t){return Q0.lastIndex=0,Q0.test(t)}var zj=-(2**31),jj=2**31-1;function Dj(t){return Number.isInteger(t)&&t<=jj&&t>=zj}function Mj(t){return Number.isInteger(t)}function ek(){return!0}var Lj=/[^\\]\\Z/;function Fj(t){if(Lj.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var ik=C(Jo=>{"use strict";Object.defineProperty(Jo,"__esModule",{value:!0});Jo.formatLimitDefinition=void 0;var Uj=Nh(),rr=Q(),un=rr.operators,Xc={formatMaximum:{okStr:"<=",ok:un.LTE,fail:un.GT},formatMinimum:{okStr:">=",ok:un.GTE,fail:un.LT},formatExclusiveMaximum:{okStr:"<",ok:un.LT,fail:un.GTE},formatExclusiveMinimum:{okStr:">",ok:un.GT,fail:un.LTE}},Zj={message:({keyword:t,schemaCode:e})=>(0,rr.str)`should be ${Xc[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,rr._)`{comparison: ${Xc[t].okStr}, limit: ${e}}`};Jo.formatLimitDefinition={keyword:Object.keys(Xc),type:"string",schemaType:"string",$data:!0,error:Zj,code(t){let{gen:e,data:r,schemaCode:n,keyword:o,it:s}=t,{opts:i,self:a}=s;if(!i.validateFormats)return;let c=new Uj.KeywordCxt(s,a.RULES.all.format.definition,"format");c.$data?u():l();function u(){let p=e.scopeValue("formats",{ref:a.formats,code:i.code.formats}),f=e.const("fmt",(0,rr._)`${p}[${c.schemaCode}]`);t.fail$data((0,rr.or)((0,rr._)`typeof ${f} != "object"`,(0,rr._)`${f} instanceof RegExp`,(0,rr._)`typeof ${f}.compare != "function"`,d(f)))}function l(){let p=c.schema,f=a.formats[p];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${o}": format "${p}" does not define "compare" function`);let m=e.scopeValue("formats",{key:p,ref:f,code:i.code.formats?(0,rr._)`${i.code.formats}${(0,rr.getProperty)(p)}`:void 0});t.fail$data(d(m))}function d(p){return(0,rr._)`${p}.compare(${r}, ${n}) ${Xc[o].fail} 0`}},dependencies:["format"]};var Hj=t=>(t.addKeyword(Jo.formatLimitDefinition),t);Jo.default=Hj});var lk=C((Ti,uk)=>{"use strict";Object.defineProperty(Ti,"__esModule",{value:!0});var Yo=sk(),qj=ik(),Fh=Q(),ak=new Fh.Name("fullFormats"),Bj=new Fh.Name("fastFormats"),Uh=(t,e={keywords:!0})=>{if(Array.isArray(e))return ck(t,e,Yo.fullFormats,ak),t;let[r,n]=e.mode==="fast"?[Yo.fastFormats,Bj]:[Yo.fullFormats,ak],o=e.formats||Yo.formatNames;return ck(t,o,r,n),e.keywords&&(0,qj.default)(t),t};Uh.get=(t,e="full")=>{let n=(e==="fast"?Yo.fastFormats:Yo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function ck(t,e,r,n){var o,s;(o=(s=t.opts.code).formats)!==null&&o!==void 0||(s.formats=(0,Fh._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}uk.exports=Ti=Uh;Object.defineProperty(Ti,"__esModule",{value:!0});Ti.default=Uh});function Vj(){let t=new dk.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,pk.default)(t),t}var dk,pk,Qc,mk=v(()=>{dk=fs(Nh(),1),pk=fs(lk(),1);Qc=class{constructor(e){this._ajv=e??Vj()}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 eu,fk=v(()=>{Un();eu=class{constructor(e){this._server=e}requestStream(e,r,n){return this._server.requestStream(e,r,n)}createMessageStream(e,r){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let o=e.messages[e.messages.length-1],s=Array.isArray(o.content)?o.content:[o.content],i=s.some(l=>l.type==="tool_result"),a=e.messages.length>1?e.messages[e.messages.length-2]:void 0,c=a?Array.isArray(a.content)?a.content:[a.content]:[],u=c.some(l=>l.type==="tool_use");if(i){if(s.some(l=>l.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!u)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(u){let l=new Set(c.filter(p=>p.type==="tool_use").map(p=>p.id)),d=new Set(s.filter(p=>p.type==="tool_result").map(p=>p.toolUseId));if(l.size!==d.size||![...l].every(p=>d.has(p)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return this.requestStream({method:"sampling/createMessage",params:e},Ys,r)}elicitInputStream(e,r){let n=this._server.getClientCapabilities(),o=e.mode??"form";switch(o){case"url":{if(!n?.elicitation?.url)throw new Error("Client does not support url elicitation.");break}case"form":{if(!n?.elicitation?.form)throw new Error("Client does not support form elicitation.");break}}let s=o==="form"&&e.mode===void 0?{...e,mode:"form"}:e;return this.requestStream({method:"elicitation/create",params:s},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 hk(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 gk(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 _k=v(()=>{});var tu,yk=v(()=>{$b();Un();mk();Ls();fk();_k();tu=class extends _c{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Js.options.map((n,o)=>[n,o])),this.isMessageIgnored=(n,o)=>{let s=this._loggingLevels.get(o);return s?this.LOG_LEVEL_SEVERITY.get(n)<this.LOG_LEVEL_SEVERITY.get(s):!1},this._capabilities=r?.capabilities??{},this._instructions=r?.instructions,this._jsonSchemaValidator=r?.jsonSchemaValidator??new Qc,this.setRequestHandler(tm,n=>this._oninitialize(n)),this.setNotificationHandler(rm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(um,async(n,o)=>{let s=o.sessionId||o.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=Js.safeParse(i);return a.success&&this._loggingLevels.set(s,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new eu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=wb(this._capabilities,e)}setRequestHandler(e,r){let o=Yr(e)?.method;if(!o)throw new Error("Schema is missing a method literal");let s;if(zt(o)){let a=o;s=a._zod?.def?.value??a.value}else{let a=o;s=a._def?.value??a.value}if(typeof s!="string")throw new Error("Schema method literal must be a string");if(s==="tools/call"){let a=async(c,u)=>{let l=Jr(Ao,c);if(!l.success){let m=l.error instanceof Error?l.error.message:String(l.error);throw new D(Z.InvalidParams,`Invalid tools/call request: ${m}`)}let{params:d}=l.data,p=await Promise.resolve(r(c,u));if(d.task){let m=Jr(Po,p);if(!m.success){let h=m.error instanceof Error?m.error.message:String(m.error);throw new D(Z.InvalidParams,`Invalid task creation result: ${h}`)}return m.data}let f=Jr(sc,p);if(!f.success){let m=f.error instanceof Error?f.error.message:String(f.error);throw new D(Z.InvalidParams,`Invalid tools/call result: ${m}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){gk(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&hk(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:wv.includes(r)?r:Jp,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"},Va)}async createMessage(e,r){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new Error("Client does not support sampling tools capability.");if(e.messages.length>0){let n=e.messages[e.messages.length-1],o=Array.isArray(n.content)?n.content:[n.content],s=o.some(u=>u.type==="tool_result"),i=e.messages.length>1?e.messages[e.messages.length-2]:void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],c=a.some(u=>u.type==="tool_use");if(s){if(o.some(u=>u.type!=="tool_result"))throw new Error("The last message must contain only tool_result content if any is present");if(!c)throw new Error("tool_result blocks are not matching any tool_use from the previous message")}if(c){let u=new Set(a.filter(d=>d.type==="tool_use").map(d=>d.id)),l=new Set(o.filter(d=>d.type==="tool_result").map(d=>d.toolUseId));if(u.size!==l.size||![...u].every(d=>l.has(d)))throw new Error("ids of tool_result blocks and tool_use blocks from previous message do not match")}}return e.tools?this.request({method:"sampling/createMessage",params:e},lm,r):this.request({method:"sampling/createMessage",params:e},Ys,r)}async elicitInput(e,r){switch(e.mode??"form"){case"url":{if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support url elicitation.");let o=e;return this.request({method:"elicitation/create",params:o},No,r)}case"form":{if(!this._clientCapabilities?.elicitation?.form)throw new Error("Client does not support form elicitation.");let o=e.mode==="form"?e:{...e,mode:"form"},s=await this.request({method:"elicitation/create",params:o},No,r);if(s.action==="accept"&&s.content&&o.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(o.requestedSchema)(s.content);if(!a.valid)throw new D(Z.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof D?i:new D(Z.InternalError,`Error validating elicitation response: ${i instanceof Error?i.message:String(i)}`)}return s}}}createElicitationCompletionNotifier(e,r){if(!this._clientCapabilities?.elicitation?.url)throw new Error("Client does not support URL elicitation (required for notifications/elicitation/complete)");return()=>this.notification({method:"notifications/elicitation/complete",params:{elicitationId:e}},r)}async listRoots(e,r){return this.request({method:"roots/list",params:e},dm,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 Zh(t){return!!t&&typeof t=="object"&&vk in t}function bk(t){return t[vk]?.complete}var vk,xk,Sk=v(()=>{vk=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(xk||(xk={}))});var kk=v(()=>{});function Gj(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"),!Wj.test(t)){let r=t.split("").filter(n=>!/[A-Za-z0-9._-]/.test(n)).filter((n,o,s)=>s.indexOf(n)===o);return e.push(`Tool name contains invalid characters: ${r.map(n=>`"${n}"`).join(", ")}`,"Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)"),{isValid:!1,warnings:e}}return{isValid:!0,warnings:e}}function Kj(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 Hh(t){let e=Gj(t);return Kj(t,e.warnings),e.isValid}var Wj,wk=v(()=>{Wj=/^[A-Za-z0-9._-]{1,128}$/});var ru,$k=v(()=>{ru=class{constructor(e){this._mcpServer=e}registerToolTask(e,r,n){let o={taskSupport:"required",...r.execution};if(o.taskSupport==="forbidden")throw new Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,r.title,r.description,r.inputSchema,r.outputSchema,r.annotations,o,r._meta,n)}}});var qh=v(()=>{ga();ga()});function Pk(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Rk(t){return"_def"in t||"_zod"in t||Pk(t)}function Bh(t){return typeof t!="object"||t===null||Rk(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Pk)}function Ek(t){if(t){if(Bh(t))return Fn(t);if(!Rk(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Yj(t){let e=Yr(t);return e?Object.entries(e).map(([r,n])=>{let o=Kx(n),s=Jx(n);return{name:r,description:o,required:!s}}):[]}function ln(t){let r=Yr(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=Fa(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Tk(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var nu,Jj,Pi,Ck=v(()=>{yk();Ls();Gm();Un();Sk();kk();wk();$k();qh();nu=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 tu(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new ru(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(ln(oc)),this.server.assertCanSetRequestHandler(ln(Ao)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(oc,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,r])=>{let n={name:e,title:r.title,description:r.description,inputSchema:(()=>{let o=Eo(r.inputSchema);return o?Bm(o,{strictUnions:!0,pipeStrategy:"input"}):Jj})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let o=Eo(r.outputSchema);o&&(n.outputSchema=Bm(o,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(Ao,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new D(Z.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new D(Z.InvalidParams,`Tool ${e.params.name} disabled`);let o=!!e.params.task,s=n.execution?.taskSupport,i="createTask"in n.handler;if((s==="required"||s==="optional")&&!i)throw new D(Z.InternalError,`Tool ${e.params.name} has taskSupport '${s}' but was not registered with registerToolTask`);if(s==="required"&&!o)throw new D(Z.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(s==="optional"&&!o&&i)return await this.handleAutomaticTaskPolling(n,e,r);let a=await this.validateToolInput(n,e.params.arguments,e.params.name),c=await this.executeToolHandler(n,a,r);return o||await this.validateToolOutput(n,c,e.params.name),c}catch(n){if(n instanceof D&&n.code===Z.UrlElicitationRequired)throw n;return this.createToolError(n instanceof Error?n.message:String(n))}}),this._toolHandlersInitialized=!0)}createToolError(e){return{content:[{type:"text",text:e}],isError:!0}}async validateToolInput(e,r,n){if(!e.inputSchema)return;let s=Eo(e.inputSchema)??e.inputSchema,i=await Ma(s,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=La(a);throw new D(Z.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 D(Z.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let o=Eo(e.outputSchema),s=await Ma(o,r.structuredContent);if(!s.success){let i="error"in s?s.error:"Unknown error",a=La(i);throw new D(Z.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${a}`)}}async executeToolHandler(e,r,n){let o=e.handler;if("createTask"in o){if(!n.taskStore)throw new Error("No task store provided.");let i={...n,taskStore:n.taskStore};if(e.inputSchema){let a=o;return await Promise.resolve(a.createTask(r,i))}else{let a=o;return await Promise.resolve(a.createTask(i))}}if(e.inputSchema){let i=o;return await Promise.resolve(i(r,n))}else{let i=o;return await Promise.resolve(i(n))}}async handleAutomaticTaskPolling(e,r,n){if(!n.taskStore)throw new Error("No task store provided for task-capable tool.");let o=await this.validateToolInput(e,r.params.arguments,r.params.name),s=e.handler,i={...n,taskStore:n.taskStore},a=o?await Promise.resolve(s.createTask(o,i)):await Promise.resolve(s.createTask(i)),c=a.task.taskId,u=a.task,l=u.pollInterval??5e3;for(;u.status!=="completed"&&u.status!=="failed"&&u.status!=="cancelled";){await new Promise(p=>setTimeout(p,l));let d=await n.taskStore.getTask(c);if(!d)throw new D(Z.InternalError,`Task ${c} not found during polling`);u=d}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(ln(ic)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(ic,async e=>{switch(e.params.ref.type){case"ref/prompt":return Fv(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Uv(e),this.handleResourceCompletion(e,e.params.ref);default:throw new D(Z.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new D(Z.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new D(Z.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Pi;let s=Yr(n.argsSchema)?.[e.params.argument.name];if(!Zh(s))return Pi;let i=bk(s);if(!i)return Pi;let a=await i(e.params.argument.value,e.params.context);return Tk(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 Pi;throw new D(Z.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let o=n.resourceTemplate.completeCallback(e.params.argument.name);if(!o)return Pi;let s=await o(e.params.argument.value,e.params.context);return Tk(s)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(ln(Co)),this.server.assertCanSetRequestHandler(ln(Oo)),this.server.assertCanSetRequestHandler(ln(rc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Co,async(e,r)=>{let n=Object.entries(this._registeredResources).filter(([s,i])=>i.enabled).map(([s,i])=>({uri:s,name:i.name,...i.metadata})),o=[];for(let s of Object.values(this._registeredResourceTemplates)){if(!s.resourceTemplate.listCallback)continue;let i=await s.resourceTemplate.listCallback(r);for(let a of i.resources)o.push({...s.metadata,...a})}return{resources:[...n,...o]}}),this.server.setRequestHandler(Oo,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(rc,async(e,r)=>{let n=new URL(e.params.uri),o=this._registeredResources[n.toString()];if(o){if(!o.enabled)throw new D(Z.InvalidParams,`Resource ${n} disabled`);return o.readCallback(n,r)}for(let s of Object.values(this._registeredResourceTemplates)){let i=s.resourceTemplate.uriTemplate.match(n.toString());if(i)return s.readCallback(n,i,r)}throw new D(Z.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(ln(Io)),this.server.assertCanSetRequestHandler(ln(nc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Io,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Yj(r.argsSchema):void 0}))})),this.server.setRequestHandler(nc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new D(Z.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new D(Z.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let o=Eo(n.argsSchema),s=await Ma(o,e.params.arguments);if(!s.success){let c="error"in s?s.error:"Unknown error",u=La(c);throw new D(Z.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${u}`)}let i=s.data,a=n.callback;return await Promise.resolve(a(i,r))}else{let o=n.callback;return await Promise.resolve(o(r))}}),this._promptHandlersInitialized=!0)}resource(e,r,...n){let o;typeof n[0]=="object"&&(o=n.shift());let s=n[0];if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let i=this._createRegisteredResource(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,void 0,r,o,s);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}registerResource(e,r,n,o){if(typeof r=="string"){if(this._registeredResources[r])throw new Error(`Resource ${r} is already registered`);let s=this._createRegisteredResource(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}else{if(this._registeredResourceTemplates[e])throw new Error(`Resource template ${e} is already registered`);let s=this._createRegisteredResourceTemplate(e,n.title,r,n,o);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),s}}_createRegisteredResource(e,r,n,o,s){let i={name:e,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({uri:null}),update:a=>{typeof a.uri<"u"&&a.uri!==n&&(delete this._registeredResources[n],a.uri&&(this._registeredResources[a.uri]=i)),typeof a.name<"u"&&(i.name=a.name),typeof a.title<"u"&&(i.title=a.title),typeof a.metadata<"u"&&(i.metadata=a.metadata),typeof a.callback<"u"&&(i.readCallback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=i,i}_createRegisteredResourceTemplate(e,r,n,o,s){let i={resourceTemplate:n,title:r,metadata:o,readCallback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:u=>{typeof u.name<"u"&&u.name!==e&&(delete this._registeredResourceTemplates[e],u.name&&(this._registeredResourceTemplates[u.name]=i)),typeof u.title<"u"&&(i.title=u.title),typeof u.template<"u"&&(i.resourceTemplate=u.template),typeof u.metadata<"u"&&(i.metadata=u.metadata),typeof u.callback<"u"&&(i.readCallback=u.callback),typeof u.enabled<"u"&&(i.enabled=u.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=i;let a=n.uriTemplate.variableNames;return Array.isArray(a)&&a.some(u=>!!n.completeCallback(u))&&this.setCompletionRequestHandler(),i}_createRegisteredPrompt(e,r,n,o,s){let i={title:r,description:n,argsSchema:o===void 0?void 0:Fn(o),callback:s,enabled:!0,disable:()=>i.update({enabled:!1}),enable:()=>i.update({enabled:!0}),remove:()=>i.update({name:null}),update:a=>{typeof a.name<"u"&&a.name!==e&&(delete this._registeredPrompts[e],a.name&&(this._registeredPrompts[a.name]=i)),typeof a.title<"u"&&(i.title=a.title),typeof a.description<"u"&&(i.description=a.description),typeof a.argsSchema<"u"&&(i.argsSchema=Fn(a.argsSchema)),typeof a.callback<"u"&&(i.callback=a.callback),typeof a.enabled<"u"&&(i.enabled=a.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=i,o&&Object.values(o).some(c=>{let u=c instanceof mt?c._def?.innerType:c;return Zh(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,o,s,i,a,c,u){Hh(e);let l={title:r,description:n,inputSchema:Ek(o),outputSchema:Ek(s),annotations:i,execution:a,_meta:c,handler:u,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:d=>{typeof d.name<"u"&&d.name!==e&&(typeof d.name=="string"&&Hh(d.name),delete this._registeredTools[e],d.name&&(this._registeredTools[d.name]=l)),typeof d.title<"u"&&(l.title=d.title),typeof d.description<"u"&&(l.description=d.description),typeof d.paramsSchema<"u"&&(l.inputSchema=Fn(d.paramsSchema)),typeof d.outputSchema<"u"&&(l.outputSchema=Fn(d.outputSchema)),typeof d.callback<"u"&&(l.handler=d.callback),typeof d.annotations<"u"&&(l.annotations=d.annotations),typeof d._meta<"u"&&(l._meta=d._meta),typeof d.enabled<"u"&&(l.enabled=d.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...r){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let n,o,s,i;if(typeof r[0]=="string"&&(n=r.shift()),r.length>1){let c=r[0];if(Bh(c))o=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Bh(r[0])&&(i=r.shift());else if(typeof c=="object"&&c!==null){if(Object.values(c).some(u=>typeof u=="object"&&u!==null))throw new Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);i=r.shift()}}let a=r[0];return this._createRegisteredTool(e,void 0,n,o,s,i,{taskSupport:"forbidden"},void 0,a)}registerTool(e,r,n){if(this._registeredTools[e])throw new Error(`Tool ${e} is already registered`);let{title:o,description:s,inputSchema:i,outputSchema:a,annotations:c,_meta:u}=r;return this._createRegisteredTool(e,o,s,i,a,c,{taskSupport:"forbidden"},u,n)}prompt(e,...r){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let n;typeof r[0]=="string"&&(n=r.shift());let o;r.length>1&&(o=r.shift());let s=r[0],i=this._createRegisteredPrompt(e,void 0,n,o,s);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),i}registerPrompt(e,r,n){if(this._registeredPrompts[e])throw new Error(`Prompt ${e} is already registered`);let{title:o,description:s,argsSchema:i}=r,a=this._createRegisteredPrompt(e,o,s,i,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,r){return this.server.sendLoggingMessage(e,r)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},Jj={type:"object",properties:{}};Pi={completion:{values:[],hasMore:!1}}});function Xj(t){return Iv.parse(JSON.parse(t))}function Ok(t){return JSON.stringify(t)+`
58
- `}var ou,Ik=v(()=>{Un();ou=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
59
- `);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Xj(r)}clear(){this._buffer=void 0}}});import Ak from"node:process";var su,Nk=v(()=>{Ik();su=class{constructor(e=Ak.stdin,r=Ak.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new ou,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=Ok(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var Zk={};Ze(Zk,{PolyglotExecutor:()=>Xo,buildScriptFilename:()=>Fk,buildSpawnOptions:()=>Uk});import{spawn as Qj,execSync as eD,execFileSync as Mk}from"node:child_process";import{mkdtempSync as tD,writeFileSync as zk,rmSync as jk,existsSync as Dk}from"node:fs";import{join as iu,resolve as Lk}from"node:path";import{tmpdir as rD}from"node:os";function Fk(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${nD[t]}`}function Uk(t){return{windowsHide:t==="win32"}}function Vh(t){if(Ht&&t.pid)try{eD(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Ht,nD,oD,Xo,Wh=v(()=>{"use strict";Yi();Ht=process.platform==="win32",nD={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs"};oD=(()=>{if(Ht)return process.env.TEMP??process.env.TMP??rD();try{let t=Mk(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:Lk(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();Xo=class{#e;#t;#n;#s=new Set;constructor(e){this.#e=e?.hardCapBytes??100*1024*1024;let r=e?.projectRoot;typeof r=="function"?this.#t=r:typeof r=="string"?this.#t=()=>r:this.#t=()=>process.cwd(),this.#n=e?.runtimes??so()}get#o(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#s)try{process.kill(Ht?e:-e,"SIGTERM")}catch{}this.#s.clear()}async execute(e){let{language:r,code:n,timeout:o,background:s=!1}=e,i=tD(iu(oD,".ctx-mode-"));try{let a=this.#a(i,n,r),c=e_(this.#n,r,a);if(c[0]==="__rust_compile_run__")return await this.#c(a,i,o);let u=r==="shell"?this.#o:i,l=await this.#i(c,u,i,o,s);if(!l.backgrounded)try{jk(i,{recursive:!0,force:!0})}catch{}return l}catch(a){try{jk(i,{recursive:!0,force:!0})}catch{}throw a}}async executeFile(e){let{path:r,language:n,code:o,timeout:s}=e,i=Lk(this.#o,r),a=this.#l(i,n,o);return this.execute({language:n,code:a,timeout:s})}#a(e,r,n){n==="go"&&!r.includes("package ")&&(r=`package main
71
+ deps: ${r}}`};var mj={keyword:"dependencies",type:"object",schemaType:"object",error:Er.error,code(t){let[e,r]=fj(t);E0(t,e),$0(t,r)}};function fj({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 E0(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,ji.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,ji.checkReportMissingProp)(t,u)}):(r.if((0,sg._)`${c} && (${(0,ji.checkMissingProp)(t,a,o)})`),(0,ji.reportMissingProp)(t,o),r.else())}}Er.validatePropertyDeps=E0;function $0(t,e=t.schema){let{gen:r,data:n,keyword:s,it:o}=t,i=r.name("valid");for(let a in e)(0,pj.alwaysValidSchema)(o,e[a])||(r.if((0,ji.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))}Er.validateSchemaDeps=$0;Er.default=mj});var R0=N(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});var P0=te(),hj=de(),gj={message:"property name must be valid",params:({params:t})=>(0,P0._)`{propertyName: ${t.propertyName}}`},yj={keyword:"propertyNames",type:"object",schemaType:["object","boolean"],error:gj,code(t){let{gen:e,schema:r,data:n,it:s}=t;if((0,hj.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,P0.not)(o),()=>{t.error(!0),s.allErrors||e.break()})}),t.ok(o)}};og.default=yj});var ag=N(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});var du=Gt(),ur=te(),_j=Mr(),pu=de(),xj={message:"must NOT have additional properties",params:({params:t})=>(0,ur._)`{additionalProperty: ${t.additionalProperty}}`},vj={keyword:"additionalProperties",type:["object"],schemaType:["boolean","object"],allowUndefined:!0,trackErrors:!0,error:xj,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,pu.alwaysValidSchema)(i,r))return;let u=(0,du.allSchemaProperties)(n.properties),d=(0,du.allSchemaProperties)(n.patternProperties);l(),t.ok((0,ur._)`${o} === ${_j.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 _=(0,pu.schemaRefOrVal)(i,n.properties,"properties");y=(0,du.isOwnProperty)(e,_,g)}else u.length?y=(0,ur.or)(...u.map(_=>(0,ur._)`${g} === ${_}`)):y=ur.nil;return d.length&&(y=(0,ur.or)(y,...d.map(_=>(0,ur._)`${(0,du.usePattern)(t,_)}.test(${g})`))),(0,ur.not)(y)}function f(g){e.code((0,ur._)`delete ${s}[${g}]`)}function p(g){if(c.removeAdditional==="all"||c.removeAdditional&&r===!1){f(g);return}if(r===!1){t.setParams({additionalProperty:g}),t.error(),a||e.break();return}if(typeof r=="object"&&!(0,pu.alwaysValidSchema)(i,r)){let y=e.name("valid");c.removeAdditional==="failing"?(h(g,y,!1),e.if((0,ur.not)(y),()=>{t.reset(),f(g)})):(h(g,y),a||e.if((0,ur.not)(y),()=>e.break()))}}function h(g,y,_){let x={keyword:"additionalProperties",dataProp:g,dataPropType:pu.Type.Str};_===!1&&Object.assign(x,{compositeRule:!0,createErrors:!1,allErrors:!1}),t.subschema(x,y)}}};ig.default=vj});var I0=N(ug=>{"use strict";Object.defineProperty(ug,"__esModule",{value:!0});var bj=ki(),C0=Gt(),cg=de(),O0=ag(),Sj={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&&O0.default.code(new bj.KeywordCxt(o,O0.default,"additionalProperties"));let i=(0,C0.allSchemaProperties)(r);for(let l of i)o.definedProperties.add(l);o.opts.unevaluated&&i.length&&o.props!==!0&&(o.props=cg.mergeEvaluated.props(e,(0,cg.toHash)(i),o.props));let a=i.filter(l=>!(0,cg.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,C0.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)}}};ug.default=Sj});var M0=N(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var A0=Gt(),mu=te(),N0=de(),D0=de(),kj={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,A0.allSchemaProperties)(r),c=a.filter(h=>(0,N0.alwaysValidSchema)(o,r[h]));if(a.length===0||c.length===a.length&&(!o.opts.unevaluated||o.props===!0))return;let u=i.strictSchema&&!i.allowMatchingProperties&&s.properties,d=e.name("valid");o.props!==!0&&!(o.props instanceof mu.Name)&&(o.props=(0,D0.evaluatedPropsToName)(e,o.props));let{props:l}=o;m();function m(){for(let h of a)u&&f(h),o.allErrors?p(h):(e.var(d,!0),p(h),e.if(d))}function f(h){for(let g in u)new RegExp(h).test(g)&&(0,N0.checkStrictMode)(o,`property ${g} matches pattern ${h} (use allowMatchingProperties)`)}function p(h){e.forIn("key",n,g=>{e.if((0,mu._)`${(0,A0.usePattern)(t,h)}.test(${g})`,()=>{let y=c.includes(h);y||t.subschema({keyword:"patternProperties",schemaProp:h,dataProp:g,dataPropType:D0.Type.Str},d),o.opts.unevaluated&&l!==!0?e.assign((0,mu._)`${l}[${g}]`,!0):!y&&!o.allErrors&&e.if((0,mu.not)(d),()=>e.break())})})}}};lg.default=kj});var j0=N(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});var wj=de(),Ej={keyword:"not",schemaType:["object","boolean"],trackErrors:!0,code(t){let{gen:e,schema:r,it:n}=t;if((0,wj.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"}};dg.default=Ej});var z0=N(pg=>{"use strict";Object.defineProperty(pg,"__esModule",{value:!0});var $j=Gt(),Tj={keyword:"anyOf",schemaType:"array",trackErrors:!0,code:$j.validateUnion,error:{message:"must match a schema in anyOf"}};pg.default=Tj});var L0=N(mg=>{"use strict";Object.defineProperty(mg,"__esModule",{value:!0});var fu=te(),Pj=de(),Rj={message:"must match exactly one schema in oneOf",params:({params:t})=>(0,fu._)`{passingSchemas: ${t.passing}}`},Cj={keyword:"oneOf",schemaType:"array",trackErrors:!0,error:Rj,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,Pj.alwaysValidSchema)(s,d)?e.var(c,!0):m=t.subschema({keyword:"oneOf",schemaProp:l,compositeRule:!0},c),l>0&&e.if((0,fu._)`${c} && ${i}`).assign(i,!1).assign(a,(0,fu._)`[${a}, ${l}]`).else(),e.if(c,()=>{e.assign(i,!0),e.assign(a,l),m&&t.mergeEvaluated(m,fu.Name)})})}}};mg.default=Cj});var F0=N(fg=>{"use strict";Object.defineProperty(fg,"__esModule",{value:!0});var Oj=de(),Ij={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,Oj.alwaysValidSchema)(n,o))return;let a=t.subschema({keyword:"allOf",schemaProp:i},s);t.ok(s),t.mergeEvaluated(a)})}};fg.default=Ij});var Z0=N(hg=>{"use strict";Object.defineProperty(hg,"__esModule",{value:!0});var hu=te(),H0=de(),Aj={message:({params:t})=>(0,hu.str)`must match "${t.ifClause}" schema`,params:({params:t})=>(0,hu._)`{failingKeyword: ${t.ifClause}}`},Nj={keyword:"if",schemaType:["object","boolean"],trackErrors:!0,error:Aj,code(t){let{gen:e,parentSchema:r,it:n}=t;r.then===void 0&&r.else===void 0&&(0,H0.checkStrictMode)(n,'"if" without "then" and "else" is ignored');let s=U0(n,"then"),o=U0(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,hu.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,hu._)`${d}`):t.setParams({ifClause:d})}}}};function U0(t,e){let r=t.schema[e];return r!==void 0&&!(0,H0.alwaysValidSchema)(t,r)}hg.default=Nj});var B0=N(gg=>{"use strict";Object.defineProperty(gg,"__esModule",{value:!0});var Dj=de(),Mj={keyword:["then","else"],schemaType:["object","boolean"],code({keyword:t,parentSchema:e,it:r}){e.if===void 0&&(0,Dj.checkStrictMode)(r,`"${t}" without "if" is ignored`)}};gg.default=Mj});var q0=N(yg=>{"use strict";Object.defineProperty(yg,"__esModule",{value:!0});var jj=Qh(),zj=b0(),Lj=eg(),Fj=k0(),Uj=w0(),Hj=T0(),Zj=R0(),Bj=ag(),qj=I0(),Vj=M0(),Wj=j0(),Gj=z0(),Kj=L0(),Jj=F0(),Yj=Z0(),Xj=B0();function Qj(t=!1){let e=[Wj.default,Gj.default,Kj.default,Jj.default,Yj.default,Xj.default,Zj.default,Bj.default,Hj.default,qj.default,Vj.default];return t?e.push(zj.default,Fj.default):e.push(jj.default,Lj.default),e.push(Uj.default),e}yg.default=Qj});var V0=N(_g=>{"use strict";Object.defineProperty(_g,"__esModule",{value:!0});var Ue=te(),ez={message:({schemaCode:t})=>(0,Ue.str)`must match format "${t}"`,params:({schemaCode:t})=>(0,Ue._)`{format: ${t}}`},tz={keyword:"format",type:["number","string"],schemaType:"string",$data:!0,error:ez,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():f();function m(){let p=r.scopeValue("formats",{ref:l.formats,code:c.code.formats}),h=r.const("fDef",(0,Ue._)`${p}[${i}]`),g=r.let("fType"),y=r.let("format");r.if((0,Ue._)`typeof ${h} == "object" && !(${h} instanceof RegExp)`,()=>r.assign(g,(0,Ue._)`${h}.type || "string"`).assign(y,(0,Ue._)`${h}.validate`),()=>r.assign(g,(0,Ue._)`"string"`).assign(y,h)),t.fail$data((0,Ue.or)(_(),x()));function _(){return c.strictSchema===!1?Ue.nil:(0,Ue._)`${i} && !${y}`}function x(){let S=d.$async?(0,Ue._)`(${h}.async ? await ${y}(${n}) : ${y}(${n}))`:(0,Ue._)`${y}(${n})`,w=(0,Ue._)`(typeof ${y} == "function" ? ${S} : ${y}.test(${n}))`;return(0,Ue._)`${y} && ${y} !== true && ${g} === ${e} && !${w}`}}function f(){let p=l.formats[o];if(!p){_();return}if(p===!0)return;let[h,g,y]=x(p);h===e&&t.pass(S());function _(){if(c.strictSchema===!1){l.logger.warn(w());return}throw new Error(w());function w(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function x(w){let I=w instanceof RegExp?(0,Ue.regexpCode)(w):c.code.formats?(0,Ue._)`${c.code.formats}${(0,Ue.getProperty)(o)}`:void 0,O=r.scopeValue("formats",{key:o,ref:w,code:I});return typeof w=="object"&&!(w instanceof RegExp)?[w.type||"string",w.validate,(0,Ue._)`${O}.validate`]:["string",w,O]}function S(){if(typeof p=="object"&&!(p instanceof RegExp)&&p.async){if(!d.$async)throw new Error("async format in sync schema");return(0,Ue._)`await ${y}(${n})`}return typeof g=="function"?(0,Ue._)`${y}(${n})`:(0,Ue._)`${y}.test(${n})`}}}};_g.default=tz});var W0=N(xg=>{"use strict";Object.defineProperty(xg,"__esModule",{value:!0});var rz=V0(),nz=[rz.default];xg.default=nz});var G0=N(so=>{"use strict";Object.defineProperty(so,"__esModule",{value:!0});so.contentVocabulary=so.metadataVocabulary=void 0;so.metadataVocabulary=["title","description","default","deprecated","readOnly","writeOnly","examples"];so.contentVocabulary=["contentMediaType","contentEncoding","contentSchema"]});var J0=N(vg=>{"use strict";Object.defineProperty(vg,"__esModule",{value:!0});var sz=n0(),oz=y0(),iz=q0(),az=W0(),K0=G0(),cz=[sz.default,oz.default,(0,iz.default)(),az.default,K0.metadataVocabulary,K0.contentVocabulary];vg.default=cz});var X0=N(gu=>{"use strict";Object.defineProperty(gu,"__esModule",{value:!0});gu.DiscrError=void 0;var Y0;(function(t){t.Tag="tag",t.Mapping="mapping"})(Y0||(gu.DiscrError=Y0={}))});var ew=N(Sg=>{"use strict";Object.defineProperty(Sg,"__esModule",{value:!0});var oo=te(),bg=X0(),Q0=Xc(),uz=wi(),lz=de(),dz={message:({params:{discrError:t,tagName:e}})=>t===bg.DiscrError.Tag?`tag "${e}" must be string`:`value of tag "${e}" must be in oneOf`,params:({params:{discrError:t,tag:e,tagName:r}})=>(0,oo._)`{error: ${t}, tag: ${r}, tagValue: ${e}}`},pz={keyword:"discriminator",type:"object",schemaType:"object",error:dz,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,oo._)`${r}${(0,oo.getProperty)(a)}`);e.if((0,oo._)`typeof ${u} == "string"`,()=>d(),()=>t.error(!1,{discrError:bg.DiscrError.Tag,tag:u,tagName:a})),t.ok(c);function d(){let f=m();e.if(!1);for(let p in f)e.elseIf((0,oo._)`${u} === ${p}`),e.assign(c,l(f[p]));e.else(),t.error(!1,{discrError:bg.DiscrError.Mapping,tag:u,tagName:a}),e.endIf()}function l(f){let p=e.name("valid"),h=t.subschema({keyword:"oneOf",schemaProp:f},p);return t.mergeEvaluated(h,oo.Name),p}function m(){var f;let p={},h=y(s),g=!0;for(let S=0;S<i.length;S++){let w=i[S];if(w?.$ref&&!(0,lz.schemaHasRulesButRef)(w,o.self.RULES)){let O=w.$ref;if(w=Q0.resolveRef.call(o.self,o.schemaEnv.root,o.baseId,O),w instanceof Q0.SchemaEnv&&(w=w.schema),w===void 0)throw new uz.default(o.opts.uriResolver,o.baseId,O)}let I=(f=w?.properties)===null||f===void 0?void 0:f[a];if(typeof I!="object")throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${a}"`);g=g&&(h||y(w)),_(I,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 _(S,w){if(S.const)x(S.const,w);else if(S.enum)for(let I of S.enum)x(I,w);else throw new Error(`discriminator: "properties/${a}" must have "const" or "enum"`)}function x(S,w){if(typeof S!="string"||S in p)throw new Error(`discriminator: "${a}" values must be unique strings`);p[S]=w}}}};Sg.default=pz});var tw=N((M6,mz)=>{mz.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 wg=N((Re,kg)=>{"use strict";Object.defineProperty(Re,"__esModule",{value:!0});Re.MissingRefError=Re.ValidationError=Re.CodeGen=Re.Name=Re.nil=Re.stringify=Re.str=Re._=Re.KeywordCxt=Re.Ajv=void 0;var fz=Yk(),hz=J0(),gz=ew(),rw=tw(),yz=["/properties"],yu="http://json-schema.org/draft-07/schema",io=class extends fz.default{_addVocabularies(){super._addVocabularies(),hz.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(gz.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(rw,yz):rw;this.addMetaSchema(e,yu,!1),this.refs["http://json-schema.org/schema"]=yu}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(yu)?yu:void 0)}};Re.Ajv=io;kg.exports=Re=io;kg.exports.Ajv=io;Object.defineProperty(Re,"__esModule",{value:!0});Re.default=io;var _z=ki();Object.defineProperty(Re,"KeywordCxt",{enumerable:!0,get:function(){return _z.KeywordCxt}});var ao=te();Object.defineProperty(Re,"_",{enumerable:!0,get:function(){return ao._}});Object.defineProperty(Re,"str",{enumerable:!0,get:function(){return ao.str}});Object.defineProperty(Re,"stringify",{enumerable:!0,get:function(){return ao.stringify}});Object.defineProperty(Re,"nil",{enumerable:!0,get:function(){return ao.nil}});Object.defineProperty(Re,"Name",{enumerable:!0,get:function(){return ao.Name}});Object.defineProperty(Re,"CodeGen",{enumerable:!0,get:function(){return ao.CodeGen}});var xz=Jc();Object.defineProperty(Re,"ValidationError",{enumerable:!0,get:function(){return xz.default}});var vz=wi();Object.defineProperty(Re,"MissingRefError",{enumerable:!0,get:function(){return vz.default}})});var lw=N(Tr=>{"use strict";Object.defineProperty(Tr,"__esModule",{value:!0});Tr.formatNames=Tr.fastFormats=Tr.fullFormats=void 0;function $r(t,e){return{validate:t,compare:e}}Tr.fullFormats={date:$r(iw,Pg),time:$r($g(!0),Rg),"date-time":$r(nw(!0),cw),"iso-time":$r($g(),aw),"iso-date-time":$r(nw(),uw),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:$z,"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:Az,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:Tz,int32:{type:"number",validate:Cz},int64:{type:"number",validate:Oz},float:{type:"number",validate:ow},double:{type:"number",validate:ow},password:!0,binary:!0};Tr.fastFormats={...Tr.fullFormats,date:$r(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,Pg),time:$r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,Rg),"date-time":$r(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,cw),"iso-time":$r(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,aw),"iso-date-time":$r(/^\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,uw),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};Tr.formatNames=Object.keys(Tr.fullFormats);function bz(t){return t%4===0&&(t%100!==0||t%400===0)}var Sz=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,kz=[0,31,28,31,30,31,30,31,31,30,31,30,31];function iw(t){let e=Sz.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&&bz(r)?29:kz[n])}function Pg(t,e){if(t&&e)return t>e?1:t<e?-1:0}var Eg=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function $g(t){return function(r){let n=Eg.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 Rg(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 aw(t,e){if(!(t&&e))return;let r=Eg.exec(t),n=Eg.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 Tg=/t|\s/i;function nw(t){let e=$g(t);return function(n){let s=n.split(Tg);return s.length===2&&iw(s[0])&&e(s[1])}}function cw(t,e){if(!(t&&e))return;let r=new Date(t).valueOf(),n=new Date(e).valueOf();if(r&&n)return r-n}function uw(t,e){if(!(t&&e))return;let[r,n]=t.split(Tg),[s,o]=e.split(Tg),i=Pg(r,s);if(i!==void 0)return i||Rg(n,o)}var wz=/\/|:/,Ez=/^(?:[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 $z(t){return wz.test(t)&&Ez.test(t)}var sw=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function Tz(t){return sw.lastIndex=0,sw.test(t)}var Pz=-(2**31),Rz=2**31-1;function Cz(t){return Number.isInteger(t)&&t<=Rz&&t>=Pz}function Oz(t){return Number.isInteger(t)}function ow(){return!0}var Iz=/[^\\]\\Z/;function Az(t){if(Iz.test(t))return!1;try{return new RegExp(t),!0}catch{return!1}}});var dw=N(co=>{"use strict";Object.defineProperty(co,"__esModule",{value:!0});co.formatLimitDefinition=void 0;var Nz=wg(),lr=te(),gn=lr.operators,_u={formatMaximum:{okStr:"<=",ok:gn.LTE,fail:gn.GT},formatMinimum:{okStr:">=",ok:gn.GTE,fail:gn.LT},formatExclusiveMaximum:{okStr:"<",ok:gn.LT,fail:gn.GTE},formatExclusiveMinimum:{okStr:">",ok:gn.GT,fail:gn.LTE}},Dz={message:({keyword:t,schemaCode:e})=>(0,lr.str)`should be ${_u[t].okStr} ${e}`,params:({keyword:t,schemaCode:e})=>(0,lr._)`{comparison: ${_u[t].okStr}, limit: ${e}}`};co.formatLimitDefinition={keyword:Object.keys(_u),type:"string",schemaType:"string",$data:!0,error:Dz,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 Nz.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}),f=e.const("fmt",(0,lr._)`${m}[${c.schemaCode}]`);t.fail$data((0,lr.or)((0,lr._)`typeof ${f} != "object"`,(0,lr._)`${f} instanceof RegExp`,(0,lr._)`typeof ${f}.compare != "function"`,l(f)))}function d(){let m=c.schema,f=a.formats[m];if(!f||f===!0)return;if(typeof f!="object"||f instanceof RegExp||typeof f.compare!="function")throw new Error(`"${s}": format "${m}" does not define "compare" function`);let p=e.scopeValue("formats",{key:m,ref:f,code:i.code.formats?(0,lr._)`${i.code.formats}${(0,lr.getProperty)(m)}`:void 0});t.fail$data(l(p))}function l(m){return(0,lr._)`${m}.compare(${r}, ${n}) ${_u[s].fail} 0`}},dependencies:["format"]};var Mz=t=>(t.addKeyword(co.formatLimitDefinition),t);co.default=Mz});var hw=N((zi,fw)=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});var uo=lw(),jz=dw(),Cg=te(),pw=new Cg.Name("fullFormats"),zz=new Cg.Name("fastFormats"),Og=(t,e={keywords:!0})=>{if(Array.isArray(e))return mw(t,e,uo.fullFormats,pw),t;let[r,n]=e.mode==="fast"?[uo.fastFormats,zz]:[uo.fullFormats,pw],s=e.formats||uo.formatNames;return mw(t,s,r,n),e.keywords&&(0,jz.default)(t),t};Og.get=(t,e="full")=>{let n=(e==="fast"?uo.fastFormats:uo.fullFormats)[t];if(!n)throw new Error(`Unknown format "${t}"`);return n};function mw(t,e,r,n){var s,o;(s=(o=t.opts.code).formats)!==null&&s!==void 0||(o.formats=(0,Cg._)`require("ajv-formats/dist/formats").${n}`);for(let i of e)t.addFormat(i,r[i])}fw.exports=zi=Og;Object.defineProperty(zi,"__esModule",{value:!0});zi.default=Og});function Lz(){let t=new gw.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,yw.default)(t),t}var gw,yw,xu,_w=v(()=>{gw=wo(wg(),1),yw=wo(hw(),1);xu=class{constructor(e){this._ajv=e??Lz()}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 vu,xw=v(()=>{Yn();vu=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},ci,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},Vs,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 vw(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 bw(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 Sw=v(()=>{});var bu,kw=v(()=>{CS();Yn();_w();Jo();xw();Sw();bu=class extends jc{constructor(e,r){super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(ai.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 xu,this.setRequestHandler(qm,n=>this._oninitialize(n)),this.setNotificationHandler(Vm,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Qm,async(n,s)=>{let o=s.sessionId||s.requestInfo?.headers["mcp-session-id"]||void 0,{level:i}=n.params,a=ai.safeParse(i);return a.success&&this._loggingLevels.set(o,a.data),{}})}get experimental(){return this._experimental||(this._experimental={tasks:new vu(this)}),this._experimental}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=RS(this._capabilities,e)}setRequestHandler(e,r){let s=sn(e)?.method;if(!s)throw new Error("Schema is missing a method literal");let o;if(Zt(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=nn(qs,c);if(!d.success){let p=d.error instanceof Error?d.error.message:String(d.error);throw new L(q.InvalidParams,`Invalid tools/call request: ${p}`)}let{params:l}=d.data,m=await Promise.resolve(r(c,u));if(l.task){let p=nn(Fs,m);if(!p.success){let h=p.error instanceof Error?p.error.message:String(p.error);throw new L(q.InvalidParams,`Invalid task creation result: ${h}`)}return p.data}let f=nn(Ec,m);if(!f.success){let p=f.error instanceof Error?f.error.message:String(f.error);throw new L(q.InvalidParams,`Invalid tools/call result: ${p}`)}return f.data};return super.setRequestHandler(e,a)}return super.setRequestHandler(e,r)}assertCapabilityForMethod(e){switch(e){case"sampling/createMessage":if(!this._clientCapabilities?.sampling)throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!this._clientCapabilities?.elicitation)throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!this._clientCapabilities?.roots)throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/elicitation/complete":if(!this._clientCapabilities?.elicitation?.url)throw new Error(`Client does not support URL elicitation (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case"completion/complete":if(!this._capabilities.completions)throw new Error(`Server does not support completions (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":if(!this._capabilities.resources)throw new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"tasks/get":case"tasks/list":case"tasks/result":case"tasks/cancel":if(!this._capabilities.tasks)throw new Error(`Server does not support tasks capability (required for ${e})`);break;case"ping":case"initialize":break}}assertTaskCapability(e){bw(this._clientCapabilities?.tasks?.requests,e,"Client")}assertTaskHandlerCapability(e){this._capabilities&&vw(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:Rb.includes(r)?r:Fm,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"},pc)}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},ef,r):this.request({method:"sampling/createMessage",params:e},ci,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},Vs,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},Vs,r);if(o.action==="accept"&&o.content&&s.requestedSchema)try{let a=this._jsonSchemaValidator.getValidator(s.requestedSchema)(o.content);if(!a.valid)throw new L(q.InvalidParams,`Elicitation response content does not match requested schema: ${a.errorMessage}`)}catch(i){throw i instanceof L?i:new L(q.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},tf,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 Ig(t){return!!t&&typeof t=="object"&&Ew in t}function $w(t){return t[Ew]?.complete}var Ew,ww,Tw=v(()=>{Ew=Symbol.for("mcp.completable");(function(t){t.Completable="McpCompletable"})(ww||(ww={}))});var Pw=v(()=>{});function Uz(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"),!Fz.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 Hz(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 Ag(t){let e=Uz(t);return Hz(t,e.warnings),e.isValid}var Fz,Rw=v(()=>{Fz=/^[A-Za-z0-9._-]{1,128}$/});var Su,Cw=v(()=>{Su=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 Ng=v(()=>{Ma();Ma()});function Aw(t){return t!==null&&typeof t=="object"&&"parse"in t&&typeof t.parse=="function"&&"safeParse"in t&&typeof t.safeParse=="function"}function Nw(t){return"_def"in t||"_zod"in t||Aw(t)}function Dg(t){return typeof t!="object"||t===null||Nw(t)?!1:Object.keys(t).length===0?!0:Object.values(t).some(Aw)}function Ow(t){if(t){if(Dg(t))return Jn(t);if(!Nw(t))throw new Error("inputSchema must be a Zod schema or raw shape, received an unrecognized object");return t}}function Bz(t){let e=sn(t);return e?Object.entries(e).map(([r,n])=>{let s=eb(n),o=tb(n);return{name:r,description:s,required:!o}}):[]}function yn(t){let r=sn(t)?.method;if(!r)throw new Error("Schema is missing a method literal");let n=ic(r);if(typeof n=="string")return n;throw new Error("Schema method literal must be a string")}function Iw(t){return{completion:{values:t.slice(0,100),total:t.length,hasMore:t.length>100}}}var ku,Zz,Li,Dw=v(()=>{kw();Jo();Lf();Yn();Tw();Pw();Rw();Cw();Ng();ku=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 bu(e,r)}get experimental(){return this._experimental||(this._experimental={tasks:new Su(this)}),this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(wc)),this.server.assertCanSetRequestHandler(yn(qs)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(wc,()=>({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=zs(r.inputSchema);return s?Mf(s,{strictUnions:!0,pipeStrategy:"input"}):Zz})(),annotations:r.annotations,execution:r.execution,_meta:r._meta};if(r.outputSchema){let s=zs(r.outputSchema);s&&(n.outputSchema=Mf(s,{strictUnions:!0,pipeStrategy:"output"}))}return n})})),this.server.setRequestHandler(qs,async(e,r)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new L(q.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new L(q.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 L(q.InternalError,`Tool ${e.params.name} has taskSupport '${o}' but was not registered with registerToolTask`);if(o==="required"&&!s)throw new L(q.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 L&&n.code===q.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=zs(e.inputSchema)??e.inputSchema,i=await sc(o,r);if(!i.success){let a="error"in i?i.error:"Unknown error",c=oc(a);throw new L(q.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 L(q.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let s=zs(e.outputSchema),o=await sc(s,r.structuredContent);if(!o.success){let i="error"in o?o.error:"Unknown error",a=oc(i);throw new L(q.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 L(q.InternalError,`Task ${c} not found during polling`);u=l}return await n.taskStore.getTaskResult(c)}setCompletionRequestHandler(){this._completionHandlerInitialized||(this.server.assertCanSetRequestHandler(yn($c)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler($c,async e=>{switch(e.params.ref.type){case"ref/prompt":return qb(e),this.handlePromptCompletion(e,e.params.ref);case"ref/resource":return Vb(e),this.handleResourceCompletion(e,e.params.ref);default:throw new L(q.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),this._completionHandlerInitialized=!0)}async handlePromptCompletion(e,r){let n=this._registeredPrompts[r.name];if(!n)throw new L(q.InvalidParams,`Prompt ${r.name} not found`);if(!n.enabled)throw new L(q.InvalidParams,`Prompt ${r.name} disabled`);if(!n.argsSchema)return Li;let o=sn(n.argsSchema)?.[e.params.argument.name];if(!Ig(o))return Li;let i=$w(o);if(!i)return Li;let a=await i(e.params.argument.value,e.params.context);return Iw(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 Li;throw new L(q.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let s=n.resourceTemplate.completeCallback(e.params.argument.name);if(!s)return Li;let o=await s(e.params.argument.value,e.params.context);return Iw(o)}setResourceRequestHandlers(){this._resourceHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(Hs)),this.server.assertCanSetRequestHandler(yn(Zs)),this.server.assertCanSetRequestHandler(yn(Sc)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(Hs,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(Zs,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([r,n])=>({name:r,uriTemplate:n.resourceTemplate.uriTemplate.toString(),...n.metadata}))})),this.server.setRequestHandler(Sc,async(e,r)=>{let n=new URL(e.params.uri),s=this._registeredResources[n.toString()];if(s){if(!s.enabled)throw new L(q.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 L(q.InvalidParams,`Resource ${n} not found`)}),this._resourceHandlersInitialized=!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||(this.server.assertCanSetRequestHandler(yn(Bs)),this.server.assertCanSetRequestHandler(yn(kc)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Bs,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,r])=>({name:e,title:r.title,description:r.description,arguments:r.argsSchema?Bz(r.argsSchema):void 0}))})),this.server.setRequestHandler(kc,async(e,r)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new L(q.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new L(q.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let s=zs(n.argsSchema),o=await sc(s,e.params.arguments);if(!o.success){let c="error"in o?o.error:"Unknown error",u=oc(c);throw new L(q.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:Jn(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=Jn(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 xt?c._def?.innerType:c;return Ig(u)})&&this.setCompletionRequestHandler(),i}_createRegisteredTool(e,r,n,s,o,i,a,c,u){Ag(e);let d={title:r,description:n,inputSchema:Ow(s),outputSchema:Ow(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"&&Ag(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=Jn(l.paramsSchema)),typeof l.outputSchema<"u"&&(d.outputSchema=Jn(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(Dg(c))s=r.shift(),r.length>1&&typeof r[0]=="object"&&r[0]!==null&&!Dg(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()}},Zz={type:"object",properties:{}};Li={completion:{values:[],hasMore:!1}}});function qz(t){return jb.parse(JSON.parse(t))}function Mw(t){return JSON.stringify(t)+`
72
+ `}var wu,jw=v(()=>{Yn();wu=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),qz(r)}clear(){this._buffer=void 0}}});import zw from"node:process";var Eu,Lw=v(()=>{jw();Eu=class{constructor(e=zw.stdin,r=zw.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new wu,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=Mw(e);this._stdout.write(n)?r():this._stdout.once("drain",r)})}}});var Gw={};Le(Gw,{PolyglotExecutor:()=>lo,buildScriptFilename:()=>qw,buildShellScriptContent:()=>Ww,buildSpawnOptions:()=>Vw});import{spawn as Vz,execSync as Wz,execFileSync as Zw}from"node:child_process";import{mkdtempSync as Gz,writeFileSync as Fw,rmSync as Uw,existsSync as Hw}from"node:fs";import{join as $u,resolve as Bw}from"node:path";import{tmpdir as Kz}from"node:os";function qw(t,e,r){if(e==="win32"&&t==="shell"){let n=r?.toLowerCase()??"";return n.includes("powershell")||n.includes("pwsh")?"script.ps1":"script"}return`script.${Jz[t]}`}function Vw(t){return{windowsHide:t==="win32"}}function Yz(t){return`'${t.replace(/'/g,"'\\''")}'`}function Ww(t,e,r){return r==="win32"||!e?t:`export PATH=${Yz(e)}
74
+ ${t}`}function Mg(t){if(Yt&&t.pid)try{Wz(`taskkill /F /T /PID ${t.pid}`,{stdio:"pipe"})}catch{}else if(t.pid)try{process.kill(-t.pid,"SIGKILL")}catch{}}var Yt,Jz,Xz,lo,jg=v(()=>{"use strict";fa();Yt=process.platform==="win32",Jz={javascript:"js",typescript:"ts",python:"py",shell:"sh",ruby:"rb",go:"go",rust:"rs",php:"php",perl:"pl",r:"R",elixir:"exs"};Xz=(()=>{if(Yt)return process.env.TEMP??process.env.TMP??Kz();try{let t=Zw(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:Bw(t,"..");if(e&&e!==process.cwd())return e}catch{}return"/tmp"})();lo=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??gs()}get#s(){return this.#t()}get runtimes(){return{...this.#n}}cleanupBackgrounded(){for(let e of this.#o)try{process.kill(Yt?e:-e,"SIGTERM")}catch{}this.#o.clear()}async execute(e){let{language:r,code:n,timeout:s,background:o=!1}=e,i=Gz($u(Xz,".ctx-mode-"));try{let a=this.#a(i,n,r),c=Xy(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{Uw(i,{recursive:!0,force:!0})}catch{}return d}catch(a){try{Uw(i,{recursive:!0,force:!0})}catch{}throw a}}async executeFile(e){let{path:r,language:n,code:s,timeout:o}=e,i=Bw(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
60
75
 
61
76
  import "fmt"
62
77
 
@@ -64,22 +79,22 @@ func main() {
64
79
  ${r}
65
80
  }
66
81
  `),n==="php"&&!r.trimStart().startsWith("<?")&&(r=`<?php
67
- ${r}`),n==="elixir"&&Dk(iu(this.#o,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify(iu(this.#o,"_build/dev/lib"))}, "*/ebin"))
82
+ ${r}`),n==="elixir"&&Hw($u(this.#s,"mix.exs"))&&(r=`Path.wildcard(Path.join(${JSON.stringify($u(this.#s,"_build/dev/lib"))}, "*/ebin"))
68
83
  |> Enum.each(&Code.prepend_path/1)
69
84
 
70
- ${r}`);let o=iu(e,Fk(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?zk(o,r,{encoding:"utf-8",mode:448}):zk(o,r,"utf-8"),o}async#c(e,r,n){let o=Ht?".exe":"",s=e.replace(/\.rs$/,"")+o;try{Mk("rustc",[e,"-o",s],{cwd:r,timeout:n===void 0?6e4:Math.min(n,6e4),encoding:"utf-8",stdio:["pipe","pipe","pipe"]})}catch(i){return{stdout:"",stderr:`Compilation failed:
71
- ${i instanceof Error?i.stderr||i.message:String(i)}`,exitCode:1,timedOut:!1}}return this.#i([s],r,r,n)}async#i(e,r,n,o,s=!1){return new Promise(i=>{let a=Ht&&["tsx","ts-node","elixir"].includes(e[0]),c=e[0],u;Ht&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Ht?e.slice(1).map(_=>_.replace(/\\/g,"/")):e.slice(1);let l=Qj(c,u,{cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),shell:a,detached:!Ht,...Uk(process.platform)}),d=!1,p=!1,f=o===void 0?void 0:setTimeout(()=>{if(d=!0,s){p=!0,l.pid&&this.#s.add(l.pid),l.unref(),l.stdout.destroy(),l.stderr.destroy();let _=Buffer.concat(m).toString("utf-8"),x=Buffer.concat(h).toString("utf-8");i({stdout:_,stderr:x,exitCode:0,timedOut:!0,backgrounded:!0})}else Vh(l)},o),m=[],h=[],g=0,y=!1;l.stdout.on("data",_=>{g+=_.length,g<=this.#e?m.push(_):y||(y=!0,Vh(l))}),l.stderr.on("data",_=>{g+=_.length,g<=this.#e?h.push(_):y||(y=!0,Vh(l))}),l.on("close",_=>{if(clearTimeout(f),p)return;let x=Buffer.concat(m).toString("utf-8"),k=Buffer.concat(h).toString("utf-8");y&&(k+=`
72
- [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:x,stderr:k,exitCode:d?1:_??1,timedOut:d})}),l.on("error",_=>{clearTimeout(f),!p&&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","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),o={};for(let[s,i]of Object.entries(process.env))i!==void 0&&!n.has(s)&&!s.startsWith("BASH_FUNC_")&&(o[s]=i);if(o.TMPDIR=e,o.HOME=r,o.LANG="en_US.UTF-8",o.PYTHONDONTWRITEBYTECODE="1",o.PYTHONUNBUFFERED="1",o.PYTHONUTF8="1",o.NO_COLOR="1",Ht&&!o.PATH&&o.Path&&(o.PATH=o.Path,delete o.Path),o.PATH||(o.PATH=Ht?"":"/usr/local/bin:/usr/bin:/bin"),Ht){o.MSYS_NO_PATHCONV="1",o.MSYS2_ARG_CONV_EXCL="*";let s="C:\\Program Files\\Git\\usr\\bin",i="C:\\Program Files\\Git\\bin";o.PATH.includes(s)||(o.PATH=`${s};${i};${o.PATH}`)}if(!o.SSL_CERT_FILE){let s=Ht?[]:["/etc/ssl/cert.pem","/etc/ssl/certs/ca-certificates.crt","/etc/pki/tls/certs/ca-bundle.crt","/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"];for(let i of s)if(Dk(i)){o.SSL_CERT_FILE=i;break}}return o}#l(e,r,n){let o=JSON.stringify(e);switch(r){case"javascript":case"typescript":return`const FILE_CONTENT_PATH = ${o};
85
+ ${r}`);let s=$u(e,qw(n,process.platform,n==="shell"?this.#n.shell:null));return n==="shell"?Fw(s,Ww(r,process.env.PATH,process.platform),{encoding:"utf-8",mode:448}):Fw(s,r,"utf-8"),s}async#c(e,r,n){let s=Yt?".exe":"",o=e.replace(/\.rs$/,"")+s;try{Zw("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=Yt&&["tsx","ts-node","elixir","bun"].includes(e[0]),c=e[0],u;Yt&&e.length===2&&e[1]?u=[e[1].replace(/\\/g,"/")]:u=Yt?e.slice(1).map(_=>_.replace(/\\/g,"/")):e.slice(1);let d=Vz(c,u,{cwd:r,stdio:["ignore","pipe","pipe"],env:this.#u(n),shell:a,detached:!Yt,...Vw(process.platform)}),l=!1,m=!1,f=s===void 0?void 0:setTimeout(()=>{if(l=!0,o){m=!0,d.pid&&this.#o.add(d.pid),d.unref(),d.stdout.destroy(),d.stderr.destroy();let _=Buffer.concat(p).toString("utf-8"),x=Buffer.concat(h).toString("utf-8");i({stdout:_,stderr:x,exitCode:0,timedOut:!0,backgrounded:!0})}else Mg(d)},s),p=[],h=[],g=0,y=!1;d.stdout.on("data",_=>{g+=_.length,g<=this.#e?p.push(_):y||(y=!0,Mg(d))}),d.stderr.on("data",_=>{g+=_.length,g<=this.#e?h.push(_):y||(y=!0,Mg(d))}),d.on("close",_=>{if(clearTimeout(f),m)return;let x=Buffer.concat(p).toString("utf-8"),S=Buffer.concat(h).toString("utf-8");y&&(S+=`
87
+ [output capped at ${(this.#e/1024/1024).toFixed(0)}MB \u2014 process killed]`),i({stdout:x,stderr:S,exitCode:l?1:_??1,timedOut:l})}),d.on("error",_=>{clearTimeout(f),!m&&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","LD_PRELOAD","DYLD_INSERT_LIBRARIES","OPENSSL_CONF","OPENSSL_ENGINES","CC","CXX","AR","GIT_TEMPLATE_DIR","GIT_CONFIG_GLOBAL","GIT_CONFIG_SYSTEM","GIT_EXEC_PATH","GIT_SSH","GIT_SSH_COMMAND","GIT_ASKPASS"]),s={};for(let[o,i]of Object.entries(process.env))i!==void 0&&!n.has(o)&&!o.startsWith("BASH_FUNC_")&&(s[o]=i);if(s.TMPDIR=e,s.HOME=r,s.LANG="en_US.UTF-8",s.PYTHONDONTWRITEBYTECODE="1",s.PYTHONUNBUFFERED="1",s.PYTHONUTF8="1",s.NO_COLOR="1",Yt&&!s.PATH&&s.Path&&(s.PATH=s.Path,delete s.Path),s.PATH||(s.PATH=Yt?"":"/usr/local/bin:/usr/bin:/bin"),Yt){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=Yt?[]:["/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(Hw(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};
73
88
  const file_path = FILE_CONTENT_PATH;
74
89
  const FILE_CONTENT = require("fs").readFileSync(FILE_CONTENT_PATH, "utf-8");
75
- ${n}`;case"python":return`FILE_CONTENT_PATH = ${o}
90
+ ${n}`;case"python":return`FILE_CONTENT_PATH = ${s}
76
91
  file_path = FILE_CONTENT_PATH
77
92
  with open(FILE_CONTENT_PATH, "r", encoding="utf-8") as _f:
78
93
  FILE_CONTENT = _f.read()
79
- ${n}`;case"shell":{let s="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${s}
80
- file_path=${s}
81
- FILE_CONTENT=$(cat ${s})
82
- ${n}`}case"ruby":return`FILE_CONTENT_PATH = ${o}
94
+ ${n}`;case"shell":{let o="'"+e.replace(/'/g,"'\\''")+"'";return`FILE_CONTENT_PATH=${o}
95
+ file_path=${o}
96
+ FILE_CONTENT=$(cat ${o})
97
+ ${n}`}case"ruby":return`FILE_CONTENT_PATH = ${s}
83
98
  file_path = FILE_CONTENT_PATH
84
99
  FILE_CONTENT = File.read(FILE_CONTENT_PATH, encoding: "utf-8")
85
100
  ${n}`;case"go":return`package main
@@ -89,7 +104,7 @@ import (
89
104
  "os"
90
105
  )
91
106
 
92
- var FILE_CONTENT_PATH = ${o}
107
+ var FILE_CONTENT_PATH = ${s}
93
108
  var file_path = FILE_CONTENT_PATH
94
109
 
95
110
  func main() {
@@ -103,28 +118,28 @@ ${n}
103
118
  use std::fs;
104
119
 
105
120
  fn main() {
106
- let file_content_path = ${o};
121
+ let file_content_path = ${s};
107
122
  let file_path = file_content_path;
108
123
  let file_content = fs::read_to_string(file_content_path).unwrap();
109
124
  ${n}
110
125
  }
111
126
  `;case"php":return`<?php
112
- $FILE_CONTENT_PATH = ${o};
127
+ $FILE_CONTENT_PATH = ${s};
113
128
  $file_path = $FILE_CONTENT_PATH;
114
129
  $FILE_CONTENT = file_get_contents($FILE_CONTENT_PATH);
115
- ${n}`;case"perl":return`my $FILE_CONTENT_PATH = ${o};
130
+ ${n}`;case"perl":return`my $FILE_CONTENT_PATH = ${s};
116
131
  my $file_path = $FILE_CONTENT_PATH;
117
132
  open(my $fh, '<:encoding(UTF-8)', $FILE_CONTENT_PATH) or die "Cannot open: $!";
118
133
  my $FILE_CONTENT = do { local $/; <$fh> };
119
134
  close($fh);
120
- ${n}`;case"r":return`FILE_CONTENT_PATH <- ${o}
135
+ ${n}`;case"r":return`FILE_CONTENT_PATH <- ${s}
121
136
  file_path <- FILE_CONTENT_PATH
122
137
  FILE_CONTENT <- readLines(FILE_CONTENT_PATH, warn=FALSE, encoding="UTF-8")
123
138
  FILE_CONTENT <- paste(FILE_CONTENT, collapse="\\n")
124
- ${n}`;case"elixir":return`file_content_path = ${o}
139
+ ${n}`;case"elixir":return`file_content_path = ${s}
125
140
  file_path = file_content_path
126
141
  file_content = File.read!(file_content_path)
127
- ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrency:r,capByCpuCount:n=!1,onSettled:o}=e;if(t.length===0)return{settled:[],effectiveConcurrency:0,capped:!1};let s=Math.max(1,r),i=n?Math.max(1,sD().length):s,a=Math.min(s,i,t.length),c=a<s,u=new Array(t.length),l=0;async function d(){for(;;){let f=l++;if(f>=t.length)return;try{let m=await t[f].run();u[f]={status:"fulfilled",value:m}}catch(m){u[f]={status:"rejected",reason:m}}o?.(f,u[f])}}let p=[];for(let f=0;f<a;f++)p.push(d());return await Promise.allSettled(p),{settled:u,effectiveConcurrency:a,capped:c}}var Hk=v(()=>{"use strict"});var Vk={};Ze(Vk,{BunSQLiteAdapter:()=>au,NodeSQLiteAdapter:()=>cu,SQLiteBase:()=>Ci,applyWALPragmas:()=>es,cleanOrphanedWALFiles:()=>ts,closeDB:()=>rs,defaultDBPath:()=>Jh,deleteDBFiles:()=>uu,isSQLiteCorruptionError:()=>lu,loadDatabase:()=>zr,renameCorruptDB:()=>Bk,withRetry:()=>dn});import{createRequire as iD}from"node:module";import{existsSync as aD,unlinkSync as qk,renameSync as cD}from"node:fs";import{tmpdir as uD}from"node:os";import{join as lD}from"node:path";function zr(){if(!Qo){let t=iD(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;Qo=function(n,o){let s=new e(n,{readonly:o?.readonly,create:!0}),i=new au(s);return o?.timeout&&i.pragma(`busy_timeout = ${o.timeout}`),i}}else if(process.platform==="linux")try{let{DatabaseSync:e}=t(["node","sqlite"].join(":"));Qo=function(n,o){let s=new e(n,{readOnly:o?.readonly??!1});return new cu(s)}}catch{Qo=t("better-sqlite3")}else Qo=t("better-sqlite3")}return Qo}function es(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function ts(t){if(!aD(t))for(let e of["-wal","-shm"])try{qk(t+e)}catch{}}function uu(t){for(let e of["","-wal","-shm"])try{qk(t+e)}catch{}}function rs(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Jh(t="context-mode"){return lD(uD(),`${t}-${process.pid}.db`)}function dn(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(o){let s=o instanceof Error?o.message:String(o);if(!s.includes("SQLITE_BUSY")&&!s.includes("database is locked"))throw o;if(r=o instanceof Error?o:new Error(s),n<e.length){let i=e[n],a=Date.now();for(;Date.now()-a<i;);}}throw new Error(`SQLITE_BUSY: database is locked after ${e.length} retries. Original error: ${r?.message}`)}function lu(t){return t.includes("SQLITE_CORRUPT")||t.includes("SQLITE_NOTADB")||t.includes("database disk image is malformed")||t.includes("file is not a database")}function Bk(t){let e=Date.now();for(let r of["","-wal","-shm"])try{cD(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var au,cu,Qo,Ri,Kh,Ci,ns=v(()=>{"use strict";au=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){let r="",n=null;for(let s=0;s<e.length;s++){let i=e[s];if(n)r+=i,i===n&&(n=null);else if(i==="'"||i==='"')r+=i,n=i;else if(i===";"){let a=r.trim();a&&this.#e.prepare(a).run(),r=""}else r+=i}let o=r.trim();return o&&this.#e.prepare(o).run(),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>{let o=r.get(...n);return o===null?void 0:o},all:(...n)=>r.all(...n),iterate:(...n)=>r.iterate(...n)}}transaction(e){return this.#e.transaction(e)}close(){this.#e.close()}},cu=class{#e;constructor(e){this.#e=e}pragma(e){let n=this.#e.prepare(`PRAGMA ${e}`).all();if(!n||n.length===0)return;if(n.length>1)return n;let o=Object.values(n[0]);return o.length===1?o[0]:n[0]}exec(e){return this.#e.exec(e),this}prepare(e){let r=this.#e.prepare(e);return{run:(...n)=>r.run(...n),get:(...n)=>r.get(...n),all:(...n)=>r.all(...n),iterate:(...n)=>typeof r.iterate=="function"?r.iterate(...n):r.all(...n)[Symbol.iterator]()}}transaction(e){return(...r)=>{this.#e.exec("BEGIN");try{let n=e(...r);return this.#e.exec("COMMIT"),n}catch(n){throw this.#e.exec("ROLLBACK"),n}}}close(){this.#e.close()}},Qo=null;Ri=Symbol.for("__context_mode_live_dbs__"),Kh=(()=>{let t=globalThis;return t[Ri]||(t[Ri]=new Set,process.on("exit",()=>{for(let e of t[Ri])rs(e);t[Ri].clear()})),t[Ri]})(),Ci=class{#e;#t;constructor(e){let r=zr();this.#e=e,ts(e);let n;try{n=new r(e,{timeout:3e4}),es(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(lu(s)){Bk(e),ts(e);try{n=new r(e,{timeout:3e4}),es(n)}catch(i){throw new Error(`Failed to create fresh DB after renaming corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#t=n,Kh.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){Kh.delete(this.#t),rs(this.#t)}withRetry(e){return dn(e)}cleanup(){Kh.delete(this.#t),rs(this.#t),uu(this.#e)}}});import{readFileSync as Wk,readdirSync as Jk,unlinkSync as Xh,existsSync as Yh,statSync as du}from"node:fs";import{createHash as Gk}from"node:crypto";import{tmpdir as Yk}from"node:os";import{join as Qh}from"node:path";function Xk(t){let e=new Set,r=[];for(let n of t){let o=n.toLowerCase();e.has(o)||(e.add(o),r.push(n))}return r}function dD(t,e="AND"){let r=Xk(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(s=>s.length>0&&!["AND","OR","NOT","NEAR"].includes(s.toUpperCase())));if(r.length===0)return'""';let n=r.filter(s=>!os.has(s.toLowerCase()));return(n.length>0?n:r).map(s=>`"${s}"`).join(e==="OR"?" OR ":" ")}function pD(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=Xk(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let o=n.filter(i=>!os.has(i.toLowerCase()));return(o.length>0?o:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function mD(t,e){if(t.length===0)return e.length;if(e.length===0)return t.length;let r=Array.from({length:e.length+1},(n,o)=>o);for(let n=1;n<=t.length;n++){let o=[n];for(let s=1;s<=e.length;s++)o[s]=t[n-1]===e[s-1]?r[s-1]:1+Math.min(r[s],o[s-1],r[s-1]);r=o}return r[e.length]}function fD(t){return t<=4?1:t<=12?2:3}function eg(){let t=Yk(),e=0;try{let r=Jk(t);for(let n of r){let o=n.match(/^context-mode-(\d+)\.db$/);if(!o)continue;let s=parseInt(o[1],10);if(s!==process.pid)try{process.kill(s,0)}catch{let i=Qh(t,n);for(let a of["","-wal","-shm"])try{Xh(i+a)}catch{}e++}}}catch{}return e}function tg(t,e){let r=0;try{if(!Yh(t))return 0;let n=Date.now()-e*24*60*60*1e3,o=Jk(t).filter(s=>s.endsWith(".db"));for(let s of o)try{let i=Qh(t,s),c=du(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Yh(u))try{let l=du(u);l.size>0&&Date.now()-l.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Xh(i+u)}catch{}r++}}catch{}}catch{}return r}function hD(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function gD(t,e,r=30){if(t.length<2||e.length<2)return 0;let n=0,o=Math.min(t.length,e.length)-1;for(let s=0;s<o;s++){let i=t[s],a=t[s+1],c=e[s].length,u=0;for(let l of i){let d=l+c,p=d+r;for(;u<a.length&&a[u]<d;)u++;u<a.length&&a[u]<=p&&(n++,u++)}}return n}function _D(t){if(t.length===0)return 1/0;if(t.length===1)return 0;let e=t.map(o=>[...o].sort((s,i)=>s-i)),r=new Array(e.length).fill(0),n=1/0;for(;;){let o=1/0,s=-1/0,i=0;for(let c=0;c<e.length;c++){let u=e[c][r[c]];u<o&&(o=u,i=c),u>s&&(s=u)}let a=s-o;if(a<n&&(n=a),r[i]++,r[i]>=e[i].length)break}return n}var os,Kk,pu,Qk=v(()=>{"use strict";ns();os=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"]);Kk=4096;pu=class t{#e;#t;#n;#s;#o;#a;#c;#i;#u;#l;#m;#f;#h;#g;#_;#y;#x;#v;#b;#S;#k;#w;#$;#E;#T;#P;#R;#C;#O;#I;#A;#N;#z=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=zr();this.#t=e??Qh(Yk(),`context-mode-${process.pid}.db`),ts(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(o){let s=o instanceof Error?o.message:String(o);if(lu(s)){uu(this.#t),ts(this.#t);try{n=new r(this.#t,{timeout:3e4}),es(n)}catch(i){throw new Error(`Failed to create fresh DB after deleting corrupt file: ${i instanceof Error?i.message:String(i)}`)}}else throw o}this.#e=n,this.#U(),this.#Z()}cleanup(){try{this.#e.close()}catch{}for(let e of["","-wal","-shm"])try{Xh(this.#t+e)}catch{}}#U(){this.#e.exec(`
142
+ ${n}`}}}});import{cpus as Qz}from"node:os";async function zg(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,Qz().length):o,a=Math.min(o,i,t.length),c=a<o,u=new Array(t.length),d=0;async function l(){for(;;){let f=d++;if(f>=t.length)return;try{let p=await t[f].run();u[f]={status:"fulfilled",value:p}}catch(p){u[f]={status:"rejected",reason:p}}s?.(f,u[f])}}let m=[];for(let f=0;f<a;f++)m.push(l());return await Promise.allSettled(m),{settled:u,effectiveConcurrency:a,capped:c}}var Kw=v(()=>{"use strict"});var Qw={};Le(Qw,{BunSQLiteAdapter:()=>Tu,NodeSQLiteAdapter:()=>Pu,SQLiteBase:()=>Ui,applyWALPragmas:()=>mo,cleanOrphanedWALFiles:()=>fo,closeDB:()=>ho,defaultDBPath:()=>Fg,deleteDBFiles:()=>Ru,isSQLiteCorruptionError:()=>Cu,loadDatabase:()=>Xt,nodeSqliteHasFts5:()=>Yw,renameCorruptDB:()=>Xw,withRetry:()=>_n});import{createRequire as eL}from"node:module";import{existsSync as tL,unlinkSync as Jw,renameSync as rL}from"node:fs";import{tmpdir as nL}from"node:os";import{join as sL}from"node:path";function Yw(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 Xt(){if(!po){let t=eL(import.meta.url);if(globalThis.Bun){let e=t(["bun","sqlite"].join(":")).Database;po=function(n,s){let o=new e(n,{readonly:s?.readonly,create:!0}),i=new Tu(o);return s?.timeout&&i.pragma(`busy_timeout = ${s.timeout}`),i}}else if(process.platform==="linux"){let e=null;try{({DatabaseSync:e}=t(["node","sqlite"].join(":")))}catch{e=null}e&&Yw(e)?po=function(n,s){let o=new e(n,{readOnly:s?.readonly??!1});return new Pu(o)}:po=t("better-sqlite3")}else po=t("better-sqlite3")}return po}function mo(t){t.pragma("journal_mode = WAL"),t.pragma("synchronous = NORMAL");try{t.pragma("mmap_size = 268435456")}catch{}}function fo(t){if(!tL(t))for(let e of["-wal","-shm"])try{Jw(t+e)}catch{}}function Ru(t){for(let e of["","-wal","-shm"])try{Jw(t+e)}catch{}}function ho(t){try{t.pragma("wal_checkpoint(TRUNCATE)")}catch{}try{t.close()}catch{}}function Fg(t="context-mode"){return sL(nL(),`${t}-${process.pid}.db`)}function _n(t,e=[100,500,2e3]){let r;for(let n=0;n<=e.length;n++)try{return t()}catch(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 Cu(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 Xw(t){let e=Date.now();for(let r of["","-wal","-shm"])try{rL(t+r,`${t}${r}.corrupt-${e}`)}catch{}}var Tu,Pu,po,Fi,Lg,Ui,go=v(()=>{"use strict";Tu=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()}},Pu=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()}},po=null;Fi=Symbol.for("__context_mode_live_dbs__"),Lg=(()=>{let t=globalThis;return t[Fi]||(t[Fi]=new Set,process.on("exit",()=>{for(let e of t[Fi])ho(e);t[Fi].clear()})),t[Fi]})(),Ui=class{#e;#t;constructor(e){let r=Xt();this.#e=e,fo(e);let n;try{n=new r(e,{timeout:3e4}),mo(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Cu(o)){Xw(e),fo(e);try{n=new r(e,{timeout:3e4}),mo(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,Lg.add(this.#t),this.initSchema(),this.prepareStatements()}get db(){return this.#t}get dbPath(){return this.#e}close(){Lg.delete(this.#t),ho(this.#t)}withRetry(e){return _n(e)}cleanup(){Lg.delete(this.#t),ho(this.#t),Ru(this.#e)}}});import{readFileSync as eE,readdirSync as iE,unlinkSync as Hg,existsSync as Ug,statSync as Ou,openSync as tE,fstatSync as rE,closeSync as nE}from"node:fs";import{createHash as sE}from"node:crypto";import{tmpdir as aE}from"node:os";import{join as Zg}from"node:path";function cE(t){let e=new Set,r=[];for(let n of t){let s=n.toLowerCase();e.has(s)||(e.add(s),r.push(n))}return r}function oL(t,e="AND"){let r=cE(t.replace(/['"(){}[\]*:^~]/g," ").split(/\s+/).filter(o=>o.length>0&&!["AND","OR","NOT","NEAR"].includes(o.toUpperCase())));if(r.length===0)return'""';let n=r.filter(o=>!yo.has(o.toLowerCase()));return(n.length>0?n:r).map(o=>`"${o}"`).join(e==="OR"?" OR ":" ")}function iL(t,e="AND"){let r=t.replace(/["'(){}[\]*:^~]/g,"").trim();if(r.length<3)return"";let n=cE(r.split(/\s+/).filter(i=>i.length>=3));if(n.length===0)return"";let s=n.filter(i=>!yo.has(i.toLowerCase()));return(s.length>0?s:n).map(i=>`"${i}"`).join(e==="OR"?" OR ":" ")}function aL(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 cL(t){return t<=4?1:t<=12?2:3}function Bg(){let t=aE(),e=0;try{let r=iE(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=Zg(t,n);for(let a of["","-wal","-shm"])try{Hg(i+a)}catch{}e++}}}catch{}return e}function qg(t,e){let r=0;try{if(!Ug(t))return 0;let n=Date.now()-e*24*60*60*1e3,s=iE(t).filter(o=>o.endsWith(".db"));for(let o of s)try{let i=Zg(t,o),c=Ou(i).mtimeMs<n;if(!c){let u=i+"-wal";if(Ug(u))try{let d=Ou(u);d.size>0&&Date.now()-d.mtimeMs>36e5&&(c=!0)}catch{}}if(c){for(let u of["","-wal","-shm"])try{Hg(i+u)}catch{}r++}}catch{}}catch{}return r}function uL(t,e){let r=[],n=t.indexOf(e);for(;n!==-1;)r.push(n),n=t.indexOf(e,n+1);return r}function lL(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 dL(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 yo,oE,Iu,uE=v(()=>{"use strict";go();yo=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"]);oE=4096;Iu=class t{#e;#t;#n;#o;#s;#a;#c;#i;#u;#l;#m;#f;#h;#g;#y;#_;#x;#v;#b;#S;#k;#w;#E;#$;#T;#P;#R;#C;#O;#I;#A;#N;#D;#M=0;static OPTIMIZE_EVERY=50;#r=new Map;static FUZZY_CACHE_SIZE=256;constructor(e){let r=Xt();this.#t=e??Zg(aE(),`context-mode-${process.pid}.db`),fo(this.#t);let n;try{n=new r(this.#t,{timeout:3e4}),mo(n)}catch(s){let o=s instanceof Error?s.message:String(s);if(Cu(o)){Ru(this.#t),fo(this.#t);try{n=new r(this.#t,{timeout:3e4}),mo(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{Hg(this.#t+e)}catch{}}#H(){this.#e.exec(`
128
143
  CREATE TABLE IF NOT EXISTS sources (
129
144
  id INTEGER PRIMARY KEY AUTOINCREMENT,
130
145
  label TEXT NOT NULL,
@@ -187,7 +202,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
187
202
  timestamp UNINDEXED,
188
203
  tokenize='trigram'
189
204
  );
190
- `))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#Z(){this.#n=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, ?, ?, ?, ?)"),this.#o=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#a=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#c=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#i=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#u=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#l=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#m=this.#e.prepare(`
205
+ `))}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN file_path TEXT")}catch{}try{this.#e.exec("ALTER TABLE sources ADD COLUMN content_hash TEXT")}catch{}}#Z(){this.#o=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, 0, 0, ?, ?)"),this.#s=this.#e.prepare("INSERT INTO sources (label, chunk_count, code_chunk_count, file_path, content_hash) VALUES (?, ?, ?, ?, ?)"),this.#a=this.#e.prepare("INSERT INTO chunks (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#c=this.#e.prepare("INSERT INTO chunks_trigram (title, content, source_id, content_type, source_category, session_id, event_id, timestamp) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"),this.#i=this.#e.prepare("INSERT OR IGNORE INTO vocabulary (word) VALUES (?)"),this.#u=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#l=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE label = ?)"),this.#m=this.#e.prepare("DELETE FROM sources WHERE label = ?"),this.#f=this.#e.prepare(`
191
206
  SELECT
192
207
  chunks.title,
193
208
  chunks.content,
@@ -201,7 +216,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
201
216
  WHERE chunks MATCH ?
202
217
  ORDER BY rank
203
218
  LIMIT ?
204
- `),this.#f=this.#e.prepare(`
219
+ `),this.#h=this.#e.prepare(`
205
220
  SELECT
206
221
  chunks.title,
207
222
  chunks.content,
@@ -215,7 +230,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
215
230
  WHERE chunks MATCH ? AND sources.label LIKE ?
216
231
  ORDER BY rank
217
232
  LIMIT ?
218
- `),this.#h=this.#e.prepare(`
233
+ `),this.#g=this.#e.prepare(`
219
234
  SELECT
220
235
  chunks.title,
221
236
  chunks.content,
@@ -229,7 +244,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
229
244
  WHERE chunks MATCH ? AND sources.label = ?
230
245
  ORDER BY rank
231
246
  LIMIT ?
232
- `),this.#g=this.#e.prepare(`
247
+ `),this.#y=this.#e.prepare(`
233
248
  SELECT
234
249
  chunks_trigram.title,
235
250
  chunks_trigram.content,
@@ -257,7 +272,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
257
272
  WHERE chunks_trigram MATCH ? AND sources.label LIKE ?
258
273
  ORDER BY rank
259
274
  LIMIT ?
260
- `),this.#y=this.#e.prepare(`
275
+ `),this.#x=this.#e.prepare(`
261
276
  SELECT
262
277
  chunks_trigram.title,
263
278
  chunks_trigram.content,
@@ -271,7 +286,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
271
286
  WHERE chunks_trigram MATCH ? AND sources.label = ?
272
287
  ORDER BY rank
273
288
  LIMIT ?
274
- `),this.#v=this.#e.prepare(`
289
+ `),this.#b=this.#e.prepare(`
275
290
  SELECT
276
291
  chunks.title,
277
292
  chunks.content,
@@ -285,7 +300,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
285
300
  WHERE chunks MATCH ? AND chunks.content_type = ?
286
301
  ORDER BY rank
287
302
  LIMIT ?
288
- `),this.#b=this.#e.prepare(`
303
+ `),this.#S=this.#e.prepare(`
289
304
  SELECT
290
305
  chunks.title,
291
306
  chunks.content,
@@ -299,7 +314,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
299
314
  WHERE chunks MATCH ? AND sources.label LIKE ? AND chunks.content_type = ?
300
315
  ORDER BY rank
301
316
  LIMIT ?
302
- `),this.#S=this.#e.prepare(`
317
+ `),this.#k=this.#e.prepare(`
303
318
  SELECT
304
319
  chunks.title,
305
320
  chunks.content,
@@ -313,7 +328,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
313
328
  WHERE chunks MATCH ? AND sources.label = ? AND chunks.content_type = ?
314
329
  ORDER BY rank
315
330
  LIMIT ?
316
- `),this.#k=this.#e.prepare(`
331
+ `),this.#w=this.#e.prepare(`
317
332
  SELECT
318
333
  chunks_trigram.title,
319
334
  chunks_trigram.content,
@@ -327,7 +342,7 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
327
342
  WHERE chunks_trigram MATCH ? AND chunks_trigram.content_type = ?
328
343
  ORDER BY rank
329
344
  LIMIT ?
330
- `),this.#w=this.#e.prepare(`
345
+ `),this.#E=this.#e.prepare(`
331
346
  SELECT
332
347
  chunks_trigram.title,
333
348
  chunks_trigram.content,
@@ -355,31 +370,31 @@ ${n}`}}}});import{cpus as sD}from"node:os";async function Gh(t,e){let{concurrenc
355
370
  WHERE chunks_trigram MATCH ? AND sources.label = ? AND chunks_trigram.content_type = ?
356
371
  ORDER BY rank
357
372
  LIMIT ?
358
- `),this.#x=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#E=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#T=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
373
+ `),this.#v=this.#e.prepare("SELECT word FROM vocabulary WHERE length(word) BETWEEN ? AND ?"),this.#T=this.#e.prepare("SELECT label, chunk_count as chunkCount FROM sources ORDER BY id DESC"),this.#P=this.#e.prepare(`SELECT c.title, c.content, c.content_type, s.label
359
374
  FROM chunks c
360
375
  JOIN sources s ON s.id = c.source_id
361
376
  WHERE c.source_id = ?
362
- ORDER BY c.rowid`),this.#P=this.#e.prepare("SELECT chunk_count FROM sources WHERE id = ?"),this.#R=this.#e.prepare("SELECT content FROM chunks WHERE source_id = ?"),this.#O=this.#e.prepare("SELECT label, chunk_count, code_chunk_count, indexed_at, file_path, content_hash FROM sources WHERE label = ?"),this.#C=this.#e.prepare(`
377
+ ORDER BY c.rowid`),this.#R=this.#e.prepare("SELECT chunk_count FROM sources WHERE id = ?"),this.#C=this.#e.prepare("SELECT content FROM chunks WHERE source_id = ?"),this.#I=this.#e.prepare("SELECT label, chunk_count, code_chunk_count, indexed_at, file_path, content_hash FROM sources WHERE label = ?"),this.#O=this.#e.prepare(`
363
378
  SELECT
364
379
  (SELECT COUNT(*) FROM sources) AS sources,
365
380
  (SELECT COUNT(*) FROM chunks) AS chunks,
366
381
  (SELECT COUNT(*) FROM chunks WHERE content_type = 'code') AS codeChunks
367
- `),this.#I=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#A=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}index(e){let{content:r,path:n,source:o}=e,s=typeof r=="string"&&r.length>0;if(!s&&!n)throw new Error("Either content or path must be provided");let i=s?r:Wk(n,"utf-8"),a=o??n??"untitled",c=this.#B(i),u=n??void 0,l=u?Gk("sha256").update(i).digest("hex"):void 0;return dn(()=>this.#d(c,a,i,u,l))}indexPlainText(e,r,n=20){if(!e||e.trim().length===0)return this.#d([],r,"");let o=this.#V(e,n);return dn(()=>this.#d(o.map(s=>({...s,hasCode:!1})),r,e))}indexJSON(e,r,n=Kk){if(!e||e.trim().length===0)return this.indexPlainText("",r);let o;try{o=JSON.parse(e)}catch{return this.indexPlainText(e,r)}let s=[];return this.#F(o,[],s,n),s.length===0?this.indexPlainText(e,r):dn(()=>this.#d(s,r,e))}#d(e,r,n,o,s){let i=e.filter(u=>u.hasCode).length,c=this.#e.transaction(()=>{if(this.#i.run(r),this.#u.run(r),this.#l.run(r),e.length===0){let p=this.#n.run(r,o??null,s??null);return Number(p.lastInsertRowid)}let u=this.#s.run(r,e.length,i,o??null,s??null),l=Number(u.lastInsertRowid),d=new Date().toISOString();for(let p of e){let f=p.hasCode?"code":"prose";this.#o.run(p.title,p.content,l,f,null,null,null,d),this.#a.run(p.title,p.content,l,f,null,null,null,d)}return l})();return n&&this.#q(n),this.#z++,this.#z%t.OPTIMIZE_EVERY===0&&this.#L(),{sourceId:c,label:r,totalChunks:e.length,codeChunks:i}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e}%`}search(e,r=3,n,o="AND",s,i="like"){let a=dD(e,o),c,u;return n&&s?(c=i==="exact"?this.#S:this.#b,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#h:this.#f,u=[a,this.#p(n,i),r]):s?(c=this.#v,u=[a,s,r]):(c=this.#m,u=[a,r]),dn(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,o="AND",s,i="like"){let a=pD(e,o);if(!a)return[];let c,u;return n&&s?(c=i==="exact"?this.#$:this.#w,u=[a,this.#p(n,i),s,r]):n?(c=i==="exact"?this.#y:this.#_,u=[a,this.#p(n,i),r]):s?(c=this.#k,u=[a,s,r]):(c=this.#g,u=[a,r]),dn(()=>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=fD(r.length),o=this.#x.all(r.length-n,r.length+n),s=null,i=n+1,a=!1;for(let{word:u}of o){if(u===r){a=!0;break}let l=mD(r,u);l<i&&(i=l,s=u)}let c=a?null:i<=n?s:null;if(this.#r.size>=t.FUZZY_CACHE_SIZE){let u=this.#r.keys().next().value;u!==void 0&&this.#r.delete(u)}return this.#r.set(r,c),c}#D(e,r,n,o,s="like"){let a=Math.max(r*2,10),c=this.search(e,a,n,"OR",o,s),u=this.searchTrigram(e,a,n,"OR",o,s),l=new Map,d=p=>`${p.source}::${p.title}`;for(let[p,f]of c.entries()){let m=d(f),h=l.get(m);h?h.score+=1/(60+p+1):l.set(m,{result:f,score:1/(60+p+1)})}for(let[p,f]of u.entries()){let m=d(f),h=l.get(m);h?h.score+=1/(60+p+1):l.set(m,{result:f,score:1/(60+p+1)})}return Array.from(l.values()).sort((p,f)=>f.score-p.score).slice(0,r).map(({result:p,score:f})=>({...p,rank:-f}))}#M(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),o=n.filter(i=>!os.has(i)),s=o.length>0?o:n;return e.map(i=>{let a=i.title.toLowerCase(),c=s.filter(f=>a.includes(f)).length,u=i.contentType==="code"?.6:.3,l=c>0?u*(c/s.length):0,d=0,p=0;if(s.length>=2){let f=i.content.toLowerCase(),m=s.map(h=>hD(f,h));if(!m.some(h=>h.length===0)){d=1/(1+_D(m)/Math.max(f.length,1));let g=gD(m,s);p=.5*Math.min(1,g/4)}}return{result:i,boost:l+d+p}}).sort((i,a)=>a.boost-i.boost||i.result.rank-a.result.rank).map(({result:i})=>i)}searchWithFallback(e,r=3,n,o,s="like"){this.#H();let i=this.#D(e,r,n,o,s);if(i.length>0)return this.#M(i,e).map(p=>({...p,matchLayer:"rrf"}));let a=e.toLowerCase().trim().split(/\s+/).filter(d=>d.length>=3&&!os.has(d)),c=a.join(" "),l=a.map(d=>this.fuzzyCorrect(d)??d).join(" ");if(l!==c){let d=this.#D(l,r,n,o,s);if(d.length>0)return this.#M(d,l).map(f=>({...f,matchLayer:"rrf-fuzzy"}))}return[]}lastRefreshCount=0;#H(){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(!Yh(r.file_path))continue;let n=du(r.file_path).mtime,o=new Date(r.indexed_at+"Z");if(n<=o)continue;let s=Wk(r.file_path,"utf-8");if(Gk("sha256").update(s).digest("hex")===r.content_hash)continue;this.index({path:r.file_path,source:r.label}),this.lastRefreshCount++}catch{}}getSourceMeta(e){let r=this.#O.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.#E.all()}getChunksBySource(e){return this.#T.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.#P.get(e);if(!n||n.chunk_count<3)return[];let o=n.chunk_count,s=2,i=Math.max(3,Math.ceil(o*.4)),a=new Map;for(let l of this.#R.iterate(e)){let d=new Set(l.content.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(p=>p.length>=3&&!os.has(p)));for(let p of d)a.set(p,(a.get(p)??0)+1)}return Array.from(a.entries()).filter(([,l])=>l>=s&&l<=i).map(([l,d])=>{let p=Math.log(o/d),f=Math.min(l.length/20,.5),m=/[_]/.test(l),h=l.length>=12,g=m?1.5:h?.8:0;return{word:l,score:p+f+g}}).sort((l,d)=>d.score-l.score).slice(0,r).map(l=>l.word)}getStats(){let e=this.#C.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(o=>(this.#I.run(o),this.#A.run(o),this.#N.run(o)))(e).changes}getDBSizeBytes(){try{return du(this.#t).size}catch{return 0}}#L(){try{this.#e.exec("INSERT INTO chunks(chunks) VALUES('optimize')"),this.#e.exec("INSERT INTO chunks_trigram(chunks_trigram) VALUES('optimize')")}catch{}}close(){this.#L(),rs(this.#e)}#q(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(s=>s.length>=3&&!os.has(s)),n=[...new Set(r)],o=0;this.#e.transaction(()=>{for(let s of n){let i=this.#c.run(s);o+=i.changes}})(),o>0&&this.#r.clear()}#B(e,r=Kk){let n=[],o=e.split(`
368
- `),s=[],i=[],a="",c=()=>{let l=i.join(`
369
- `).trim();if(l.length===0)return;let d=this.#J(s,a),p=i.some(y=>/^`{3,}/.test(y));if(Buffer.byteLength(l)<=r){n.push({title:d,content:l,hasCode:p}),i=[];return}let f=l.split(/\n\n+/),m=[],h=1,g=()=>{if(m.length===0)return;let y=m.join(`
382
+ `),this.#A=this.#e.prepare("DELETE FROM chunks WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#N=this.#e.prepare("DELETE FROM chunks_trigram WHERE source_id IN (SELECT id FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days'))"),this.#D=this.#e.prepare("DELETE FROM sources WHERE datetime(indexed_at) < datetime('now', '-' || ? || ' days')")}setDenyChecker(e){this.#n=e}index(e){let{content:r,path:n,source:s}=e,o=typeof r=="string"&&r.length>0;if(!o&&!n)throw new Error("Either content or path must be provided");let i;if(o)i=r;else{let l=tE(n,"r");try{if(!rE(l).isFile())throw new Error(`refusing to index ${n}: not a regular file`);i=eE(l,"utf-8")}finally{nE(l)}}let a=s??n??"untitled",c=this.#V(i),u=n??void 0,d=u?sE("sha256").update(i).digest("hex"):void 0;return _n(()=>this.#d(c,a,i,u,d))}indexPlainText(e,r,n=20){if(!e||e.trim().length===0)return this.#d([],r,"");let s=this.#W(e,n);return _n(()=>this.#d(s.map(o=>({...o,hasCode:!1})),r,e))}indexJSON(e,r,n=oE){if(!e||e.trim().length===0)return this.indexPlainText("",r);let s;try{s=JSON.parse(e)}catch{return this.indexPlainText(e,r)}let o=[];return this.#U(s,[],o,n),o.length===0?this.indexPlainText(e,r):_n(()=>this.#d(o,r,e))}#d(e,r,n,s,o){let i=e.filter(u=>u.hasCode).length,c=this.#e.transaction(()=>{if(this.#u.run(r),this.#l.run(r),this.#m.run(r),e.length===0){let m=this.#o.run(r,s??null,o??null);return Number(m.lastInsertRowid)}let u=this.#s.run(r,e.length,i,s??null,o??null),d=Number(u.lastInsertRowid),l=new Date().toISOString();for(let m of e){let f=m.hasCode?"code":"prose";this.#a.run(m.title,m.content,d,f,null,null,null,l),this.#c.run(m.title,m.content,d,f,null,null,null,l)}return d})();return n&&this.#q(n),this.#M++,this.#M%t.OPTIMIZE_EVERY===0&&this.#F(),{sourceId:c,label:r,totalChunks:e.length,codeChunks:i}}#j(e){return e.map(r=>({title:r.title,content:r.content,source:r.label,rank:r.rank,contentType:r.content_type,highlighted:r.highlighted,timestamp:r.timestamp??void 0}))}#p(e,r){return r==="exact"?e:`%${e}%`}search(e,r=3,n,s="AND",o,i="like"){let a=oL(e,s),c,u;return n&&o?(c=i==="exact"?this.#k:this.#S,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#g:this.#h,u=[a,this.#p(n,i),r]):o?(c=this.#b,u=[a,o,r]):(c=this.#f,u=[a,r]),_n(()=>this.#j(c.all(...u)))}searchTrigram(e,r=3,n,s="AND",o,i="like"){let a=iL(e,s);if(!a)return[];let c,u;return n&&o?(c=i==="exact"?this.#$:this.#E,u=[a,this.#p(n,i),o,r]):n?(c=i==="exact"?this.#x:this.#_,u=[a,this.#p(n,i),r]):o?(c=this.#w,u=[a,o,r]):(c=this.#y,u=[a,r]),_n(()=>this.#j(c.all(...u)))}fuzzyCorrect(e){let r=e.toLowerCase().trim();if(r.length<3)return null;if(this.#r.has(r)){let u=this.#r.get(r)??null;return this.#r.delete(r),this.#r.set(r,u),u}let n=cL(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=aL(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,f]of c.entries()){let p=l(f),h=d.get(p);h?h.score+=1/(60+m+1):d.set(p,{result:f,score:1/(60+m+1)})}for(let[m,f]of u.entries()){let p=l(f),h=d.get(p);h?h.score+=1/(60+m+1):d.set(p,{result:f,score:1/(60+m+1)})}return Array.from(d.values()).sort((m,f)=>f.score-m.score).slice(0,r).map(({result:m,score:f})=>({...m,rank:-f}))}#L(e,r){let n=r.toLowerCase().split(/\s+/).filter(i=>i.length>=2),s=n.filter(i=>!yo.has(i)),o=s.length>0?s:n;return e.map(i=>{let a=i.title.toLowerCase(),c=o.filter(f=>a.includes(f)).length,u=i.contentType==="code"?.6:.3,d=c>0?u*(c/o.length):0,l=0,m=0;if(o.length>=2){let f=i.content.toLowerCase(),p=o.map(h=>uL(f,h));if(!p.some(h=>h.length===0)){l=1/(1+dL(p)/Math.max(f.length,1));let g=lL(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&&!yo.has(l)),c=a.join(" "),d=a.map(l=>this.fuzzyCorrect(l)??l).join(" ");if(d!==c){let l=this.#z(d,r,n,s,o);if(l.length>0)return this.#L(l,d).map(f=>({...f,matchLayer:"rrf-fuzzy"}))}return[]}lastRefreshCount=0;#B(){this.lastRefreshCount=0;let e=this.#e.prepare("SELECT label, file_path, content_hash, indexed_at FROM sources WHERE file_path IS NOT NULL").all();for(let r of e)try{if(!Ug(r.file_path)||this.#n&&this.#n(r.file_path))continue;let n=Ou(r.file_path).mtime,s=new Date(r.indexed_at+"Z");if(n<=s)continue;let o=tE(r.file_path,"r"),i;try{if(!rE(o).isFile())continue;i=eE(o,"utf-8")}finally{nE(o)}if(sE("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&&!yo.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),f=Math.min(d.length/20,.5),p=/[_]/.test(d),h=d.length>=12,g=p?1.5:h?.8:0;return{word:d,score:m+f+g}}).sort((d,l)=>l.score-d.score).slice(0,r).map(d=>d.word)}getStats(){let e=this.#O.get();return{sources:e?.sources??0,chunks:e?.chunks??0,codeChunks:e?.codeChunks??0}}cleanupStaleSources(e){return this.#e.transaction(s=>(this.#A.run(s),this.#N.run(s),this.#D.run(s)))(e).changes}getDBSizeBytes(){try{return Ou(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(),ho(this.#e)}#q(e){let r=e.toLowerCase().split(/[^\p{L}\p{N}_-]+/u).filter(o=>o.length>=3&&!yo.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=oE){let n=[],s=e.split(`
383
+ `),o=[],i=[],a="",c=()=>{let d=i.join(`
384
+ `).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 f=d.split(/\n\n+/),p=[],h=1,g=()=>{if(p.length===0)return;let y=p.join(`
370
385
 
371
- `).trim();if(y.length===0)return;let _=f.length>1?`${d} (${h})`:d;h++,n.push({title:_,content:y,hasCode:y.includes("```")}),m=[]};for(let y of f){m.push(y);let _=m.join(`
386
+ `).trim();if(y.length===0)return;let _=f.length>1?`${l} (${h})`:l;h++,n.push({title:_,content:y,hasCode:y.includes("```")}),p=[]};for(let y of f){p.push(y);let _=p.join(`
372
387
 
373
- `);Buffer.byteLength(_)>r&&m.length>1&&(m.pop(),g(),m=[y])}g(),i=[]},u=0;for(;u<o.length;){let l=o[u];if(/^[-_*]{3,}\s*$/.test(l)){c(),u++;continue}let d=l.match(/^(#{1,4})\s+(.+)$/);if(d){c();let f=d[1].length,m=d[2].trim();for(;s.length>0&&s[s.length-1].level>=f;)s.pop();s.push({level:f,text:m}),a=m,i.push(l),u++;continue}let p=l.match(/^(`{3,})(.*)?$/);if(p){let f=p[1],m=[l];for(u++;u<o.length;){if(m.push(o[u]),o[u].startsWith(f)&&o[u].trim()===f){u++;break}u++}i.push(...m);continue}i.push(l),u++}return c(),n}#V(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let l=c.trim();return{title:l.split(`
374
- `)[0].slice(0,80)||`Section ${u+1}`,content:l}}).filter(c=>c.content.length>0);let o=e.split(`
375
- `);if(o.length<=r)return[{title:"Output",content:e}];let s=[],a=Math.max(r-2,1);for(let c=0;c<o.length;c+=a){let u=o.slice(c,c+r);if(u.length===0)break;let l=c+1,d=Math.min(c+u.length,o.length),p=u[0]?.trim().slice(0,80);s.push({title:p||`Lines ${l}-${d}`,content:u.join(`
376
- `)})}return s}#F(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=o&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:s,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#F(u,[...r,c],n,o);return}n.push({title:s,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#K(e,r,n,o);return}n.push({title:s,content:i,hasCode:!1})}#W(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],o=r;for(let s of n)if(s in o&&(typeof o[s]=="string"||typeof o[s]=="number"))return s;return null}#G(e,r,n,o,s){let i=e?`${e} > `:"";if(!s)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[s]);return o.length===1?`${i}${a(o[0])}`:o.length<=3?i+o.map(a).join(", "):`${i}${a(o[0])}\u2026${a(o[o.length-1])}`}#K(e,r,n,o){let s=r.length>0?r.join(" > "):"(root)",i=this.#W(e),a=[],c=0,u=l=>{if(a.length===0)return;let d=this.#G(s,c,l,a,i);n.push({title:d,content:JSON.stringify(a,null,2),hasCode:!0})};for(let l=0;l<e.length;l++){a.push(e[l]);let d=JSON.stringify(a,null,2);Buffer.byteLength(d)>o&&a.length>1&&(a.pop(),u(l-1),a=[e[l]],c=l)}u(c+a.length-1)}#J(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});function rg(t,e){return t===void 0?e:`${t}::${e}`}var ew=v(()=>{"use strict"});import{readFileSync as rw,realpathSync as yD}from"node:fs";import{resolve as Xn}from"node:path";import{homedir as nw}from"node:os";function ow(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function xD(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function vD(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function tw(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function bD(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let o=t.slice(0,n),s=t.slice(n+1),i=vD(o),a=tw(s);r=`^${i}(\\s${a})?$`}else r=`^${tw(t)}$`;return new RegExp(r,e?"i":"")}function SD(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 kD(t,e,r=!1){for(let n of e){let o=ow(n);if(o&&bD(o,r).test(t))return n}return null}function wD(t){let e=[],r="",n=!1,o=!1,s=!1;for(let i=0;i<t.length;i++){let a=t[i],c=i>0?t[i-1]:"";a==="'"&&!o&&!s&&c!=="\\"?(n=!n,r+=a):a==='"'&&!n&&!s&&c!=="\\"?(o=!o,r+=a):a==="`"&&!n&&!o&&c!=="\\"?(s=!s,r+=a):!n&&!o&&!s?a===";"?(e.push(r.trim()),r=""):a==="|"&&t[i+1]==="|"||a==="&"&&t[i+1]==="&"?(e.push(r.trim()),r="",i++):a==="|"?(e.push(r.trim()),r=""):r+=a:r+=a}return r.trim()&&e.push(r.trim()),e.filter(i=>i.length>0)}function ng(t){let e;try{e=rw(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let o=s=>Array.isArray(s)?s.filter(i=>typeof i=="string"&&ow(i)!==null):[];return{allow:o(n.allow),deny:o(n.deny),ask:o(n.ask)}}function og(t,e){let r=[];if(t){let s=Xn(t,".claude","settings.local.json"),i=ng(s);i&&r.push(i);let a=Xn(t,".claude","settings.json"),c=ng(a);c&&r.push(c)}let n=e??Xn(nw(),".claude","settings.json"),o=ng(n);return o&&r.push(o),r}function sw(t,e,r){let n=[],o=a=>{let c;try{c=rw(a,"utf-8")}catch{return null}let u;try{u=JSON.parse(c)}catch{return null}let l=u?.permissions?.deny;if(!Array.isArray(l))return[];let d=[];for(let p of l){if(typeof p!="string")continue;let f=xD(p);f&&f.tool===t&&d.push(f.glob)}return d};if(e){let a=o(Xn(e,".claude","settings.local.json"));a!==null&&n.push(a);let c=o(Xn(e,".claude","settings.json"));c!==null&&n.push(c)}let s=r??Xn(nw(),".claude","settings.json"),i=o(s);return i!==null&&n.push(i),n}function sg(t,e,r=process.platform==="win32"){let n=wD(t);for(let o of n)for(let s of e){let i=kD(o,s.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function iw(t,e,r=process.platform==="win32",n){let o=i=>i.replace(/\\/g,"/"),s=new Set;if(s.add(o(t)),n){let i=Xn(n,t);s.add(o(i));try{s.add(o(yD(i)))}catch{}}for(let i of e)for(let a of i){let c=SD(a,r);for(let u of s)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function ED(t){let e=[],r=/subprocess\.(?:run|call|Popen|check_output|check_call)\(\s*\[([^\]]+)\]/g,n;for(;(n=r.exec(t))!==null;){let s=[...n[1].matchAll(/(['"])(.*?)\1/g)].map(i=>i[2]);s.length>0&&e.push(s.join(" "))}return e}function aw(t,e){let r=$D[e];if(!r&&e!=="python")return[];let n=[];if(r)for(let o of r){o.lastIndex=0;let s;for(;(s=o.exec(t))!==null;){let i=s[s.length-1];i&&n.push(i)}}return e==="python"&&n.push(...ED(t)),n}var $D,cw=v(()=>{"use strict";$D={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 ig(t){let{language:e,exitCode:r,stdout:n,stderr:o}=t,s=e==="shell"&&r===1&&n.trim().length>0;return{isError:!s,output:s?n:`Exit code: ${r}
388
+ `);Buffer.byteLength(_)>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 f=l[1].length,p=l[2].trim();for(;o.length>0&&o[o.length-1].level>=f;)o.pop();o.push({level:f,text:p}),a=p,i.push(d),u++;continue}let m=d.match(/^(`{3,})(.*)?$/);if(m){let f=m[1],p=[d];for(u++;u<s.length;){if(p.push(s[u]),s[u].startsWith(f)&&s[u].trim()===f){u++;break}u++}i.push(...p);continue}i.push(d),u++}return c(),n}#W(e,r){let n=e.split(/\n\s*\n/);if(n.length>=3&&n.length<=200&&n.every(c=>Buffer.byteLength(c)<5e3))return n.map((c,u)=>{let d=c.trim();return{title:d.split(`
389
+ `)[0].slice(0,80)||`Section ${u+1}`,content:d}}).filter(c=>c.content.length>0);let s=e.split(`
390
+ `);if(s.length<=r)return[{title:"Output",content:e}];let o=[],a=Math.max(r-2,1);for(let c=0;c<s.length;c+=a){let u=s.slice(c,c+r);if(u.length===0)break;let d=c+1,l=Math.min(c+u.length,s.length),m=u[0]?.trim().slice(0,80);o.push({title:m||`Lines ${d}-${l}`,content:u.join(`
391
+ `)})}return o}#U(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=JSON.stringify(e,null,2);if(Buffer.byteLength(i)<=s&&!(typeof e=="object"&&e!==null&&!Array.isArray(e)&&Object.values(e).some(c=>typeof c=="object"&&c!==null))){n.push({title:o,content:i,hasCode:!0});return}if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let a=Object.entries(e);if(a.length>0){for(let[c,u]of a)this.#U(u,[...r,c],n,s);return}n.push({title:o,content:i,hasCode:!0});return}if(Array.isArray(e)){this.#J(e,r,n,s);return}n.push({title:o,content:i,hasCode:!1})}#G(e){if(e.length===0)return null;let r=e[0];if(typeof r!="object"||r===null||Array.isArray(r))return null;let n=["id","name","title","path","slug","key","label"],s=r;for(let o of n)if(o in s&&(typeof s[o]=="string"||typeof s[o]=="number"))return o;return null}#K(e,r,n,s,o){let i=e?`${e} > `:"";if(!o)return r===n?`${i}[${r}]`:`${i}[${r}-${n}]`;let a=c=>String(c[o]);return s.length===1?`${i}${a(s[0])}`:s.length<=3?i+s.map(a).join(", "):`${i}${a(s[0])}\u2026${a(s[s.length-1])}`}#J(e,r,n,s){let o=r.length>0?r.join(" > "):"(root)",i=this.#G(e),a=[],c=0,u=d=>{if(a.length===0)return;let l=this.#K(o,c,d,a,i);n.push({title:l,content:JSON.stringify(a,null,2),hasCode:!0})};for(let d=0;d<e.length;d++){a.push(e[d]);let l=JSON.stringify(a,null,2);Buffer.byteLength(l)>s&&a.length>1&&(a.pop(),u(d-1),a=[e[d]],c=d)}u(c+a.length-1)}#Y(e,r){return e.length===0?r||"Untitled":e.map(n=>n.text).join(" > ")}}});function Vg(t,e){return t===void 0?e:`${t}::${e}`}var lE=v(()=>{"use strict"});import{readFileSync as pE,realpathSync as pL}from"node:fs";import{resolve as Hi}from"node:path";function mE(t){let e=t.match(/^Bash\((.+)\)$/);return e?e[1]:null}function mL(t){let e=t.match(/^(\w+)\((.+)\)$/);return e?{tool:e[1],glob:e[2]}:null}function fL(t){return t.replace(/[.*+?^${}()|[\]\\\/\-]/g,"\\$&")}function dE(t){return t.replace(/[.+?^${}()|[\]\\\/\-]/g,"\\$&").replace(/\*/g,".*")}function hL(t,e=!1){let r,n=t.indexOf(":");if(n!==-1){let s=t.slice(0,n),o=t.slice(n+1),i=fL(s),a=dE(o);r=`^${i}(\\s${a})?$`}else r=`^${dE(t)}$`;return new RegExp(r,e?"i":"")}function gL(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 yL(t,e,r=!1){for(let n of e){let s=mE(n);if(s&&hL(s,r).test(t))return n}return null}function _L(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 Wg(t){let e;try{e=pE(t,"utf-8")}catch{return null}let r;try{r=JSON.parse(e)}catch{return null}let n=r?.permissions;if(!n||typeof n!="object")return null;let s=o=>Array.isArray(o)?o.filter(i=>typeof i=="string"&&mE(i)!==null):[];return{allow:s(n.allow),deny:s(n.deny),ask:s(n.ask)}}function Gg(t,e){let r=[];if(t){let s=Hi(t,".claude","settings.local.json"),o=Wg(s);o&&r.push(o);let i=Hi(t,".claude","settings.json"),a=Wg(i);a&&r.push(a)}let n=e!==void 0?[e]:Sl();for(let s of n){let o=Wg(s);o&&r.push(o)}return r}function Kg(t,e,r){let n=[],s=i=>{let a;try{a=pE(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=mL(l);m&&m.tool===t&&d.push(m.glob)}return d};if(e){let i=s(Hi(e,".claude","settings.local.json"));i!==null&&n.push(i);let a=s(Hi(e,".claude","settings.json"));a!==null&&n.push(a)}let o=r!==void 0?[r]:Sl();for(let i of o){let a=s(i);a!==null&&n.push(a)}return n}function Jg(t,e,r=process.platform==="win32"){let n=_L(t);for(let s of n)for(let o of e){let i=yL(s,o.deny,r);if(i)return{decision:"deny",matchedPattern:i}}return{decision:"allow"}}function Yg(t,e,r=process.platform==="win32",n){let s=i=>i.replace(/\\/g,"/"),o=new Set;if(o.add(s(t)),n){let i=Hi(n,t);o.add(s(i));try{o.add(s(pL(i)))}catch{}}for(let i of e)for(let a of i){let c=gL(s(a),r);for(let u of o)if(c.test(u))return{denied:!0,matchedPattern:a}}return{denied:!1}}function vL(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 fE(t,e){let r=xL[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(...vL(t)),n}var xL,hE=v(()=>{"use strict";Wr();xL={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 Xg(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}
377
392
 
378
393
  stdout:
379
394
  ${n}
380
395
 
381
396
  stderr:
382
- ${o}`}}var uw=v(()=>{"use strict"});import{execFileSync as TD}from"node:child_process";function PD(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=TD("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 RD(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??PD,n=e(),o=r();return()=>{let s=e();return!(s!==n||s===0||s===1||!Number.isNaN(o)&&o>1&&r()===1)}}function lw(t){let e=t.checkIntervalMs??3e4,r=t.isParentAlive??CD,n=!1,o=()=>{n||(n=!0,t.onShutdown())},s=setInterval(()=>{r()||o()},e);s.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,o);let a=()=>{r()||o()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(s);for(let c of i)process.removeListener(c,o);process.stdin.removeListener("end",a)}}var CD,dw=v(()=>{"use strict";CD=RD()});import{createHash as ag}from"node:crypto";import{execFileSync as OD}from"node:child_process";function Ii(){let t=process.env.CONTEXT_MODE_SESSION_SUFFIX,e=process.cwd();if(Oi&&Oi.cwd===e&&Oi.envSuffix===t)return Oi.suffix;let r="";if(t!==void 0)r=t?`__${t}`:"";else try{let n=OD("git",["worktree","list","--porcelain"],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).split(/\r?\n/).find(o=>o.startsWith("worktree "))?.replace("worktree ","")?.trim();n&&e!==n&&(r=`__${ag("sha256").update(e).digest("hex").slice(0,8)}`)}catch{}return Oi={cwd:e,envSuffix:t,suffix:r},r}var Oi,pw,mw,U,Qn,cg=v(()=>{"use strict";ns();pw=1e3,mw=5,U={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"},Qn=class extends Ci{constructor(e){super(e?.dbPath??Jh("session"))}stmt(e){return this.stmts.get(e)}initSchema(){try{let r=this.db.pragma("table_xinfo(session_events)").find(n=>n.name==="data_hash");r&&r.hidden!==0&&this.db.exec("DROP TABLE session_events")}catch{}this.db.exec(`
397
+ ${s}`}}var gE=v(()=>{"use strict"});import{execFileSync as bL}from"node:child_process";function SL(){if(process.platform==="win32")return NaN;let t=process.ppid;if(!t||t<=1)return NaN;try{let e=bL("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 kL(t={}){let e=t.getPpid??(()=>process.ppid),r=t.readGrandparentPpid??SL,n=e(),s=r();return()=>{let o=e();return!(o!==n||o===0||o===1||!Number.isNaN(s)&&s>1&&r()===1)}}function yE(t){let e=t.checkIntervalMs??3e4,r=t.isParentAlive??wL,n=!1,s=()=>{n||(n=!0,t.onShutdown())},o=setInterval(()=>{r()||s()},e);o.unref();let i=["SIGTERM","SIGINT"];process.platform!=="win32"&&i.push("SIGHUP");for(let c of i)process.on(c,s);let a=()=>{r()||s()};return process.stdin.isTTY||process.stdin.on("end",a),()=>{n=!0,clearInterval(o);for(let c of i)process.removeListener(c,s);process.stdin.removeListener("end",a)}}var wL,_E=v(()=>{"use strict";wL=kL()});import{createHash as Bi}from"node:crypto";import{execFileSync as EL}from"node:child_process";import{existsSync as Nu,realpathSync as $L,renameSync as Qg}from"node:fs";import{join as Du}from"node:path";function qi(t){let e=t.replace(/\\/g,"/");return/^\/+$/.test(e)?"/":/^[A-Za-z]:\/+$/.test(e)?`${e.slice(0,2)}/`:e.replace(/\/+$/,"")}function xE(t){let e=t;try{e=$L.native(t)}catch{}let r=qi(e);return process.platform==="win32"||process.platform==="darwin"?r.toLowerCase():r}function SE(t,e){return EL("git",["-C",t,...e],{encoding:"utf-8",timeout:2e3,stdio:["ignore","pipe","ignore"]}).trim()}function TL(t){let e=SE(t,["rev-parse","--show-toplevel"]);return e.length>0?qi(e):null}function PL(t){let e=SE(t,["worktree","list","--porcelain"]).split(/\r?\n/).find(r=>r.startsWith("worktree "))?.replace("worktree ","")?.trim();return e?qi(e):null}function ey(t=process.cwd()){let e=process.env.CONTEXT_MODE_SESSION_SUFFIX;if(Zi&&Zi.projectDir===t&&Zi.envSuffix===e)return Zi.suffix;let r="";if(e!==void 0)r=e?`__${e}`:"";else try{let n=TL(t),s=PL(t);if(n&&s){let o=xE(n),i=xE(s);o!==i&&(r=`__${Bi("sha256").update(o).digest("hex").slice(0,8)}`)}}catch{}return Zi={projectDir:t,envSuffix:e,suffix:r},r}function cs(t){return Bi("sha256").update(qi(t)).digest("hex").slice(0,16)}function us(t){let e=qi(t),r=process.platform==="darwin"||process.platform==="win32"?e.toLowerCase():e;return Bi("sha256").update(r).digest("hex").slice(0,16)}function kE(t){let{projectDir:e,contentDir:r}=t,n=us(e),s=Du(r,`${n}.db`);if(Nu(s))return s;let o=cs(e);if(o===n)return s;let i=Du(r,`${o}.db`);if(Nu(i))try{Qg(i,s);for(let a of["-wal","-shm"])try{Qg(i+a,s+a)}catch{}}catch{}return s}function Mu(t){return RL({...t,ext:".db"})}function RL(t){let{projectDir:e,sessionsDir:r,ext:n}=t,s=t.suffix??ey(e),o=us(e),i=Du(r,`${o}${s}${n}`);if(Nu(i))return i;let a=cs(e);if(a===o)return i;let c=Du(r,`${a}${s}${n}`);if(Nu(c))try{Qg(c,i)}catch{}return i}function Au(t){let e=Number(t);return!Number.isFinite(e)||e<=0?0:Math.floor(e)}var Zi,vE,bE,B,Lr,Vi=v(()=>{"use strict";go();vE=1e3,bE=5;B={insertEvent:"insertEvent",getEvents:"getEvents",getEventsByType:"getEventsByType",getEventsByPriority:"getEventsByPriority",getEventsByTypeAndPriority:"getEventsByTypeAndPriority",getEventCount:"getEventCount",getLatestAttributedProject:"getLatestAttributedProject",checkDuplicate:"checkDuplicate",evictLowestPriority:"evictLowestPriority",updateMetaLastEvent:"updateMetaLastEvent",ensureSession:"ensureSession",getSessionStats:"getSessionStats",incrementCompactCount:"incrementCompactCount",upsertResume:"upsertResume",getResume:"getResume",markResumeConsumed:"markResumeConsumed",claimLatestUnconsumedResume:"claimLatestUnconsumedResume",deleteEvents:"deleteEvents",deleteMeta:"deleteMeta",deleteResume:"deleteResume",getOldSessions:"getOldSessions",searchEvents:"searchEvents",incrementToolCall:"incrementToolCall",getToolCallTotals:"getToolCallTotals",getToolCallByTool:"getToolCallByTool",getEventBytesSummary:"getEventBytesSummary"},Lr=class extends Ui{constructor(e){super(e?.dbPath??Fg("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(`
383
398
  CREATE TABLE IF NOT EXISTS session_events (
384
399
  id INTEGER PRIMARY KEY AUTOINCREMENT,
385
400
  session_id TEXT NOT NULL,
@@ -390,6 +405,8 @@ ${o}`}}var uw=v(()=>{"use strict"});import{execFileSync as TD}from"node:child_pr
390
405
  project_dir TEXT NOT NULL DEFAULT '',
391
406
  attribution_source TEXT NOT NULL DEFAULT 'unknown',
392
407
  attribution_confidence REAL NOT NULL DEFAULT 0,
408
+ bytes_avoided INTEGER NOT NULL DEFAULT 0,
409
+ bytes_returned INTEGER NOT NULL DEFAULT 0,
393
410
  source_hook TEXT NOT NULL,
394
411
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
395
412
  data_hash TEXT NOT NULL DEFAULT ''
@@ -427,45 +444,50 @@ ${o}`}}var uw=v(()=>{"use strict"});import{execFileSync as TD}from"node:child_pr
427
444
  );
428
445
 
429
446
  CREATE INDEX IF NOT EXISTS idx_tool_calls_session ON tool_calls(session_id);
430
- `);try{let e=this.db.pragma("table_xinfo(session_events)"),r=new Set(e.map(n=>n.name));r.has("project_dir")||this.db.exec("ALTER TABLE session_events ADD COLUMN project_dir TEXT NOT NULL DEFAULT ''"),r.has("attribution_source")||this.db.exec("ALTER TABLE session_events ADD COLUMN attribution_source TEXT NOT NULL DEFAULT 'unknown'"),r.has("attribution_confidence")||this.db.exec("ALTER TABLE session_events ADD COLUMN attribution_confidence REAL NOT NULL DEFAULT 0"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)")}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(U.insertEvent,`INSERT INTO session_events (
447
+ `);try{let e=this.db.pragma("table_xinfo(session_events)"),r=new Set(e.map(n=>n.name));r.has("project_dir")||this.db.exec("ALTER TABLE session_events ADD COLUMN project_dir TEXT NOT NULL DEFAULT ''"),r.has("attribution_source")||this.db.exec("ALTER TABLE session_events ADD COLUMN attribution_source TEXT NOT NULL DEFAULT 'unknown'"),r.has("attribution_confidence")||this.db.exec("ALTER TABLE session_events ADD COLUMN attribution_confidence REAL NOT NULL DEFAULT 0"),r.has("bytes_avoided")||this.db.exec("ALTER TABLE session_events ADD COLUMN bytes_avoided INTEGER NOT NULL DEFAULT 0"),r.has("bytes_returned")||this.db.exec("ALTER TABLE session_events ADD COLUMN bytes_returned INTEGER NOT NULL DEFAULT 0"),this.db.exec("CREATE INDEX IF NOT EXISTS idx_session_events_project ON session_events(session_id, project_dir)")}catch{}}prepareStatements(){this.stmts=new Map;let e=(r,n)=>{this.stmts.set(r,this.db.prepare(n))};e(B.insertEvent,`INSERT INTO session_events (
431
448
  session_id, type, category, priority, data,
432
449
  project_dir, attribution_source, attribution_confidence,
450
+ bytes_avoided, bytes_returned,
433
451
  source_hook, data_hash
434
452
  )
435
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(U.getEvents,`SELECT id, session_id, type, category, priority, data,
453
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`),e(B.getEvents,`SELECT id, session_id, type, category, priority, data,
436
454
  project_dir, attribution_source, attribution_confidence,
455
+ bytes_avoided, bytes_returned,
437
456
  source_hook, created_at, data_hash
438
- FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(U.getEventsByType,`SELECT id, session_id, type, category, priority, data,
457
+ FROM session_events WHERE session_id = ? ORDER BY id ASC LIMIT ?`),e(B.getEventsByType,`SELECT id, session_id, type, category, priority, data,
439
458
  project_dir, attribution_source, attribution_confidence,
459
+ bytes_avoided, bytes_returned,
440
460
  source_hook, created_at, data_hash
441
- FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(U.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
461
+ FROM session_events WHERE session_id = ? AND type = ? ORDER BY id ASC LIMIT ?`),e(B.getEventsByPriority,`SELECT id, session_id, type, category, priority, data,
442
462
  project_dir, attribution_source, attribution_confidence,
463
+ bytes_avoided, bytes_returned,
443
464
  source_hook, created_at, data_hash
444
- FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(U.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
465
+ FROM session_events WHERE session_id = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(B.getEventsByTypeAndPriority,`SELECT id, session_id, type, category, priority, data,
445
466
  project_dir, attribution_source, attribution_confidence,
467
+ bytes_avoided, bytes_returned,
446
468
  source_hook, created_at, data_hash
447
- FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(U.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(U.getLatestAttributedProject,`SELECT project_dir
469
+ FROM session_events WHERE session_id = ? AND type = ? AND priority >= ? ORDER BY id ASC LIMIT ?`),e(B.getEventCount,"SELECT COUNT(*) AS cnt FROM session_events WHERE session_id = ?"),e(B.getLatestAttributedProject,`SELECT project_dir
448
470
  FROM session_events
449
471
  WHERE session_id = ? AND project_dir != ''
450
472
  ORDER BY id DESC
451
- LIMIT 1`),e(U.checkDuplicate,`SELECT 1 FROM (
473
+ LIMIT 1`),e(B.checkDuplicate,`SELECT 1 FROM (
452
474
  SELECT type, data_hash FROM session_events
453
475
  WHERE session_id = ? ORDER BY id DESC LIMIT ?
454
476
  ) AS recent
455
477
  WHERE recent.type = ? AND recent.data_hash = ?
456
- LIMIT 1`),e(U.evictLowestPriority,`DELETE FROM session_events WHERE id = (
478
+ LIMIT 1`),e(B.evictLowestPriority,`DELETE FROM session_events WHERE id = (
457
479
  SELECT id FROM session_events WHERE session_id = ?
458
480
  ORDER BY priority ASC, id ASC LIMIT 1
459
- )`),e(U.updateMetaLastEvent,`UPDATE session_meta
481
+ )`),e(B.updateMetaLastEvent,`UPDATE session_meta
460
482
  SET last_event_at = datetime('now'), event_count = event_count + 1
461
- WHERE session_id = ?`),e(U.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(U.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
462
- FROM session_meta WHERE session_id = ?`),e(U.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(U.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
483
+ WHERE session_id = ?`),e(B.ensureSession,"INSERT OR IGNORE INTO session_meta (session_id, project_dir) VALUES (?, ?)"),e(B.getSessionStats,`SELECT session_id, project_dir, started_at, last_event_at, event_count, compact_count
484
+ FROM session_meta WHERE session_id = ?`),e(B.incrementCompactCount,"UPDATE session_meta SET compact_count = compact_count + 1 WHERE session_id = ?"),e(B.upsertResume,`INSERT INTO session_resume (session_id, snapshot, event_count)
463
485
  VALUES (?, ?, ?)
464
486
  ON CONFLICT(session_id) DO UPDATE SET
465
487
  snapshot = excluded.snapshot,
466
488
  event_count = excluded.event_count,
467
489
  created_at = datetime('now'),
468
- consumed = 0`),e(U.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(U.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(U.claimLatestUnconsumedResume,`UPDATE session_resume
490
+ consumed = 0`),e(B.getResume,"SELECT snapshot, event_count, consumed FROM session_resume WHERE session_id = ?"),e(B.markResumeConsumed,"UPDATE session_resume SET consumed = 1 WHERE session_id = ?"),e(B.claimLatestUnconsumedResume,`UPDATE session_resume
469
491
  SET consumed = 1
470
492
  WHERE id = (
471
493
  SELECT id FROM session_resume
@@ -474,63 +496,201 @@ ${o}`}}var uw=v(()=>{"use strict"});import{execFileSync as TD}from"node:child_pr
474
496
  ORDER BY created_at DESC, id DESC
475
497
  LIMIT 1
476
498
  )
477
- RETURNING session_id, snapshot`),e(U.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(U.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(U.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(U.searchEvents,`SELECT id, session_id, category, type, data, created_at
499
+ RETURNING session_id, snapshot`),e(B.deleteEvents,"DELETE FROM session_events WHERE session_id = ?"),e(B.deleteMeta,"DELETE FROM session_meta WHERE session_id = ?"),e(B.deleteResume,"DELETE FROM session_resume WHERE session_id = ?"),e(B.searchEvents,`SELECT id, session_id, category, type, data, created_at
478
500
  FROM session_events
479
501
  WHERE project_dir = ?
480
502
  AND (data LIKE '%' || ? || '%' ESCAPE '\\' OR category LIKE '%' || ? || '%' ESCAPE '\\')
481
503
  AND (? IS NULL OR category = ?)
482
504
  ORDER BY id ASC
483
- LIMIT ?`),e(U.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(U.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
505
+ LIMIT ?`),e(B.getOldSessions,"SELECT session_id FROM session_meta WHERE started_at < datetime('now', ? || ' days')"),e(B.incrementToolCall,`INSERT INTO tool_calls (session_id, tool, calls, bytes_returned)
484
506
  VALUES (?, ?, 1, ?)
485
507
  ON CONFLICT(session_id, tool) DO UPDATE SET
486
508
  calls = calls + 1,
487
509
  bytes_returned = bytes_returned + excluded.bytes_returned,
488
- updated_at = datetime('now')`),e(U.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
510
+ updated_at = datetime('now')`),e(B.getToolCallTotals,`SELECT COALESCE(SUM(calls), 0) AS calls,
489
511
  COALESCE(SUM(bytes_returned), 0) AS bytes_returned
490
- FROM tool_calls WHERE session_id = ?`),e(U.getToolCallByTool,`SELECT tool, calls, bytes_returned
491
- FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`)}insertEvent(e,r,n="PostToolUse",o){let s=ag("sha256").update(r.data).digest("hex").slice(0,16).toUpperCase(),i=String(o?.projectDir??r.project_dir??"").trim(),a=String(o?.source??r.attribution_source??"unknown"),c=Number(o?.confidence??r.attribution_confidence??0),u=Number.isFinite(c)?Math.max(0,Math.min(1,c)):0,l=this.db.transaction(()=>{if(this.stmt(U.checkDuplicate).get(e,mw,r.type,s))return;this.stmt(U.getEventCount).get(e).cnt>=pw&&this.stmt(U.evictLowestPriority).run(e),this.stmt(U.insertEvent).run(e,r.type,r.category,r.priority,r.data,i,a,u,n,s),this.stmt(U.updateMetaLastEvent).run(e)});this.withRetry(()=>l())}bulkInsertEvents(e,r,n="PostToolUse",o){if(!r||r.length===0)return;if(r.length===1){this.insertEvent(e,r[0],n,o?.[0]);return}let s=r.map((a,c)=>{let u=ag("sha256").update(a.data).digest("hex").slice(0,16).toUpperCase(),l=o?.[c],d=String(l?.projectDir??a.project_dir??"").trim(),p=String(l?.source??a.attribution_source??"unknown"),f=Number(l?.confidence??a.attribution_confidence??0),m=Number.isFinite(f)?Math.max(0,Math.min(1,f)):0;return{event:a,dataHash:u,projectDir:d,attributionSource:p,attributionConfidence:m}}),i=this.db.transaction(()=>{let a=this.stmt(U.getEventCount).get(e).cnt;for(let c of s)this.stmt(U.checkDuplicate).get(e,mw,c.event.type,c.dataHash)||(a>=pw?this.stmt(U.evictLowestPriority).run(e):a++,this.stmt(U.insertEvent).run(e,c.event.type,c.event.category,c.event.priority,c.event.data,c.projectDir,c.attributionSource,c.attributionConfidence,n,c.dataHash));this.stmt(U.updateMetaLastEvent).run(e)});this.withRetry(()=>i())}getEvents(e,r){let n=r?.limit??1e3,o=r?.type,s=r?.minPriority;return o&&s!==void 0?this.stmt(U.getEventsByTypeAndPriority).all(e,o,s,n):o?this.stmt(U.getEventsByType).all(e,o,n):s!==void 0?this.stmt(U.getEventsByPriority).all(e,s,n):this.stmt(U.getEvents).all(e,n)}getEventCount(e){return this.stmt(U.getEventCount).get(e).cnt}getLatestAttributedProjectDir(e){return this.stmt(U.getLatestAttributedProject).get(e)?.project_dir||null}searchEvents(e,r,n,o){try{let s=e.replace(/[%_]/g,a=>"\\"+a),i=o??null;return this.stmt(U.searchEvents).all(n,s,s,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(U.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(U.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(U.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(U.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(U.getResume).get(e)??null}markResumeConsumed(e){this.stmt(U.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(U.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let o=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(U.incrementToolCall).run(e,r,o)}catch{}}getToolCallStats(e){try{let r=this.stmt(U.getToolCallTotals).get(e),n=this.stmt(U.getToolCallByTool).all(e),o={};for(let s of n)o[s.tool]={calls:s.calls,bytesReturned:s.bytes_returned};return{totalCalls:r?.calls??0,totalBytesReturned:r?.bytes_returned??0,byTool:o}}catch{return{totalCalls:0,totalBytesReturned:0,byTool:{}}}}deleteSession(e){this.db.transaction(()=>{this.stmt(U.deleteEvents).run(e),this.stmt(U.deleteResume).run(e),this.stmt(U.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(U.getOldSessions).all(r);for(let{session_id:o}of n)this.deleteSession(o);return n.length}}});import{existsSync as fw}from"node:fs";function hw(t,e,r){try{if(!fw(t))return;let n=new Qn({dbPath:t});try{let o=n.getLatestSessionId();if(!o)return;n.incrementToolCall(o,e,r)}finally{n.close()}}catch{}}function gw(t){try{if(!fw(t))return null;let e=new Qn({dbPath:t});try{let r=e.getLatestSessionId();if(!r)return null;let n=e.getToolCallStats(r),o={},s={};for(let[a,c]of Object.entries(n.byTool))o[a]=c.calls,s[a]=c.bytesReturned;let i=Date.now();try{let a=e.getSessionStats(r);if(a?.started_at){let c=Date.parse(`${a.started_at}Z`);Number.isFinite(c)&&c>0&&(i=c)}}catch{}return Object.keys(o).length===0&&Object.keys(s).length===0?{calls:o,bytesReturned:s,sessionStart:i}:{calls:o,bytesReturned:s,sessionStart:i}}finally{e.close()}}catch{return null}}var _w=v(()=>{"use strict";cg()});import{existsSync as ug,readFileSync as ID,readdirSync as AD,statSync as ND}from"node:fs";import{join as ss,isAbsolute as zD}from"node:path";import{homedir as jD}from"node:os";function vw(t,e=5,r,n,o){let s=[],i=o?.getInstructionFiles()??["CLAUDE.md"],a=o?.getConfigDir(),c=a?xw(r,a):n||ss(jD(),".claude"),u=o?.getMemoryDir(),l=u?xw(r,u):ss(c,"memory"),d=[];if(r)for(let p of i){let f=ss(r,p);ug(f)&&d.push({path:f,label:`project/${p}`})}if(c&&c!==r)for(let p of i){let f=ss(c,p);ug(f)&&d.push({path:f,label:`user/${p}`})}if(l&&ug(l))try{let p=AD(l).filter(f=>f.endsWith(".md"));for(let f of p)d.push({path:ss(l,f),label:`memory/${f}`})}catch(p){yw&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${p}
492
- `)}for(let p of d){if(s.length>=e)break;try{let f;try{if(f=ND(p.path),f.size>1e6)continue}catch{continue}let m=ID(p.path,"utf-8"),h=m.toLowerCase();for(let g of t){if(s.length>=e)break;let _=g.toLowerCase().split(/\s+/).filter(k=>k.length>=3);if(_.some(k=>{try{return new RegExp(`\\b${k.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(m)}catch{return h.includes(k)}})){let k=_.reduce((P,N)=>{let ce=h.indexOf(N);return ce>=0&&(P<0||ce<P)?ce:P},-1),E=Math.max(0,k-200),H=Math.min(m.length,k+500),z=m.lastIndexOf(`
493
-
494
- `,E),K=m.indexOf(`
495
-
496
- `,H);z>=0&&(E=z+2),K>=0&&(H=K);let Le=m.slice(E,H).trim();s.push({title:`[auto-memory] ${p.label}`,content:Le,source:p.label,origin:"auto-memory",timestamp:f.mtime.toISOString()});break}}}catch(f){yw&&process.stderr.write(`[ctx] auto-memory file read failed: ${f}
497
- `)}}return s.slice(0,e)}function xw(t,e){return e?zD(e)||!t?e:ss(t,e):t??""}var yw,bw=v(()=>{"use strict";yw=process.env.DEBUG?.includes("context-mode")});function Sw(t){let{query:e,limit:r,store:n,sort:o="relevance",source:s,contentType:i,sessionDB:a,projectDir:c,configDir:u,adapter:l}=t,d=[],p=new Date().toISOString();try{let f=n.searchWithFallback(e,r,s,i);d.push(...f.map(m=>({title:m.title,content:m.content,source:m.source,origin:"current-session",timestamp:m.timestamp||p,rank:m.rank,matchLayer:m.matchLayer,highlighted:m.highlighted,contentType:m.contentType})))}catch(f){lg&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
498
- `)}if(o==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",s);d.push(...f.map(m=>({title:`[${m.category}] ${m.type}`,content:m.data,source:"prior-session",origin:"prior-session",timestamp:m.created_at})))}}catch(f){lg&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
499
- `)}try{let f=vw([e],r,c,u,l);d.push(...f)}catch(f){lg&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
500
- `)}}for(let f of d)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return o==="timeline"&&d.sort((f,m)=>(f.timestamp||"").localeCompare(m.timestamp||"")),d.slice(0,r)}var lg,kw=v(()=>{"use strict";bw();lg=process.env.DEBUG?.includes("context-mode")});import{existsSync as dg,readdirSync as pg,statSync as DD}from"node:fs";import{join as Ai}from"node:path";import{homedir as ww}from"node:os";function MD(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function FD(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function Ni(t){let e=t?.sessionsDir??Ai(ww(),".claude","context-mode","sessions"),r=t?.memoryRoot??Ai(ww(),".claude","projects"),n=0,o=0,s={};if(dg(e)){let u=[];try{u=pg(e).filter(l=>l.endsWith(".db"))}catch{}if(u.length>0){let l=null;try{l=t?.loadDatabase?t.loadDatabase():zr()}catch{}if(l)for(let d of u){let p=Ai(e,d);try{let f=new l(p,{readonly:!0});try{let m=f.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),h=f.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n+=m?.cnt??0,o+=h?.cnt??0;try{let g=f.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let y of g)y.category&&(s[y.category]=(s[y.category]??0)+(y.cnt??0))}catch{}}finally{f.close()}}catch{}}}}let i=0,a=0,c={};if(dg(r)){let u=[];try{u=pg(r).filter(l=>{try{return DD(Ai(r,l)).isDirectory()}catch{return!1}})}catch{}for(let l of u){let d=Ai(r,l,"memory");if(!dg(d))continue;let p=[];try{p=pg(d).filter(f=>f.endsWith(".md"))}catch{continue}if(p.length!==0){a++,i+=p.length;for(let f of p){let m=FD(f);c[m]=(c[m]??0)+1}}}}return{totalEvents:n,totalSessions:o,autoMemoryCount:i,autoMemoryProjects:a,autoMemoryByPrefix:c,categoryCounts:s}}function eo(t){return t>=1024*1024?`${(t/1024/1024).toFixed(1)} MB`:t>=1024?`${(t/1024).toFixed(1)} KB`:`${Math.round(t)} B`}function UD(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 fg(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function mu(t){return`$${((Number.isFinite(t)&&t>0?t:0)*hu).toFixed(2)}`}function fu(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 $w(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0)return[];let n=e?.topN??2,o=[];o.push(""),o.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let s=e?.lifetime?.totalEvents??t.total_events,i=e?.lifetime?.totalSessions??t.session_count,a=i===0&&r>0?1:i,c=a===1?"1 session":`${fg(a)} sessions`,u=s*256+r;o.push(` ${fg(s)} events \xB7 ${c} \xB7 ~${mu(u)} saved lifetime`),o.push("");let l=e?.lifetime?.categoryCounts,d;l&&Object.keys(l).length>0?d=Object.entries(l).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:mg[h]||h})).sort((h,g)=>g.count-h.count):d=t.by_category;let p=d.slice(0,n),f=p.length>0?p[0].count:1;for(let h of p)o.push(` ${h.label.padEnd(18)} ${String(h.count).padStart(5)} ${fu(h.count,f,30)}`);let m=Math.max(0,d.length-n);return m>0&&o.push(` ... ${m} more categor${m===1?"y":"ies"}`),o}function Ew(t){if(!t||t.autoMemoryCount===0)return[];let e=[];e.push(""),e.push(`Auto-memory \u2713 ${t.autoMemoryCount} preference${t.autoMemoryCount===1?"":"s"} learned across ${t.autoMemoryProjects} project${t.autoMemoryProjects===1?"":"s"}`);let r=Object.entries(t.autoMemoryByPrefix).sort((o,s)=>s[1]-o[1]).slice(0,6),n=r.length>0?r[0][1]:1;for(let[o,s]of r)e.push(` ${o.padEnd(12)} ${String(s).padStart(2)} ${fu(s,n,20)}`);return e}function Tw(t,e){let r=[],n=mu(t),o=(e?.totalEvents??0)*256+t,s=mu(o);return r.push(""),r.push("\u2500".repeat(65)),r.push("Your AI talks less, remembers more, costs less."),r.push(`${n} this session \xB7 ${s} lifetime`),r.push("\u2500".repeat(65)),r}function gu(t,e,r,n){let o=[],s=UD(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),u=t.savings.total_bytes_returned,l=t.savings.total_calls,d=c+u,p=d>0?c/d*100:0,f=Math.round(c/4),m=u>0?Math.max(1,Math.round(d/Math.max(u,1))):0;if(c===0){o.push(`context-mode ${s} ${l} calls`),o.push(""),l===0?o.push("No tool calls yet. Use batch_execute or execute to start saving tokens."):o.push(`${eo(u)} entered context | 0 tokens saved`),o.push(...$w(t.projectMemory,{lifetime:i,sessionTokensSaved:0})),o.push(...Ew(i)),o.push(...Tw(0,i)),o.push("");let _=e?`v${e}`:"context-mode";return o.push(_),e&&r&&r!=="unknown"&&MD(r,e)&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
501
- `)}o.push(`${fg(f)} tokens saved \xB7 ${p.toFixed(1)}% reduction \xB7 ${s} \xB7 ~${mu(f)} saved (Opus)`),o.push(""),o.push(`Without context-mode |${fu(d,d)}| ${eo(d)}`),o.push(`With context-mode |${fu(u,d)}| ${eo(u)}`),o.push(""),m>=2?o.push(`${eo(c)} kept out of your conversation \u2014 ${m}\xD7 longer sessions before compact.`):o.push(`${eo(c)} kept out of your conversation. Never entered context.`),o.push("");let h=[`${l} calls`];t.cache&&t.cache.hits>0&&h.push(`${t.cache.hits} cache hits (+${eo(t.cache.bytes_saved)})`),o.push(h.join(" \xB7 "));let g=t.savings.by_tool.filter(_=>_.calls>0);if(g.length>=2){o.push("");let _=g.map(x=>{let k=x.context_kb*1024,E=p<100?k/(1-p/100):k,H=Math.max(0,E-k);return{...x,returnedBytes:k,estimatedSaved:H}}).sort((x,k)=>k.estimatedSaved-x.estimatedSaved);for(let x of _){let k=x.tool.length>22?x.tool.slice(0,19)+"...":x.tool;o.push(` ${k.padEnd(22)} ${String(x.calls).padStart(4)} calls ${eo(x.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let _=a.filter(x=>x.median_concurrency!=null&&(x.max_concurrency??1)>1);if(_.length>0){o.push(""),o.push("Parallel I/O \u2713 one call did the work of many \u2014 faster runs, lower bill, same answer.");for(let x of _){let k=x.tool_name.replace(/^mcp__.*?__/,"");o.push(` ${k.padEnd(22)} ${x.calls} batches \xB7 ${x.median_concurrency} typical, ${x.max_concurrency} peak`)}}}o.push(...$w(t.projectMemory,{lifetime:i,sessionTokensSaved:f})),o.push(...Ew(i)),o.push(...Tw(f,i)),o.push("");let y=e?`v${e}`:"context-mode";return o.push(y),e&&r&&r!=="unknown"&&r!==e&&o.push(`Update available: v${e} -> v${r} | ctx_upgrade`),o.join(`
502
- `)}var mg,LD,is,hu,Pw=v(()=>{"use strict";ns();mg={file:"Files tracked",rule:"Project rules (CLAUDE.md)",prompt:"Your requests saved",mcp:"Plugin tools used",git:"Git operations",env:"Environment setup",error:"Errors caught",task:"Tasks in progress",decision:"Your decisions",cwd:"Working directory",skill:"Skills used",subagent:"Delegated work",intent:"Session mode",data:"Data references",role:"Behavioral directives"},LD={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"},is=class{db;constructor(e){this.db=e}static contextSavingsTotal(e,r){let n=e-r,o=e>0?Math.round(n/e*1e3)/10:0;return{rawBytes:e,contextBytes:r,savedBytes:n,savedPercent:o}}static thinkInCodeComparison(e,r){let n=r>0?Math.round(e/r*10)/10:0;return{fileBytes:e,outputBytes:r,ratio:n}}static toolSavings(e){return e.map(r=>({...r,savedBytes:r.rawBytes-r.contextBytes}))}static sandboxIO(e,r){return{inputBytes:e,outputBytes:r}}getMcpToolUsage(){let e;try{e=this.db.prepare("SELECT data FROM session_events WHERE category = 'mcp_tool_call'").all()}catch{return[]}let r=new Map;for(let o of e){let s;try{s=JSON.parse(o.data)}catch{continue}let i=typeof s.tool_name=="string"?s.tool_name:null;if(!i)continue;let a=r.get(i)??{calls:0,concurrencies:[]};if(a.calls+=1,s.truncated!==!0&&s.params&&typeof s.params=="object"){let c=s.params.concurrency;typeof c=="number"&&Number.isFinite(c)&&c>0&&a.concurrencies.push(c)}r.set(i,a)}let n=[];for(let[o,s]of r){let i=null,a=null;if(s.concurrencies.length>0){let c=[...s.concurrencies].sort((l,d)=>l-d),u=Math.floor(c.length/2);i=c.length%2===0?(c[u-1]+c[u])/2:c[u],a=c[c.length-1]}n.push({tool_name:o,calls:s.calls,median_concurrency:i,max_concurrency:a})}return n.sort((o,s)=>s.calls-o.calls||o.tool_name.localeCompare(s.tool_name)),n}queryAll(e){let n=this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??"",o=Object.values(e.bytesReturned).reduce((N,ce)=>N+ce,0),s=Object.values(e.calls).reduce((N,ce)=>N+ce,0),i=e.bytesIndexed+e.bytesSandboxed,a=i+o,c=a/Math.max(o,1),u=a>0?Math.round((1-o/a)*100):0,l=new Set([...Object.keys(e.calls),...Object.keys(e.bytesReturned)]),d=Array.from(l).sort().map(N=>({tool:N,calls:e.calls[N]||0,context_kb:Math.round((e.bytesReturned[N]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[N]||0)/4)})),f=((Date.now()-e.sessionStart)/6e4).toFixed(1),m;if(e.cacheHits>0||e.cacheBytesSaved>0){let N=a+e.cacheBytesSaved,ce=N/Math.max(o,1),De=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3)));m={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:De,total_with_cache:N,total_savings_ratio:ce}}let h=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,g=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),_=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,x=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),k=x?!x.consumed:!1,E=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),H=new Map;for(let N of E){H.has(N.category)||H.set(N.category,new Set);let ce=H.get(N.category);if(ce.size<5){let De=N.data;N.category==="file"?De=N.data.split("/").pop()||N.data:(N.category==="prompt"||N.category==="user-prompt")&&(De=De.length>50?De.slice(0,47)+"...":De),De.length>40&&(De=De.slice(0,37)+"..."),ce.add(De)}}let z=g.map(N=>({category:N.category,count:N.cnt,label:mg[N.category]||N.category,preview:H.get(N.category)?Array.from(H.get(N.category)).join(", "):"",why:LD[N.category]||"Survives context resets"})),K=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(N=>N.cnt>0).map(N=>({category:N.category,count:N.cnt,label:mg[N.category]||N.category}));return{savings:{processed_kb:Math.round(a/1024*10)/10,entered_kb:Math.round(o/1024*10)/10,saved_kb:Math.round(i/1024*10)/10,pct:u,savings_ratio:Math.round(c*10)/10,by_tool:d,total_calls:s,total_bytes_returned:o,kept_out:i,total_processed:a},cache:m,session:{id:n,uptime_min:f},continuity:{total_events:h,by_category:z,compact_count:_,resume_ready:k},projectMemory:{total_events:K.cnt,session_count:K.sessions,by_category:P}}}};hu=15/1e6});var Ww={};Ze(Ww,{buildBatchNodeOptionsPrefix:()=>qw,classifyIp:()=>Tg,extractSnippet:()=>$g,formatBatchQueryResults:()=>Hw,positionsFromHighlight:()=>Zw,runBatchCommands:()=>Bw});import{createRequire as Mw}from"node:module";import{createHash as ZD}from"node:crypto";import{existsSync as je,unlinkSync as _r,readdirSync as HD,readFileSync as vg,writeFileSync as bg,renameSync as qD,rmSync as vu,mkdirSync as zi,cpSync as BD,statSync as Rw,symlinkSync as VD,lstatSync as WD}from"node:fs";import{execSync as qt}from"node:child_process";import{join as pe,dirname as nr,resolve as ot,sep as GD,isAbsolute as KD}from"node:path";import{fileURLToPath as JD}from"node:url";import{homedir as ro,tmpdir as Sg,cpus as YD}from"node:os";import{request as XD}from"node:https";function QD(t){try{let e=xr();if(!je(e))return;let r=HD(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let o=pe(e,n);try{t.index({path:o,source:"session-events"}),_r(o)}catch{}}}catch{}}function xr(){if(cs)return cs.getSessionDir();try{let e=wr(),r=wl(e.platform);if(r){let n=pe(ro(),...r,"context-mode","sessions");return zi(n,{recursive:!0}),n}}catch{}let t=pe(ro(),".claude","context-mode","sessions");return zi(t,{recursive:!0}),t}function Mi(){return process.env.CLAUDE_PROJECT_DIR||process.env.GEMINI_PROJECT_DIR||process.env.VSCODE_CWD||process.env.OPENCODE_PROJECT_DIR||process.env.PI_PROJECT_DIR||process.env.IDEA_INITIAL_DIRECTORY||process.env.CONTEXT_MODE_PROJECT_DIR||process.cwd()}function eM(t){return KD(t)?t:ot(Mi(),t)}function us(){let e=Mi().replace(/\\/g,"/");return ZD("sha256").update(e).digest("hex").slice(0,16)}function Lw(){return pe(xr(),`${us()}${Ii()}.db`)}function yg(){let t=us(),e=xr(),r=pe(nr(e),"content");return zi(r,{recursive:!0}),pe(r,`${t}.db`)}function no(){if(!yr){let t=yg();yr=new pu(t);try{let e=nr(yg());tg(e,14),yr.cleanupStaleSources(14);let r=pe(ro(),".context-mode","content");je(r)&&tg(r,0)}catch{}eg()}return QD(yr),yr}async function Ow(){return new Promise(t=>{let e=XD("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}function nM(){let t=cs?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function oM(t,e){let r=t.split(".").map(Number),n=e.split(".").map(Number);for(let o=0;o<3;o++){if((r[o]??0)>(n[o]??0))return!0;if((r[o]??0)<(n[o]??0))return!1}return!1}function sM(){return!Mr||Mr==="unknown"?!1:oM(Mr,Dr)}function iM(){if(!sM())return!1;let t=Date.now();if(_u>=tM){if(t-Cw<rM)return!1;_u=0}return _u===0&&(Cw=t),_u++,!0}function aM(){if(!Iw){Iw=!0;try{let t=ot(ro(),".claude","plugins","installed_plugins.json");if(!je(t))return;let e=JSON.parse(vg(t,"utf-8")),r=ot(ro(),".claude","plugins","cache"),n=je(ot(kt,"package.json"))?kt:nr(kt);for(let[o,s]of Object.entries(e.plugins??{}))if(o==="context-mode@context-mode")for(let i of s){let a=i.installPath;if(!a||je(a)||!ot(a).startsWith(r+GD))continue;try{WD(a).isSymbolicLink()&&_r(a)}catch{}let c=nr(a);je(c)||zi(c,{recursive:!0}),je(n)&&VD(n,a,process.platform==="win32"?"junction":void 0)}}catch{}}}function W(t,e){if(aM(),iM()&&e.content.length>0){let n=nM();e.content[0].text=`\u26A0\uFE0F context-mode v${Dr} outdated \u2192 v${Mr} available. Upgrade: ${n}
503
-
504
- `+e.content[0].text}let r=e.content.reduce((n,o)=>n+Buffer.byteLength(o.text),0);return re.calls[t]=(re.calls[t]||0)+1,re.bytesReturned[t]=(re.bytesReturned[t]||0)+r,bu(),setImmediate(()=>hw(Lw(),t,r)),e}function or(t){re.bytesIndexed+=t,bu()}function Fw(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`;return pe(xr(),`stats-${t}.json`)}function bu(){let t=Date.now();if(!(t-xg<cM)){xg=t;try{let e=Object.values(re.bytesReturned).reduce((d,p)=>d+p,0),r=Object.values(re.calls).reduce((d,p)=>d+p,0),n=re.bytesIndexed+re.bytesSandboxed+re.cacheBytesSaved,o=n+e,s=o>0?Math.round((1-e/o)*100):0,i=Math.round(n/4),a=yu?.tokens??0;if(!yu||t-yu.computedAt>lM)try{a=(Ni({sessionsDir:xr()})?.totalEvents??0)*dM,yu={tokens:a,computedAt:t}}catch{}let c={schemaVersion:uM,version:Dr,updated_at:t,session_start:re.sessionStart,uptime_ms:t-re.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:re.bytesIndexed,bytes_sandboxed:re.bytesSandboxed,cache_hits:re.cacheHits,cache_bytes_saved:re.cacheBytesSaved,kept_out:n,total_processed:o,reduction_pct:s,tokens_saved:i,dollars_saved_session:+(i*hu).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*hu).toFixed(2),by_tool:Object.fromEntries(Object.keys({...re.calls,...re.bytesReturned}).map(d=>[d,{calls:re.calls[d]||0,bytes:re.bytesReturned[d]||0}]))},u=Fw(),l=`${u}.tmp`;bg(l,JSON.stringify(c)),qD(l,u)}catch{}}}function wg(t,e){try{let r=og(process.env.CLAUDE_PROJECT_DIR),n=sg(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 Uw(t,e,r){try{let n=aw(t,e);if(n.length===0)return null;let o=og(process.env.CLAUDE_PROJECT_DIR);for(let s of n){let i=sg(s,o);if(i.decision==="deny")return W(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${s}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function pM(t,e){try{let r=Mi(),n=sw("Read",r),o=iw(t,n,process.platform==="win32",r);if(o.denied)return W(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${o.matchedPattern}`}],isError:!0})}catch{}return null}function Zw(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===hM){for(e.push(r),n++;n<t.length&&t[n]!==gM;)r++,n++;n<t.length&&n++}else r++,n++;return e}function $g(t,e,r=1500,n){if(t.length<=r)return t;let o=[];if(n)for(let u of Zw(n))o.push(u);if(o.length===0){let u=e.toLowerCase().split(/\s+/).filter(d=>d.length>2),l=t.toLowerCase();for(let d of u){let p=l.indexOf(d);for(;p!==-1;)o.push(p),p=l.indexOf(d,p+1)}}if(o.length===0)return t.slice(0,r)+`
505
- \u2026`;o.sort((u,l)=>u-l);let s=300,i=[];for(let u of o){let l=Math.max(0,u-s),d=Math.min(t.length,u+s);i.length>0&&l<=i[i.length-1][1]?i[i.length-1][1]=d:i.push([l,d])}let a=[],c=0;for(let[u,l]of i){if(c>=r)break;let d=t.slice(u,Math.min(l,u+(r-c)));a.push((u>0?"\u2026":"")+d+(l<t.length?"\u2026":"")),c+=d.length}return a.join(`
506
-
507
- `)}function Hw(t,e,r,n=80*1024){let o=[],s=0;for(let i of e){if(s>n){o.push(`## ${i}
512
+ FROM tool_calls WHERE session_id = ?`),e(B.getToolCallByTool,`SELECT tool, calls, bytes_returned
513
+ FROM tool_calls WHERE session_id = ? ORDER BY calls DESC`),e(B.getEventBytesSummary,`SELECT COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
514
+ COALESCE(SUM(bytes_returned), 0) AS bytes_returned
515
+ FROM session_events WHERE session_id = ?`)}insertEvent(e,r,n="PostToolUse",s,o){let i=Bi("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=Au(o?.bytesAvoided),m=Au(o?.bytesReturned),f=this.db.transaction(()=>{if(this.stmt(B.checkDuplicate).get(e,bE,r.type,i))return;this.stmt(B.getEventCount).get(e).cnt>=vE&&this.stmt(B.evictLowestPriority).run(e),this.stmt(B.insertEvent).run(e,r.type,r.category,r.priority,r.data,a,c,d,l,m,n,i),this.stmt(B.updateMetaLastEvent).run(e)});this.withRetry(()=>f())}bulkInsertEvents(e,r,n="PostToolUse",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=Bi("sha256").update(c.data).digest("hex").slice(0,16).toUpperCase(),l=s?.[u],m=String(l?.projectDir??c.project_dir??"").trim(),f=String(l?.source??c.attribution_source??"unknown"),p=Number(l?.confidence??c.attribution_confidence??0),h=Number.isFinite(p)?Math.max(0,Math.min(1,p)):0,g=o?.[u],y=Au(g?.bytesAvoided),_=Au(g?.bytesReturned);return{event:c,dataHash:d,projectDir:m,attributionSource:f,attributionConfidence:h,bytesAvoided:y,bytesReturned:_}}),a=this.db.transaction(()=>{let c=this.stmt(B.getEventCount).get(e).cnt;for(let u of i)this.stmt(B.checkDuplicate).get(e,bE,u.event.type,u.dataHash)||(c>=vE?this.stmt(B.evictLowestPriority).run(e):c++,this.stmt(B.insertEvent).run(e,u.event.type,u.event.category,u.event.priority,u.event.data,u.projectDir,u.attributionSource,u.attributionConfidence,u.bytesAvoided,u.bytesReturned,n,u.dataHash));this.stmt(B.updateMetaLastEvent).run(e)});this.withRetry(()=>a())}getEvents(e,r){let n=r?.limit??1e3,s=r?.type,o=r?.minPriority;return s&&o!==void 0?this.stmt(B.getEventsByTypeAndPriority).all(e,s,o,n):s?this.stmt(B.getEventsByType).all(e,s,n):o!==void 0?this.stmt(B.getEventsByPriority).all(e,o,n):this.stmt(B.getEvents).all(e,n)}getEventCount(e){return this.stmt(B.getEventCount).get(e).cnt}getEventBytesSummary(e){let r=this.stmt(B.getEventBytesSummary).get(e);return{bytesAvoided:Number(r?.bytes_avoided??0),bytesReturned:Number(r?.bytes_returned??0)}}getLatestAttributedProjectDir(e){return this.stmt(B.getLatestAttributedProject).get(e)?.project_dir||null}searchEvents(e,r,n,s){try{let o=e.replace(/[%_]/g,a=>"\\"+a),i=s??null;return this.stmt(B.searchEvents).all(n,o,o,i,i,r)}catch{return[]}}ensureSession(e,r){this.stmt(B.ensureSession).run(e,r)}getSessionStats(e){return this.stmt(B.getSessionStats).get(e)??null}incrementCompactCount(e){this.stmt(B.incrementCompactCount).run(e)}upsertResume(e,r,n){this.stmt(B.upsertResume).run(e,r,n??0)}getResume(e){return this.stmt(B.getResume).get(e)??null}markResumeConsumed(e){this.stmt(B.markResumeConsumed).run(e)}claimLatestUnconsumedResume(e){let r=this.stmt(B.claimLatestUnconsumedResume).get(e);return r?{sessionId:r.session_id,snapshot:r.snapshot}:null}getLatestSessionId(){try{return this.db.prepare("SELECT session_id FROM session_meta ORDER BY started_at DESC LIMIT 1").get()?.session_id??null}catch{return null}}incrementToolCall(e,r,n=0){let s=Number.isFinite(n)&&n>0?Math.round(n):0;try{this.stmt(B.incrementToolCall).run(e,r,s)}catch{}}getToolCallStats(e){try{let r=this.stmt(B.getToolCallTotals).get(e),n=this.stmt(B.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(B.deleteEvents).run(e),this.stmt(B.deleteResume).run(e),this.stmt(B.deleteMeta).run(e)})()}cleanupOldSessions(e=7){let r=`-${e}`,n=this.stmt(B.getOldSessions).all(r);for(let{session_id:s}of n)this.deleteSession(s);return n.length}}});import{unlinkSync as CL}from"node:fs";import{join as ty}from"node:path";function ry(t,e){try{return CL(t),e.push(t),!0}catch{return!1}}function ju(t,e){let r=!1;for(let n of OL)ry(`${t}${n}`,e)&&n===""&&(r=!0);return r}function wE(t){let{projectDir:e,sessionsDir:r,storePath:n,contentDir:s,legacyContentDir:o,contentHash:i}=t,a=[],c=[],u=!1;if(n&&ju(n,c)&&(u=!0),s){let g=us(e),y=cs(e),_=g===y?[g]:[g,y];for(let x of _){let S=ty(s,`${x}.db`);ju(S,c)&&(u=!0)}}if(u&&a.push("knowledge base (FTS5)"),o){if(!i)throw new TypeError("purgeSession: contentHash is required when legacyContentDir is provided");let g=ty(o,`${i}.db`);ju(g,c)}let d=ey(e),l=us(e),m=cs(e),f=l===m?[l]:[l,m],p=!1,h=!1;for(let g of f){let y=ty(r,`${g}${d}`);ju(`${y}.db`,c)&&(p=!0),ry(`${y}-events.md`,c)&&(h=!0),ry(`${y}.cleanup`,c)}return p&&a.push("session events DB"),h&&a.push("session events markdown"),{deleted:a,wipedPaths:c}}var OL,EE=v(()=>{"use strict";Vi();OL=["","-wal","-shm"]});import{existsSync as IL}from"node:fs";function ny(t,e){try{if(!IL(t))return;let r=new Lr({dbPath:t});try{let n=r.getLatestSessionId();if(!n)return;e(r,n)}finally{try{r.close()}catch{}}}catch{}}function $E(t){ny(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 TE(t){ny(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 PE(t){ny(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 RE=v(()=>{"use strict";Vi()});import{existsSync as CE}from"node:fs";function OE(t,e,r){try{if(!CE(t))return;let n=new Lr({dbPath:t});try{let s=n.getLatestSessionId();if(!s)return;n.incrementToolCall(s,e,r)}finally{n.close()}}catch{}}function IE(t){try{if(!CE(t))return null;let e=new Lr({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 AE=v(()=>{"use strict";Vi()});import{existsSync as sy,readFileSync as AL,readdirSync as NL,statSync as DL}from"node:fs";import{join as Wi,isAbsolute as ML}from"node:path";function ME(t,e=5,r,n,s){let o=[],i=s?.getInstructionFiles()??["CLAUDE.md"],a=s?.getConfigDir(),u=(a?DE(r,a):null)??n??We(),d=s?.getMemoryDir(),l=d?DE(r,d):Wi(u,"memory"),m=[];if(r)for(let f of i){let p=Wi(r,f);sy(p)&&m.push({path:p,label:`project/${f}`})}if(u&&u!==r)for(let f of i){let p=Wi(u,f);sy(p)&&m.push({path:p,label:`user/${f}`})}if(l&&sy(l))try{let f=NL(l).filter(p=>p.endsWith(".md"));for(let p of f)m.push({path:Wi(l,p),label:`memory/${p}`})}catch(f){NE&&process.stderr.write(`[ctx] auto-memory dir scan failed: ${f}
516
+ `)}for(let f of m){if(o.length>=e)break;try{let p;try{if(p=DL(f.path),p.size>1e6)continue}catch{continue}let h=AL(f.path,"utf-8"),g=h.toLowerCase();for(let y of t){if(o.length>=e)break;let x=y.toLowerCase().split(/\s+/).filter(w=>w.length>=3);if(x.some(w=>{try{return new RegExp(`\\b${w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`,"i").test(h)}catch{return g.includes(w)}})){let w=x.reduce((R,V)=>{let oe=g.indexOf(V);return oe>=0&&(R<0||oe<R)?oe:R},-1),I=Math.max(0,w-200),O=Math.min(h.length,w+500),C=h.lastIndexOf(`
517
+
518
+ `,I),F=h.indexOf(`
519
+
520
+ `,O);C>=0&&(I=C+2),F>=0&&(O=F);let T=h.slice(I,O).trim();o.push({title:`[auto-memory] ${f.label}`,content:T,source:f.label,origin:"auto-memory",timestamp:p.mtime.toISOString()});break}}}catch(p){NE&&process.stderr.write(`[ctx] auto-memory file read failed: ${p}
521
+ `)}}return o.slice(0,e)}function DE(t,e){return e?ML(e)||!t?e:Wi(t,e):t??""}var NE,jE=v(()=>{"use strict";Wr();NE=process.env.DEBUG?.includes("context-mode")});function zE(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 f=n.searchWithFallback(e,r,o,i);l.push(...f.map(p=>({title:p.title,content:p.content,source:p.source,origin:"current-session",timestamp:p.timestamp||m,rank:p.rank,matchLayer:p.matchLayer,highlighted:p.highlighted,contentType:p.contentType})))}catch(f){oy&&process.stderr.write(`[ctx] ContentStore search failed: ${f}
522
+ `)}if(s==="timeline"){try{if(a){let f=a.searchEvents(e,r,c||"",o);l.push(...f.map(p=>({title:`[${p.category}] ${p.type}`,content:p.data,source:"prior-session",origin:"prior-session",timestamp:p.created_at})))}}catch(f){oy&&process.stderr.write(`[ctx] SessionDB search failed: ${f}
523
+ `)}try{let f=ME([e],r,c,u,d);l.push(...f)}catch(f){oy&&process.stderr.write(`[ctx] auto-memory search failed: ${f}
524
+ `)}}for(let f of l)f.timestamp&&!f.timestamp.includes("T")&&(f.timestamp=f.timestamp.replace(" ","T")+"Z");return s==="timeline"&&l.sort((f,p)=>(f.timestamp||"").localeCompare(p.timestamp||"")),l.slice(0,r)}var oy,LE=v(()=>{"use strict";jE();oy=process.env.DEBUG?.includes("context-mode")});import{execFileSync as jL}from"node:child_process";import{existsSync as ls,readdirSync as _o,statSync as zL}from"node:fs";import{homedir as Uu}from"node:os";import{join as At,sep as LL}from"node:path";function WE(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 UL(t){let e=t?.home??Uu();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=At(e,...s,"context-mode");return{name:n,sessionsDir:At(o,"sessions"),contentDir:At(o,"content")}})}function HL(t){let r=t.replace(/\.md$/i,"").match(/^([a-z]+)/i);return r?r[1].toLowerCase():"other"}function Gi(t){let e=We(),r=t?.sessionsDir??At(e,"context-mode","sessions"),n=t?.memoryRoot??At(e,"projects"),s=0,o=0,i=0,a=Number.POSITIVE_INFINITY,c=new Set,u={};if(ls(r)){let f=[];try{f=_o(r).filter(p=>p.endsWith(".db"))}catch{}if(f.length>0){let p=null;try{p=t?.loadDatabase?t.loadDatabase():Xt()}catch{}if(p)for(let h of f){let g=At(r,h);try{let y=new p(g,{readonly:!0});try{let _=y.prepare("SELECT COUNT(*) AS cnt FROM session_events").get(),x=y.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();s+=_?.cnt??0,o+=x?.cnt??0;try{let S=y.prepare("SELECT category, COUNT(*) AS cnt FROM session_events GROUP BY category").all();for(let w of S)w.category&&(u[w.category]=(u[w.category]??0)+(w.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 w=S.t.endsWith("Z")?S.t:S.t+"Z",I=Date.parse(w);Number.isFinite(I)&&I<a&&(a=I)}}catch{}try{let S=y.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let w of S)w.p&&c.add(w.p)}catch{}}finally{y.close()}}catch{}}}}let d=0,l=0,m={};if(ls(n)){let f=[];try{f=_o(n).filter(p=>{try{return zL(At(n,p)).isDirectory()}catch{return!1}})}catch{}for(let p of f){let h=At(n,p,"memory");if(!ls(h))continue;let g=[];try{g=_o(h).filter(y=>y.endsWith(".md"))}catch{continue}if(g.length!==0){l++,d+=g.length;for(let y of g){let _=HL(y);m[_]=(m[_]??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 GE(t){let e=t.sessionsDir??At(Uu(),".claude","context-mode","sessions"),r=t.sessionId,n={sessionId:r,events:0,dbCount:0,daysAlive:0,snapshotBytes:0,snapshotsConsumed:0,byCategory:[]};if(!r||!ls(e))return n;let s=[];try{s=_o(e).filter(x=>!(!x.endsWith(".db")||t.worktreeHash&&!x.startsWith(t.worktreeHash)))}catch{return n}if(s.length===0)return n;let o=null;try{o=t.loadDatabase?t.loadDatabase():Xt()}catch{return n}if(!o)return n;let i={},a=0,c=0,u=0,d=0,l=Number.POSITIVE_INFINITY,m=0,f=0,p=new Map,h=x=>Math.floor(x/864e5)*864e5;for(let x of s){let S=At(e,x),w=!1;try{let I=new o(S,{readonly:!0});try{let O=I.prepare("SELECT category, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY category").all(r);for(let F of O)F.category&&(i[F.category]=(i[F.category]??0)+(F.cnt??0),a+=F.cnt??0,w=!0);let C=I.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events WHERE session_id = ?").get(r);if(C?.mn){let F=Date.parse(C.mn+(C.mn.endsWith("Z")?"":"Z"));Number.isFinite(F)&&F<l&&(l=F)}if(C?.mx){let F=Date.parse(C.mx+(C.mx.endsWith("Z")?"":"Z"));Number.isFinite(F)&&F>m&&(m=F)}try{let F=I.prepare("SELECT strftime('%s', created_at) AS sec, COUNT(*) AS cnt FROM session_events WHERE session_id = ? GROUP BY date(created_at)").all(r);for(let T of F){if(!T.sec)continue;let R=parseInt(T.sec,10)*1e3;if(!Number.isFinite(R))continue;let V=h(R),oe=p.get(V)??{count:0,rescueBytes:0};oe.count+=T.cnt??0,p.set(V,oe)}}catch{}try{let F=I.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(F?.bytes&&(u+=F.bytes),F?.n&&(d+=F.n),F?.lastSec){let T=parseInt(F.lastSec,10)*1e3;if(Number.isFinite(T)&&T>f&&(f=T),Number.isFinite(T)&&(F?.bytes??0)>0){let R=h(T),V=p.get(R)??{count:0,rescueBytes:0};V.rescueBytes=Math.max(V.rescueBytes,F.bytes),p.set(R,V)}}}catch{}}finally{I.close()}}catch{}w&&c++}let g=l<m?(m-l)/864e5:0,y=Object.entries(i).filter(([,x])=>x>0).map(([x,S])=>({category:x,count:S,label:zu[x]||x})).sort((x,S)=>S.count-x.count),_=[...p.entries()].sort((x,S)=>x[0]-S[0]).map(([x,S])=>({ms:x,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:f>0?f:void 0,byDay:_}}function iy(t){let e={eventDataBytes:0,bytesAvoided:0,bytesReturned:0,snapshotBytes:0,totalSavedTokens:0},r=t.sessionsDir??At(Uu(),".claude","context-mode","sessions");if(!ls(r))return e;let n=[];try{n=_o(r).filter(d=>!(!d.endsWith(".db")||t.worktreeHash&&!d.startsWith(t.worktreeHash)))}catch{return e}if(n.length===0)return e;let s=null;try{s=t.loadDatabase?t.loadDatabase():Xt()}catch{return e}if(!s)return e;let o=0,i=0,a=0,c=0;for(let d of n){let l=At(r,d);try{let m=new s(l,{readonly:!0});try{if(t.sessionId){let f=m.prepare(`SELECT
525
+ COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
526
+ COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
527
+ COALESCE(SUM(bytes_returned), 0) AS bytes_returned
528
+ FROM session_events WHERE session_id = ?`).get(t.sessionId);f&&(o+=Number(f.data_bytes??0),i+=Number(f.bytes_avoided??0),a+=Number(f.bytes_returned??0));try{let p=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume WHERE session_id = ?").get(t.sessionId);p?.bytes&&(c+=Number(p.bytes))}catch{}}else{let f=m.prepare(`SELECT
529
+ COALESCE(SUM(LENGTH(data)), 0) AS data_bytes,
530
+ COALESCE(SUM(bytes_avoided), 0) AS bytes_avoided,
531
+ COALESCE(SUM(bytes_returned), 0) AS bytes_returned
532
+ FROM session_events`).get();f&&(o+=Number(f.data_bytes??0),i+=Number(f.bytes_avoided??0),a+=Number(f.bytes_returned??0));try{let p=m.prepare("SELECT COALESCE(SUM(LENGTH(snapshot)), 0) AS bytes FROM session_resume").get();p?.bytes&&(c+=Number(p.bytes))}catch{}}}finally{m.close()}}catch{}}let u=Math.floor((o+i+c)/4);return{eventDataBytes:o,bytesAvoided:i,bytesReturned:a,snapshotBytes:c,totalSavedTokens:u}}function BL(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(!ls(t.sessionsDir))return n;let s=[];try{s=_o(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=At(t.sessionsDir,d);try{let m=new o(l,{readonly:!0});try{let f=m.prepare("SELECT COUNT(*) AS cnt, COALESCE(SUM(LENGTH(data)), 0) AS bytes FROM session_events").get();f&&(n.eventCount+=Number(f.cnt??0),n.dataBytes+=Number(f.bytes??0));try{let p=m.prepare("SELECT COUNT(*) AS cnt FROM session_meta").get();n.sessionCount+=Number(p?.cnt??0)}catch{}try{let p=m.prepare("SELECT COALESCE(SUM(length(snapshot)), 0) AS bytes FROM session_resume WHERE consumed = 1").get();p?.bytes&&(n.rescueBytes+=Number(p.bytes))}catch{}try{let p=m.prepare("SELECT MIN(created_at) AS mn, MAX(created_at) AS mx FROM session_events").get();if(p?.mn){let h=Date.parse(p.mn+(p.mn.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h<n.firstMs&&(n.firstMs=h)}if(p?.mx){let h=Date.parse(p.mx+(p.mx.endsWith("Z")?"":"Z"));Number.isFinite(h)&&h>n.lastMs&&(n.lastMs=h)}}catch{}try{let p=m.prepare("SELECT DISTINCT project_dir AS p FROM session_events WHERE project_dir != ''").all();for(let h of p)h.p&&i.add(h.p)}catch{}try{let p=m.prepare("SELECT DISTINCT session_id AS s FROM session_events").all();for(let h of p)h.s&&a.add(h.s)}catch{}}finally{m.close()}}catch{}}n.projectDirs=Array.from(i),n.uuidConvs=a.size;let c=n.eventCount>0?n.dataBytes/n.eventCount:0,u=n.lastMs>0&&r.nowMs-n.lastMs<=r.recencyMs;return n.isReal=n.eventCount>=r.minEvents&&i.size>=r.minProjects&&u&&c>=r.minAvgBytes,n}function Hu(t){let e=UL({home:t?.home}),r=t?.loadDatabase??Xt,n={...ZL,...t?.filter??{},nowMs:t?.filter?.nowMs??Date.now()},s=[],o=0,i=0,a=0;for(let c of e){if(!ls(c.sessionsDir))continue;let u=BL(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 Lu(t){return qL[t]??t}function et(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 VL(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 WL(){let t=process.env??{},e=t.CONTEXT_MODE_LOCALE??"";if(!e){if(process.platform==="darwin")try{let n=jL("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 FE(t){let e=Uu();return e?t===e?"~":t.startsWith(e+LL)?"~"+t.slice(e.length):t:t}function GL(t,e,r){if(!Number.isFinite(e)||e<=0)return[];let n=e*15/1e6,s=(h,g=2)=>h.toFixed(g),o=Math.round(n/20),i=(n/200).toFixed(1),a=Math.round(n/73.67),c=Math.round(n*10),u=r>0?Math.round(n*10/r*365):0,d=(e*3/1e6).toFixed(2),l=(e*2.5/1e6).toFixed(2),m=(e*1.25/1e6).toFixed(2),f=(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 ${et(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 KL(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*qE,f=Math.round((e.snapshotBytes??0)/4),p=m+f,h=s?.conversation?.totalSavedTokens??0,g=Math.max(p,h),y=(r?.totalEvents??0)*qE,_=Math.round((r?.rescueBytes??0)/4),x=y+_,S=s?.lifetime?.totalSavedTokens??0,w=Math.max(x,S),I=Math.max(1,Math.round(w*.02)),O=n?.totalBytes&&n.totalBytes>0?n.totalBytes:w*4,C=s?.conversation?s.conversation.eventDataBytes+s.conversation.bytesAvoided+s.conversation.snapshotBytes:g*4,F=e.daysAlive>=1?`${e.daysAlive.toFixed(1)} days alive \xB7 still going`:`${Math.max(1,Math.round(e.daysAlive*24))} hr alive \xB7 still going`,T=r?.firstEventMs??n?.perAdapter?.[0]?.firstMs??0,R=T>0?Math.max(1,Math.round((c-T)/864e5)):0,V=n?.totalSessions??r?.totalSessions??1,oe=n?.perAdapter.filter(Ze=>Ze.isReal).length??0,fe;if(n&&oe>=2)fe=`across ${oe} AI tools`;else if(n&&oe===1){let Ze=n.perAdapter.find(Br=>Br.isReal);fe=`in ${Ze?Lu(Ze.name):"Claude Code"}`}else fe="in Claude Code";R>0?l.push(` Across ${R} days you ran ${dr(V)} conversations ${fe}.`):l.push(` You ran ${dr(V)} conversations ${fe}.`);let gt=R>0?O/R:0;l.push(` context-mode kept ${et(O)} out of your context window \u2014 about ${et(gt)} every single day.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 1. Where you are now \u2500\u2500\u2500"),l.push("");let Dt=e.firstEventMs&&e.firstEventMs>0?UE(e.firstEventMs,i,a):"";if(Dt?l.push(` This conversation started ${Dt} in ${FE(o)}.`):l.push(` This conversation lives in ${FE(o)}.`),l.push(` ${F}.`),e.snapshotsConsumed>0&&e.snapshotBytes>0){let Ze=e.lastRescueMs&&e.lastRescueMs>0?UE(e.lastRescueMs,i,a):"",Br=Math.round(e.snapshotBytes/1024);Ze?l.push(` On ${Ze}, /compact fired \u2014 ${Br} KB rescued from snapshot.`):l.push(` /compact fired \u2014 ${Br} KB rescued from snapshot.`),l.push(" Without that, you'd be re-explaining everything to a blank model right now.")}l.push("");let yt=Math.max(1,Math.round(g*.02)),ms=xn(g,g,32),tl=xn(yt,g,32),rl=g>0?(1-yt/g)*100:0;if(l.push(` Without context-mode ${et(C).padStart(8)} ${ms} ${dr(g).padStart(7)} tokens`),l.push(` With context-mode ${et(Math.max(1,Math.round(C*.02))).padStart(8)} ${tl} ${dr(yt).padStart(7)} tokens`),l.push(` ${rl.toFixed(0)}% kept out of context \xB7 your AI ran ${Math.max(1,Math.round(g/yt))}\xD7 longer before /compact fired`),l.push(""),e.byDay&&e.byDay.length>0){let Ze=e.lastEventMs&&e.firstEventMs?Math.max(1,Math.round((e.lastEventMs-e.firstEventMs)/864e5)+1):e.byDay.length;l.push(` How that ${et(C)} built up \u2014 ${Ze} days, ${e.byDay.length} active:`),l.push(""),l.push(...YL(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 $$=e.byCategory.reduce((Ze,Br)=>Ze+Br.count,0).toLocaleString(i);l.push(` ${$$} things \u2014 files, errors, decisions, agent runs:`),l.push("");let T$=e.byCategory[0]?.count??1;for(let Ze of e.byCategory)l.push(` ${Ze.label.padEnd(26)} ${String(Ze.count).padStart(5)} ${xn(Ze.count,T$,28)}`);l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 3. The scope, getting wider \u2500\u2500\u2500"),l.push("");let Ey=e.firstEventMs&&e.firstEventMs>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(e.firstEventMs)):"",$y=T>0?new Intl.DateTimeFormat(i,{timeZone:a,year:"numeric",month:"short",day:"numeric"}).format(new Date(T)):"",Ty=r?.distinctProjects??0,P$=r?.totalEvents??n?.totalEvents??0;if(l.push(` This chat: ${et(C)} kept out \xB7 ${e.events.toLocaleString(i)} captures${Ey?` \xB7 started ${Ey}`:""}.`),l.push(` All your work: ${et(O)} kept out \xB7 ${P$.toLocaleString(i)} captures across ${Ty} project${Ty===1?"":"s"}${$y?` \xB7 since ${$y}`:""}.`),l.push(""),l.push(""),l.push(" \u2500\u2500\u2500 4. The bottom line \u2500\u2500\u2500"),l.push(""),l.push(...GL(O,w,R)),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 Ze=Object.entries(r.autoMemoryByPrefix).sort((ra,na)=>na[1]-ra[1]),Br=Ze.length>0?Ze[0][1]:1;for(let[ra,na]of Ze){let C$=KE[ra]??ra;l.push(` ${C$.padEnd(26)} ${String(na).padStart(2)} ${xn(na,Br,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 R$=u?`v${u}`:"context-mode";return l.push(` ${R$}`),u&&d&&d!=="unknown"&&WE(d,u)&&l.push(` Update available: v${u} -> v${d} | ctx_upgrade`),JL(l)}function JL(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 YL(t,e,r){if(t.length===0)return[];let n=[...t].sort((m,f)=>m.ms-f.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 f=Math.round((m.ms-s.ms)/i*(c-1)),p="\u25CF";m===a&&(p="\u2588"),(m.rescueBytes??0)>0&&(p="\u25C6"),u[f]=p}let d=m=>{let f=new Intl.DateTimeFormat(e,{timeZone:r,month:"short",day:"numeric"}).formatToParts(new Date(m)),p=(f.find(g=>g.type==="month")?.value??"").toLowerCase(),h=f.find(g=>g.type==="day")?.value??"";return`${p} ${h}`},l=[];l.push(` ${d(s.ms)} ${u.join("")} ${d(o.ms)}`),l.push("");for(let m of n){let f=d(m.ms).padEnd(7),p=`${m.count} captures`,h=m===a?" \u2190 peak":"",g=(m.rescueBytes??0)>0?` \u25C6 /compact rescued ${Math.round((m.rescueBytes??0)/1024)} KB`:"";l.push(` ${f} ${p}${h}${g}`)}return l.push(""),l.push(" \u25CF active day \u2588 peak day \u25C6 /compact rescue"),l}function UE(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 dr(t){return t>=1e6?`${(t/1e6).toFixed(1)}M`:t>=1e3?`${(t/1e3).toFixed(1)}K`:String(t)}function Fu(t){return`$${((Number.isFinite(t)&&t>0?t:0)*Zu).toFixed(2)}`}function xn(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 HE(t,e){let r=e?.sessionTokensSaved??0;if(t.total_events===0&&(e?.lifetime?.totalEvents??0)===0&&r===0&&(e?.multiAdapter?.totalEvents??0)===0)return[];let n=e?.topN??Number.POSITIVE_INFINITY,s=[];s.push("");let o=e?.multiAdapter,i=o?.perAdapter.filter(h=>h.isReal).length??0,a=o?.totalEvents??e?.lifetime?.totalEvents??t.total_events,c=o?.totalSessions??e?.lifetime?.totalSessions??t.session_count,u=e?.lifetime?.distinctProjects;if(a>0&&u&&u>0){let h=i>=2?" everywhere":"";s.push(` All your work${h} \xB7 ${dr(a)} events captured across ${u} project${u===1?"":"s"} \xB7 ${dr(c)} conversations`)}else{s.push("Persistent memory \u2713 preserved across compact, restart & upgrade");let h=c===0&&r>0?1:c,g=h===1?"1 session":`${dr(h)} sessions`,y=a*256+r;s.push(` ${dr(a)} events \xB7 ${g} \xB7 ~${Fu(y)} saved lifetime`)}s.push("");let d=e?.lifetime?.categoryCounts,l;d&&Object.keys(d).length>0?l=Object.entries(d).filter(([,h])=>h>0).map(([h,g])=>({category:h,count:g,label:zu[h]||h})).sort((h,g)=>g.count-h.count):l=(t.by_category??[]).filter(h=>h&&h.count>0);let m=l.slice(0,n),f=m.length>0?m[0].count:1;for(let h of m)s.push(` ${h.label.padEnd(26)} ${String(h.count).padStart(5)} ${xn(h.count,f,30)}`);let p=Math.max(0,l.length-n);return p>0&&s.push(` ... ${p} more categor${p===1?"y":"ies"}`),s}function ZE(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=KE[s]??s;e.push(` ${i.padEnd(26)} ${String(o).padStart(2)} ${xn(o,n,20)}`)}return e}function BE(t,e){let r=[],n=Fu(t),s=(e?.totalEvents??0)*256+t,o=Fu(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 VE(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?dr(u.eventCount):"\u2014",m=et(u.dataBytes),f=et(d);n.push(` ${Lu(u.name).padEnd(s)}${l.padStart(o)}${m.padStart(i)}${f.padStart(a)}`)}}if(r.length>0){e.length>0&&n.push("");let s=r.map(o=>Lu(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 Bu(t,e,r,n){let s=[],o=VL(t.session.uptime_min),i=n?.lifetime,a=n?.mcpUsage,c=n?.conversation,u=n?.realBytes,d=n?.multiAdapter,l=d?.perAdapter.filter(I=>I.isReal).length??0;if(d&&l>0){let I=d.totalSessions||i?.totalSessions||0,O=i?.firstEventMs??0,C=O>0?Math.max(1,Math.round((Date.now()-O)/864e5)):0,F=C>0?`Across ${C} day${C===1?"":"s"} `:"",T=I>0?`you ran ${dr(I)} conversation${I===1?"":"s"} `:"you ran ",R;if(l>=2)R=`across ${l} AI tools`;else{let V=d.perAdapter.find(oe=>oe.isReal);R=`in ${V?Lu(V.name):"Claude Code"}`}s.push(`${F}${T}${R}.`),s.push("")}if(c&&c.events>0){s.length>0&&(s.length=0);let I=WL(),O=n?.cwd??process.cwd(),C=n?.now??Date.now(),F=n?.locale??I.locale,T=n?.tz??I.tz;return s.push(...KL({conversation:c,lifetime:i,multiAdapter:d,realBytes:u,cwd:O,locale:F,tz:T,now:C,version:e,latestVersion:r})),s.join(`
533
+ `)}let m=t.savings.kept_out+(t.cache?t.cache.bytes_saved:0),f=t.savings.total_bytes_returned,p=t.savings.total_calls,h=m+f,g=h>0?m/h*100:0,y=Math.round(m/4),_=f>0?Math.max(1,Math.round(h/Math.max(f,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(`${et(f)} entered context | 0 tokens saved`),s.push(...HE(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:0})),s.push(...VE(d)),s.push(...ZE(i)),s.push(...BE(0,i)),s.push("");let I=e?`v${e}`:"context-mode";return s.push(I),e&&r&&r!=="unknown"&&WE(r,e)&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
534
+ `)}s.push(`${dr(y)} tokens saved \xB7 ${g.toFixed(1)}% reduction \xB7 ${o} \xB7 ~${Fu(y)} saved (Opus)`),s.push(""),s.push(`Without context-mode |${xn(h,h)}| ${et(h)}`),s.push(`With context-mode |${xn(f,h)}| ${et(f)}`),s.push(""),_>=2?s.push(`${et(m)} kept out of your conversation \u2014 ${_}\xD7 longer sessions before compact.`):s.push(`${et(m)} kept out of your conversation. Never entered context.`),s.push("");let x=[`${p} calls`];t.cache&&t.cache.hits>0&&x.push(`${t.cache.hits} cache hits (+${et(t.cache.bytes_saved)})`),s.push(x.join(" \xB7 "));let S=t.savings.by_tool.filter(I=>I.calls>0);if(S.length>=2){s.push("");let I=S.map(O=>{let C=O.context_kb*1024,F=g<100?C/(1-g/100):C,T=Math.max(0,F-C);return{...O,returnedBytes:C,estimatedSaved:T}}).sort((O,C)=>C.estimatedSaved-O.estimatedSaved);for(let O of I){let C=O.tool.length>22?O.tool.slice(0,19)+"...":O.tool;s.push(` ${C.padEnd(22)} ${String(O.calls).padStart(4)} calls ${et(O.estimatedSaved).padStart(8)} saved`)}}if(a&&a.length>0){let I=a.filter(O=>O.median_concurrency!=null&&(O.max_concurrency??1)>1);if(I.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 O of I){let C=O.tool_name.replace(/^mcp__.*?__/,"");s.push(` ${C.padEnd(22)} ${O.calls} batches \xB7 ${O.median_concurrency} typical, ${O.max_concurrency} peak`)}}}s.push(...HE(t.projectMemory,{lifetime:i,multiAdapter:d,sessionTokensSaved:y})),s.push(...VE(d)),s.push(...ZE(i)),s.push(...BE(y,i)),s.push("");let w=e?`v${e}`:"context-mode";return s.push(w),e&&r&&r!=="unknown"&&r!==e&&s.push(`Update available: v${e} -> v${r} | ctx_upgrade`),s.join(`
535
+ `)}var zu,FL,xo,ZL,KE,qL,Zu,qE,JE=v(()=>{"use strict";go();Wr();zu={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"},FL={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"},xo=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((R,V)=>R+V,0),o=Object.values(e.calls).reduce((R,V)=>R+V,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(R=>({tool:R,calls:e.calls[R]||0,context_kb:Math.round((e.bytesReturned[R]||0)/1024*10)/10,tokens:Math.round((e.bytesReturned[R]||0)/4)})),f=((Date.now()-e.sessionStart)/6e4).toFixed(1),p;if(e.cacheHits>0||e.cacheBytesSaved>0){let R=a+e.cacheBytesSaved,V=R/Math.max(s,1),oe=Math.max(0,24-Math.floor((Date.now()-e.sessionStart)/(3600*1e3)));p={hits:e.cacheHits,bytes_saved:e.cacheBytesSaved,ttl_hours_left:oe,total_with_cache:R,total_savings_ratio:V}}let h=this.db.prepare("SELECT COUNT(*) as cnt FROM session_events WHERE session_id = ?").get(n).cnt,g=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events WHERE session_id = ? GROUP BY category ORDER BY cnt DESC").all(n),_=this.db.prepare("SELECT compact_count FROM session_meta WHERE session_id = ?").get(n)?.compact_count??0,x=this.db.prepare("SELECT event_count, consumed FROM session_resume WHERE session_id = ? ORDER BY created_at DESC LIMIT 1").get(n),S=x?!x.consumed:!1,w=this.db.prepare("SELECT category, type, data FROM session_events WHERE session_id = ? ORDER BY id DESC").all(n),I=new Map;for(let R of w){I.has(R.category)||I.set(R.category,new Set);let V=I.get(R.category);if(V.size<5){let oe=R.data;R.category==="file"?oe=R.data.split("/").pop()||R.data:(R.category==="prompt"||R.category==="user-prompt")&&(oe=oe.length>50?oe.slice(0,47)+"...":oe),oe.length>40&&(oe=oe.slice(0,37)+"..."),V.add(oe)}}let O=g.map(R=>({category:R.category,count:R.cnt,label:zu[R.category]||R.category,preview:I.get(R.category)?Array.from(I.get(R.category)).join(", "):"",why:FL[R.category]||"Survives context resets"})),C=this.db.prepare("SELECT COUNT(*) as cnt, COUNT(DISTINCT session_id) as sessions FROM session_events").get(),T=this.db.prepare("SELECT category, COUNT(*) as cnt FROM session_events GROUP BY category ORDER BY cnt DESC").all().filter(R=>R.cnt>0).map(R=>({category:R.category,count:R.cnt,label:zu[R.category]||R.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:f},continuity:{total_events:h,by_category:O,compact_count:_,resume_ready:S},projectMemory:{total_events:C.cnt,session_count:C.sessions,by_category:T}}}};ZL={minEvents:100,minProjects:5,recencyMs:30*864e5,minAvgBytes:50};KE={project:"What you're building",feedback:"How you work",user:"Who you are",reference:"Where to look",memory:"Long-term context",other:"Other notes"},qL={"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"};Zu=15/1e6;qE=256});var x$={};Le(x$,{browserOpenArgv:()=>_$,buildBatchNodeOptionsPrefix:()=>f$,buildFetchCode:()=>y$,classifyIp:()=>Xu,extractSnippet:()=>vy,formatBatchQueryResults:()=>m$,killProcessOnPort:()=>Sy,openBrowserSync:()=>my,positionsFromHighlight:()=>p$,runBatchCommands:()=>h$});import{createRequire as a$}from"node:module";import{existsSync as ze,unlinkSync as Ji,readdirSync as XL,readFileSync as fy,writeFileSync as hy,renameSync as QL,rmSync as Gu,mkdirSync as Yi,cpSync as eF,statSync as YE,symlinkSync as tF,lstatSync as rF}from"node:fs";import{execSync as XE,spawnSync as c$}from"node:child_process";import{join as De,dirname as Qt,resolve as ct,sep as nF,isAbsolute as sF}from"node:path";import{fileURLToPath as oF}from"node:url";import{homedir as gy,tmpdir as yy,cpus as iF}from"node:os";import{request as aF}from"node:https";function cF(t){try{let e=at();if(!ze(e))return;let r=XL(e).filter(n=>n.endsWith("-events.md"));for(let n of r){let s=De(e,n);try{t.index({path:s,source:"session-events"}),Ji(s)}catch{}}}catch{}}function ly(){return We()}async function uF(){if(vn)return vn;try{let{getAdapter:t}=await Promise.resolve().then(()=>(Io(),fd)),e=gr();return await t(e.platform)}catch{return null}}function at(){if(vn)return vn.getSessionDir();try{let e=gr(),r=md(e.platform);if(r){let n=De(gy(),...r);r.length===1&&r[0]===".claude"?n=ly():r.length===1&&r[0]===".codex"&&(n=xa());let s=De(n,"context-mode","sessions");return Yi(s,{recursive:!0}),s}}catch{}let t=De(ly(),"context-mode","sessions");return Yi(t,{recursive:!0}),t}function fr(){return process.env.CLAUDE_PROJECT_DIR||process.env.GEMINI_PROJECT_DIR||process.env.VSCODE_CWD||process.env.OPENCODE_PROJECT_DIR||process.env.PI_PROJECT_DIR||process.env.IDEA_INITIAL_DIRECTORY||process.env.CONTEXT_MODE_PROJECT_DIR||process.cwd()}function lF(t){return sF(t)?t:ct(fr(),t)}function Xi(){return Mu({projectDir:fr(),sessionsDir:at()})}function dy(){let t=De(Qt(at()),"content");return Yi(t,{recursive:!0}),kE({projectDir:fr(),contentDir:t})}function ps(){if(!pr){let t=dy();pr=new Iu(t),pr.setDenyChecker(e=>{try{let r=fr(),n=Kg("Read",r);return Yg(e,n,process.platform==="win32",r).denied}catch{return!0}});try{let e=Qt(dy());qg(e,14),pr.cleanupStaleSources(14);let r=De(gy(),".context-mode","content");ze(r)&&qg(r,0)}catch{}Bg()}return cF(pr),pr}async function e$(){return new Promise(t=>{let e=aF("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 mF(){let t=vn?.name;return t==="Claude Code"?"/ctx-upgrade":t==="OpenClaw"?"npm run install:openclaw":t==="Pi"?"npm run build":"npm update -g context-mode"}function fF(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 hF(){return!Hr||Hr==="unknown"?!1:fF(Hr,Ur)}function gF(){if(!hF())return!1;let t=Date.now();if(qu>=dF){if(t-QE<pF)return!1;qu=0}return qu===0&&(QE=t),qu++,!0}function yF(){if(!t$){t$=!0;try{let t=We(),e=ct(t,"plugins","installed_plugins.json");if(!ze(e))return;let r=JSON.parse(fy(e,"utf-8")),n=ct(t,"plugins","cache"),s=ze(ct(Nt,"package.json"))?Nt:Qt(Nt);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)||!ct(c).startsWith(n+nF))continue;try{rF(c).isSymbolicLink()&&Ji(c)}catch{}let u=Qt(c);ze(u)||Yi(u,{recursive:!0}),ze(s)&&tF(s,c,process.platform==="win32"?"junction":void 0)}}catch{}}}function K(t,e){if(yF(),gF()&&e.content.length>0){let n=mF();e.content[0].text=`\u26A0\uFE0F context-mode v${Ur} outdated \u2192 v${Hr} available. Upgrade: ${n}
536
+
537
+ `+e.content[0].text}let r=e.content.reduce((n,s)=>n+Buffer.byteLength(s.text),0);return se.calls[t]=(se.calls[t]||0)+1,se.bytesReturned[t]=(se.bytesReturned[t]||0)+r,Ku(),setImmediate(()=>OE(Xi(),t,r)),(t==="ctx_execute"||t==="ctx_execute_file"||t==="ctx_batch_execute")&&setImmediate(()=>$E({sessionDbPath:Xi(),toolName:t,bytesReturned:r})),e}function mr(t,e="unknown"){se.bytesIndexed+=t,Ku(),t>0&&setImmediate(()=>TE({sessionDbPath:Xi(),source:e,bytesAvoided:t}))}function u$(){let t=process.env.CLAUDE_SESSION_ID||`pid-${process.ppid}`;return De(at(),`stats-${t}.json`)}function Ku(){let t=Date.now();if(!(t-py<_F)){py=t;try{let e=Object.values(se.bytesReturned).reduce((l,m)=>l+m,0),r=Object.values(se.calls).reduce((l,m)=>l+m,0),n=se.bytesIndexed+se.bytesSandboxed+se.cacheBytesSaved,s=n+e,o=s>0?Math.round((1-e/s)*100):0,i=Math.round(n/4),a=Vu?.tokens??0;if(!Vu||t-Vu.computedAt>vF)try{a=(Gi({sessionsDir:at()})?.totalEvents??0)*bF,Vu={tokens:a,computedAt:t}}catch{}let c={schemaVersion:xF,version:Ur,updated_at:t,session_start:se.sessionStart,uptime_ms:t-se.sessionStart,total_calls:r,bytes_returned:e,bytes_indexed:se.bytesIndexed,bytes_sandboxed:se.bytesSandboxed,cache_hits:se.cacheHits,cache_bytes_saved:se.cacheBytesSaved,kept_out:n,total_processed:s,reduction_pct:o,tokens_saved:i,dollars_saved_session:+(i*Zu).toFixed(2),tokens_saved_lifetime:a,dollars_saved_lifetime:+(a*Zu).toFixed(2),by_tool:Object.fromEntries(Object.keys({...se.calls,...se.bytesReturned}).map(l=>[l,{calls:se.calls[l]||0,bytes:se.bytesReturned[l]||0}]))},u=u$(),d=`${u}.tmp`;hy(d,JSON.stringify(c)),QL(d,u)}catch{}}}function xy(t,e){try{let r=Gg(process.env.CLAUDE_PROJECT_DIR),n=Jg(t,r);if(n.decision==="deny")return K(e,{content:[{type:"text",text:`Command blocked by security policy: matches deny pattern ${n.matchedPattern}`}],isError:!0})}catch{}return null}function l$(t,e,r){try{let n=fE(t,e);if(n.length===0)return null;let s=Gg(process.env.CLAUDE_PROJECT_DIR);for(let o of n){let i=Jg(o,s);if(i.decision==="deny")return K(r,{content:[{type:"text",text:`Command blocked by security policy: embedded shell command "${o}" matches deny pattern ${i.matchedPattern}`}],isError:!0})}}catch{}return null}function d$(t,e){try{let r=fr(),n=Kg("Read",r),s=Yg(t,n,process.platform==="win32",r);if(s.denied)return K(e,{content:[{type:"text",text:`File access blocked by security policy: path matches Read deny pattern ${s.matchedPattern}`}],isError:!0})}catch{}return null}function p$(t){let e=[],r=0,n=0;for(;n<t.length;)if(t[n]===wF){for(e.push(r),n++;n<t.length&&t[n]!==EF;)r++,n++;n<t.length&&n++}else r++,n++;return e}function vy(t,e,r=1500,n){if(t.length<=r)return t;let s=[];if(n)for(let u of p$(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)+`
538
+ \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(`
539
+
540
+ `)}function m$(t,e,r,n=80*1024){let s=[],o=0;for(let i of e){if(o>n){s.push(`## ${i}
508
541
  (output cap reached \u2014 use ctx_search(queries: ["${i}"]) for details)
509
- `);continue}let a=t.searchWithFallback(i,3,r,void 0,"exact");if(o.push(`## ${i}`),o.push(""),a.length>0){for(let c of a){let u=$g(c.content,i,3e3,c.highlighted);o.push(`### ${c.title}`),o.push(u),o.push(""),s+=u.length+c.title.length}continue}o.push("No matching sections found."),o.push("")}return o.push("\n> **Tip:** Results are scoped to this batch only. To search across all indexed sources, use `ctx_search(queries: [...])`."),o}function _M(t){return`'${t.replace(/'/g,"'\\''")}'`}function yM(t){return`'${t.replace(/'/g,"''")}'`}function qw(t,e){let r=`--require ${e}`,n=t.toLowerCase(),o=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${yM(r)}; `:o==="cmd"||o==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${_M(r)} `}function Aw(t,e,r){let n=e||"(no output)",o=n.matchAll(/__CM_FS__:(\d+)/g),s=0;for(let i of o)s+=parseInt(i[1]);return s>0&&(r?.(s),n=n.replace(/__CM_FS__:\d+\n?/g,"")),`# ${t}
542
+ `);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=vy(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 $F(t){return`'${t.replace(/'/g,"'\\''")}'`}function TF(t){return`'${t.replace(/'/g,"''")}'`}function f$(t,e){let r=`--require ${e}`,n=t.toLowerCase(),s=n.split(/[\\/]/).pop()??n;return n.includes("powershell")||n.includes("pwsh")?`$env:NODE_OPTIONS=${TF(r)}; `:s==="cmd"||s==="cmd.exe"?`set "NODE_OPTIONS=${r.replace(/"/g,'""')}" && `:`NODE_OPTIONS=${$F(r)} `}function r$(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}
510
543
 
511
544
  ${n}
512
- `}async function Bw(t,e,r){let{timeout:n,concurrency:o,nodeOptsPrefix:s,onFsBytes:i}=e;if(o<=1){let d=[],p=Date.now(),f=!1;for(let m=0;m<t.length;m++){let h=t[m],g;if(n!==void 0){let _=Date.now()-p,x=n-_;if(x<=0){d.push(`# ${h.label}
545
+ `}async function h$(t,e,r){let{timeout:n,concurrency:s,nodeOptsPrefix:o,onFsBytes:i}=e;if(s<=1){let l=[],m=Date.now(),f=!1;for(let p=0;p<t.length;p++){let h=t[p],g;if(n!==void 0){let _=Date.now()-m,x=n-_;if(x<=0){l.push(`# ${h.label}
513
546
 
514
547
  (skipped \u2014 batch timeout exceeded)
515
- `),f=!0;continue}g=x}let y=await r.execute({language:"shell",code:`${s}${h.command} 2>&1`,timeout:g});if(d.push(Aw(h.label,y.stdout,i)),y.timedOut){f=!0;for(let _=m+1;_<t.length;_++)d.push(`# ${t[_].label}
548
+ `),f=!0;continue}g=x}let y=await r.execute({language:"shell",code:`${o}${h.command} 2>&1`,timeout:g});if(l.push(r$(h.label,y.stdout,i)),y.timedOut){f=!0;for(let _=p+1;_<t.length;_++)l.push(`# ${t[_].label}
516
549
 
517
550
  (skipped \u2014 batch timeout exceeded)
518
- `);break}}return{outputs:d,timedOut:f}}let a=t.map(d=>({run:async()=>{let p=await r.execute({language:"shell",code:`${s}${d.command} 2>&1`,timeout:n}),f=Aw(d.label,p.stdout,i);return{output:p.timedOut?f.replace(/\n$/,"")+`
551
+ `);break}}return{outputs:l,timedOut:f}}let a=t.map(l=>({run:async()=>{let m=await r.execute({language:"shell",code:`${o}${l.command} 2>&1`,timeout:n}),f=r$(l.label,m.stdout,i);return{output:m.timedOut?f.replace(/\n$/,"")+`
519
552
  (timed out after ${n??"?"}ms)
520
- `:f,timedOut:!!p.timedOut}}})),{settled:c}=await Gh(a,{concurrency:o}),u=new Array(t.length),l=!1;for(let d=0;d<c.length;d++){let p=c[d];if(p.status==="fulfilled")u[d]=p.value.output,p.value.timedOut&&(l=!0);else{let f=p.reason instanceof Error?p.reason.message:String(p.reason);u[d]=`# ${t[d].label}
553
+ `:f,timedOut:!!m.timedOut}}})),{settled:c}=await zg(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 f=m.reason instanceof Error?m.reason.message:String(m.reason);u[l]=`# ${t[l].label}
521
554
 
522
555
  (executor error: ${f})
523
- `}}return{outputs:u,timedOut:l}}function Vw(t,e){let r=no();or(Buffer.byteLength(t));let n=r.index({content:t,source:e});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
524
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function as(t,e,r,n=5){let o=t.split(`
525
- `).length,s=Buffer.byteLength(t),i=no(),a=i.indexPlainText(t,r),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let d=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${o}-line output (${(s/1024).toFixed(1)}KB).`];return u.length>0&&(d.push(""),d.push(`Searchable terms: ${u.join(", ")}`)),d.push(""),d.push("Use ctx_search(queries: [...]) to explore the indexed content."),d.join(`
526
- `)}let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`${c.length} sections matched "${e}" (${o} lines, ${(s/1024).toFixed(1)}KB):`,""];for(let d of c){let p=d.content.split(`
527
- `)[0].slice(0,120);l.push(` - ${d.title}: ${p}`)}return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to retrieve full content of any section."),l.join(`
528
- `)}function Eg(t){if(typeof t=="string")try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t}function vM(t){let e=Eg(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function bM(){return gg||(gg=Mw(import.meta.url).resolve("turndown")),gg}function SM(){return _g||(_g=Mw(import.meta.url).resolve("turndown-plugin-gfm")),_g}function kM(t,e){let r=JSON.stringify(bM()),n=JSON.stringify(SM()),o=JSON.stringify(e);return`
556
+ `}}return{outputs:u,timedOut:d}}function g$(t,e){let r=ps();mr(Buffer.byteLength(t));let n=r.index({content:t,source:e});return{content:[{type:"text",text:`Indexed ${n.totalChunks} sections (${n.codeChunks} with code) from: ${n.label}
557
+ Use ctx_search(queries: ["..."]) to query this content. Use source: "${n.label}" to scope results.`}]}}function vo(t,e,r,n=5){let s=t.split(`
558
+ `).length,o=Buffer.byteLength(t),i=ps(),a=i.indexPlainText(t,r),c=i.searchWithFallback(e,n,r),u=i.getDistinctiveTerms(a.sourceId);if(c.length===0){let l=[`Indexed ${a.totalChunks} sections from "${r}" into knowledge base.`,`No sections matched intent "${e}" in ${s}-line output (${(o/1024).toFixed(1)}KB).`];return u.length>0&&(l.push(""),l.push(`Searchable terms: ${u.join(", ")}`)),l.push(""),l.push("Use ctx_search(queries: [...]) to explore the indexed content."),l.join(`
559
+ `)}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(`
560
+ `)[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(`
561
+ `)}function by(t){if(typeof t=="string")try{let e=JSON.parse(t);if(Array.isArray(e))return e}catch{}return t}function RF(t){let e=by(t);return Array.isArray(e)?e.map((r,n)=>typeof r=="string"?{label:`cmd_${n+1}`,command:r}:r):e}function CF(){return cy||(cy=a$(import.meta.url).resolve("turndown")),cy}function OF(){return uy||(uy=a$(import.meta.url).resolve("turndown-plugin-gfm")),uy}function y$(t,e){let r=JSON.stringify(CF()),n=JSON.stringify(OF()),s=JSON.stringify(e),o=Xu.toString(),i=process.env.CTX_FETCH_STRICT==="1";return`
529
562
  const TurndownService = require(${r});
530
563
  const { gfm } = require(${n});
531
564
  const fs = require('fs');
565
+ const dns = require('node:dns');
566
+ const dnsPromises = require('node:dns/promises');
532
567
  const url = ${JSON.stringify(t)};
533
- const outputPath = ${o};
568
+ const outputPath = ${s};
569
+
570
+ // Strip proxy env vars from this subprocess only. A configured outbound
571
+ // proxy (HTTP_PROXY / HTTPS_PROXY / ALL_PROXY) would route fetch through
572
+ // an arbitrary target \u2014 DNS resolution happens at the proxy and the
573
+ // in-subprocess DNS rebinding guard never sees the rebound IP. The
574
+ // sandbox fetch path has no legitimate need for an upstream proxy.
575
+ delete process.env.HTTP_PROXY;
576
+ delete process.env.HTTPS_PROXY;
577
+ delete process.env.ALL_PROXY;
578
+ delete process.env.http_proxy;
579
+ delete process.env.https_proxy;
580
+ delete process.env.all_proxy;
581
+ delete process.env.npm_config_proxy;
582
+ delete process.env.npm_config_https_proxy;
583
+
584
+ ${o}
585
+
586
+ const STRICT = ${JSON.stringify(i)};
587
+
588
+ // SSRF rebinding defense: every dns.lookup call inside this subprocess
589
+ // (including the one undici performs to connect the fetch socket) is
590
+ // re-validated against the same policy ssrfGuard runs in the parent.
591
+ // Even if a hostname rebinds between the parent's pre-flight check and
592
+ // the subprocess's actual connect, the connect-time lookup re-classifies
593
+ // every returned record and aborts before TCP if any verdict is "block".
594
+ const _origLookup = dns.lookup;
595
+ dns.lookup = function patchedLookup(hostname, options, callback) {
596
+ if (typeof options === 'function') { callback = options; options = {}; }
597
+ if (typeof options === 'number') { options = { family: options }; }
598
+ const wantAll = options && options.all;
599
+ const opts = Object.assign({}, options || {}, { all: true, verbatim: true });
600
+ _origLookup(hostname, opts, function(err, records) {
601
+ if (err) return callback(err);
602
+ if (!Array.isArray(records)) {
603
+ records = [{ address: records, family: (options && options.family) || 4 }];
604
+ }
605
+ for (var i = 0; i < records.length; i++) {
606
+ var verdict = classifyIp(records[i].address);
607
+ if (verdict === 'block' || (STRICT && verdict === 'private')) {
608
+ return callback(new Error(
609
+ 'SSRF blocked at connect-time: ' + hostname +
610
+ ' resolves to ' + records[i].address +
611
+ ' (' + verdict + ')'
612
+ ));
613
+ }
614
+ }
615
+ if (wantAll) callback(null, records);
616
+ else callback(null, records[0].address, records[0].family);
617
+ });
618
+ };
619
+
620
+ // dns/promises is a separate function reference. Patching dns.lookup does
621
+ // NOT affect dnsPromises.lookup. Today undici's connect path uses callback
622
+ // dns.lookup so default fetch is covered, but the invariant is fragile \u2014
623
+ // any future undici switch (or user code calling dnsPromises.lookup
624
+ // directly) would bypass the guard. Patch both to keep the contract.
625
+ const _origPromisesLookup = dnsPromises.lookup;
626
+ dnsPromises.lookup = async function patchedPromisesLookup(hostname, options) {
627
+ const opts = Object.assign({}, options || {}, { all: true, verbatim: true });
628
+ const records = await _origPromisesLookup(hostname, opts);
629
+ const list = Array.isArray(records) ? records : [records];
630
+ for (var i = 0; i < list.length; i++) {
631
+ var verdict = classifyIp(list[i].address);
632
+ if (verdict === 'block' || (STRICT && verdict === 'private')) {
633
+ throw new Error(
634
+ 'SSRF blocked at connect-time: ' + hostname +
635
+ ' resolves to ' + list[i].address + ' (' + verdict + ')'
636
+ );
637
+ }
638
+ }
639
+ return options && options.all
640
+ ? list
641
+ : { address: list[0].address, family: list[0].family };
642
+ };
643
+
644
+ // dns.resolve4 / dns.resolve6 use a different code path (no getaddrinfo,
645
+ // no /etc/hosts) than dns.lookup \u2014 they must be patched separately or the
646
+ // guard is trivially bypassed by any caller using dns.resolve* directly.
647
+ ['resolve4', 'resolve6'].forEach(function patchResolve(name) {
648
+ const _origResolve = dns[name];
649
+ dns[name] = function patchedResolve(hostname, options, cb) {
650
+ if (typeof options === 'function') { cb = options; options = undefined; }
651
+ _origResolve.call(dns, hostname, options || {}, function(err, addrs) {
652
+ if (err) return cb(err);
653
+ var withTtl = options && options.ttl;
654
+ for (var i = 0; i < addrs.length; i++) {
655
+ var ip = withTtl ? addrs[i].address : addrs[i];
656
+ var v = classifyIp(ip);
657
+ if (v === 'block' || (STRICT && v === 'private')) {
658
+ return cb(new Error(
659
+ 'SSRF blocked at connect-time: ' + hostname +
660
+ ' resolves to ' + ip + ' (' + v + ')'
661
+ ));
662
+ }
663
+ }
664
+ cb(null, addrs);
665
+ });
666
+ };
667
+ });
668
+
669
+ // Generic dns.resolve is a polymorphic dispatcher (rrtype-driven). Internally
670
+ // Node delegates to dns.resolve4/dns.resolve6 for A/AAAA, but the patches
671
+ // above hook the *exported* references \u2014 Node's internal dispatcher holds
672
+ // captured originals and bypasses our patch. Patch the wrapper explicitly:
673
+ // classify A/AAAA records the same way; pass through CNAME/MX/TXT/SRV/etc.
674
+ const _origResolveGeneric = dns.resolve;
675
+ dns.resolve = function patchedResolveGeneric(hostname, rrtype, cb) {
676
+ if (typeof rrtype === 'function') { cb = rrtype; rrtype = 'A'; }
677
+ _origResolveGeneric.call(dns, hostname, rrtype, function(err, records) {
678
+ if (err) return cb(err);
679
+ if ((rrtype === 'A' || rrtype === 'AAAA') && Array.isArray(records)) {
680
+ for (var i = 0; i < records.length; i++) {
681
+ var ip = records[i];
682
+ var v = classifyIp(ip);
683
+ if (v === 'block' || (STRICT && v === 'private')) {
684
+ return cb(new Error(
685
+ 'SSRF blocked at connect-time: ' + hostname +
686
+ ' resolves to ' + ip + ' (' + v + ')'
687
+ ));
688
+ }
689
+ }
690
+ }
691
+ cb(null, records);
692
+ });
693
+ };
534
694
 
535
695
  function emit(ct, content) {
536
696
  // Write content to file to bypass executor stdout truncation (100KB limit).
@@ -539,8 +699,60 @@ function emit(ct, content) {
539
699
  console.log('__CM_CT__:' + ct);
540
700
  }
541
701
 
702
+ // Manual redirect handling: a 3xx Location header can rebind the subprocess
703
+ // fetch to an alternate host the parent's pre-flight ssrfGuard never saw.
704
+ // Even with the connect-time DNS patch, a redirect target that is a literal
705
+ // IP (e.g. http://169.254.169.254/) skips getaddrinfo entirely. Walk the
706
+ // chain manually so every hop runs through classifyIp before the next fetch.
707
+ const MAX_REDIRECTS = 5;
708
+ async function fetchWithManualRedirect(initialUrl) {
709
+ let currentUrl = initialUrl;
710
+ for (let redirectCount = 0; redirectCount <= MAX_REDIRECTS; redirectCount++) {
711
+ const resp = await fetch(currentUrl, { redirect: 'manual' });
712
+ if (resp.status < 300 || resp.status >= 400) return resp;
713
+ const location = resp.headers.get('location') || resp.headers.get('Location');
714
+ if (!location) return resp;
715
+ if (redirectCount === MAX_REDIRECTS) {
716
+ throw new Error('SSRF blocked: redirect chain exceeded ' + MAX_REDIRECTS + ' hops');
717
+ }
718
+ let nextParsed;
719
+ try { nextParsed = new URL(location, currentUrl); } catch (e) {
720
+ throw new Error('SSRF blocked: invalid redirect Location: ' + location);
721
+ }
722
+ if (nextParsed.protocol !== 'http:' && nextParsed.protocol !== 'https:') {
723
+ throw new Error('SSRF blocked: redirect to non-http(s) scheme ' + nextParsed.protocol);
724
+ }
725
+ // If the redirect target is a literal IP, classify it directly \u2014 no DNS
726
+ // lookup will fire and the connect-time guard would never see it.
727
+ const hostname = nextParsed.hostname.replace(/^[|]$/g, '');
728
+ const isIpLiteral = /^[0-9.]+$/.test(hostname) || hostname.includes(':');
729
+ if (isIpLiteral) {
730
+ const verdict = classifyIp(hostname);
731
+ if (verdict === 'block' || (STRICT && verdict === 'private')) {
732
+ throw new Error('SSRF blocked: redirect to ' + hostname + ' (' + verdict + ')');
733
+ }
734
+ } else {
735
+ // Hostname target: resolve and classify every record. The patched
736
+ // dns.lookup also fires on the next fetch's connect, but checking
737
+ // here gives a clearer error and short-circuits before TCP setup.
738
+ const records = await dnsPromises.lookup(hostname, { all: true, verbatim: true });
739
+ for (const rec of records) {
740
+ const verdict = classifyIp(rec.address);
741
+ if (verdict === 'block' || (STRICT && verdict === 'private')) {
742
+ throw new Error(
743
+ 'SSRF blocked: redirect target ' + hostname +
744
+ ' resolves to ' + rec.address + ' (' + verdict + ')'
745
+ );
746
+ }
747
+ }
748
+ }
749
+ currentUrl = nextParsed.toString();
750
+ }
751
+ throw new Error('SSRF blocked: redirect chain exceeded ' + MAX_REDIRECTS + ' hops');
752
+ }
753
+
542
754
  async function main() {
543
- const resp = await fetch(url);
755
+ const resp = await fetchWithManualRedirect(url);
544
756
  if (!resp.ok) { console.error("HTTP " + resp.status); process.exit(1); }
545
757
  const contentType = resp.headers.get('content-type') || '';
546
758
 
@@ -571,22 +783,20 @@ async function main() {
571
783
  emit('text', text);
572
784
  }
573
785
  main();
574
- `}async function $M(t){let e;try{e=new URL(t)}catch{return{kind:"fetch_error",url:t,error:"invalid URL",reason:"exit"}}if(e.protocol!=="http:"&&e.protocol!=="https:")return{kind:"fetch_error",url:t,error:`URL scheme "${e.protocol}" not allowed (only http: and https:)`,reason:"exit"};let r=process.env.CTX_FETCH_STRICT==="1";try{let{lookup:n}=await import("node:dns/promises"),o=await n(e.hostname,{all:!0,verbatim:!0});for(let s of o){let i=Tg(s.address);if(i==="block")return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to ${s.address} \u2014 blocked (link-local / IMDS / multicast / reserved)`,reason:"exit"};if(i==="private"&&r)return{kind:"fetch_error",url:t,error:`URL "${e.hostname}" resolves to private IP ${s.address} \u2014 blocked under CTX_FETCH_STRICT=1`,reason:"exit"}}}catch(n){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 Tg(t){let e=t.toLowerCase();if(e.includes(":")){let s=e.match(/^::ffff:([\d.]+)$/);return s?Tg(s[1]):e==="::"||e.startsWith("fe8")||e.startsWith("fe9")||e.startsWith("fea")||e.startsWith("feb")||e.startsWith("ff")?"block":e==="::1"||e.startsWith("fc")||e.startsWith("fd")?"private":"public"}if(!t.includes("."))return"block";let r=t.split(".").map(s=>parseInt(s,10));if(r.length!==4||r.some(s=>isNaN(s)||s<0||s>255))return"block";let[n,o]=r;return n===169&&o===254||n===0||n>=224?"block":n===127||n===10||n===172&&o>=16&&o<=31||n===192&&o===168?"private":"public"}async function EM(t,e,r){let n=await $M(t);if(n)return n;if(!r){let s=no(),i=rg(e,t),a=s.getSourceMeta(i);if(a){let c=new Date(a.indexedAt+"Z"),u=Date.now()-c.getTime();if(u<wM){let l=Math.floor(u/36e5),d=Math.floor(u/(60*1e3)),p=l>0?`${l}h ago`:d>0?`${d}m ago`:"just now",f=a.chunkCount*1600;return{kind:"cached",label:a.label,chunkCount:a.chunkCount,estimatedBytes:f,ageStr:p}}}}let o=pe(Sg(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let s=kM(t,o),i=await Di.execute({language:"javascript",code:s,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=vg(o,"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(s){return{kind:"fetch_error",url:t,error:s instanceof Error?s.message:String(s),reason:"throw"}}finally{try{vu(o)}catch{}}}function TM(t){let e=no(),r=rg(t.source,t.url),n;t.header==="__CM_CT__:json"?n=e.indexJSON(t.markdown,r):t.header==="__CM_CT__:text"?n=e.indexPlainText(t.markdown,r):n=e.index({content:t.markdown,source:r}),or(Buffer.byteLength(t.markdown));let o=t.markdown.length>jw?t.markdown.slice(0,jw)+`
786
+ `}async function AF(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=Xu(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 Xu(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?Xu(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 NF(t,e,r){let n=await AF(t);if(n)return n;if(!r){let o=ps(),i=Vg(e,t),a=o.getSourceMeta(i);if(a){let c=new Date(a.indexedAt+"Z"),u=Date.now()-c.getTime();if(u<IF){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",f=a.chunkCount*1600;return{kind:"cached",label:a.label,chunkCount:a.chunkCount,estimatedBytes:f,ageStr:m}}}}let s=De(yy(),`ctx-fetch-${Date.now()}-${Math.random().toString(36).slice(2)}.dat`);try{let o=y$(t,s),i=await ea.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=fy(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{Gu(s)}catch{}}}function DF(t){let e=ps(),r=Vg(t.source,t.url),n;t.header==="__CM_CT__:json"?n=e.indexJSON(t.markdown,r):t.header==="__CM_CT__:text"?n=e.indexPlainText(t.markdown,r):n=e.index({content:t.markdown,source:r}),mr(Buffer.byteLength(t.markdown));let s=t.markdown.length>o$?t.markdown.slice(0,o$)+`
575
787
 
576
- \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:n.label,totalChunks:n.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:o}}function Dw(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}async function PM(){let t=eg();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?Sg():"/tmp",r=pe(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{Di.cleanupBackgrounded(),yr&&yr.close();try{_r(kg)}catch{}try{_r(r)}catch{}if(jr&&jr.pid&&!jr.killed)try{jr.kill("SIGTERM")}catch{}},o=async()=>{try{xg=0,bu()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{o()}),process.on("SIGTERM",()=>{o()}),lw({onShutdown:()=>o()});let s=new su;await Qe.connect(s);try{bg(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(ca(),iy)),c=Qe.server.getClientVersion(),u=i(c??void 0);cs=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=gw(Lw());if(i){for(let[a,c]of Object.entries(i.calls))re.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))re.bytesReturned[a]=c;i.sessionStart>0&&(re.sessionStart=i.sessionStart)}}catch{}Ow().then(i=>{i!=="unknown"&&(Mr=i)}),setInterval(()=>{Ow().then(i=>{i!=="unknown"&&(Mr=i)})},3600*1e3).unref(),setInterval(()=>bu(),6e4).unref(),console.error(`Context Mode MCP server v${Dr} running on stdio`),console.error(`Detected runtimes:
577
- ${Ki(ji)}`),io()||(console.error(`
578
- Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash"))}var kt,Dr,ji,xu,Qe,Di,kg,yr,cs,jr,re,Mr,_u,Cw,tM,rM,Iw,cM,uM,lM,dM,xg,yu,mM,fM,hM,gM,Su,ku,to,hg,xM,Nw,zw,gg,_g,wM,jw,Gw=v(()=>{"use strict";Ck();Nk();qh();Wh();Hk();Qk();ew();cw();Yi();uw();dw();cg();_w();kw();Sr();ca();ns();Pw();Un();kt=nr(JD(import.meta.url)),Dr=(()=>{for(let t of["../package.json","./package.json"]){let e=ot(kt,t);if(je(e))try{return JSON.parse(vg(e,"utf8")).version}catch{}}return"unknown"})();process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
788
+ \u2026[truncated \u2014 use ctx_search() for full content]`:t.markdown;return{label:n.label,totalChunks:n.totalChunks,totalBytes:Buffer.byteLength(t.markdown),preview:s}}function i$(){return{prepare:()=>({run:()=>{},get:(...t)=>({cnt:0,compact_count:0,minutes:null,rate:0,avg:0,outcome:"exploratory"}),all:()=>[]})}}function _$(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 my(t,e=process.platform,r=c$){let n=_$(t,e),s=[];for(let{cmd:o,args:i}of n)try{let a=r(o,i,{stdio:"ignore",timeout:Ki});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 Sy(t,e=process.platform,r=c$){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:Ki});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],f=u[u.length-1];d==="TCP"&&l.endsWith(o)&&(m!=="0.0.0.0:0"&&m!=="[::]:0"||/^\d+$/.test(f)&&i.add(f))}for(let a of i){n.attemptedPids.push(a);try{let c=r("taskkill",["/F","/PID",a],{stdio:"ignore",timeout:Ki});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:Ki});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:Ki});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 MF(){let t=Bg();t>0&&console.error(`Cleaned up ${t} stale DB file(s) from previous sessions`);let e=process.platform==="win32"?yy():"/tmp",r=De(e,`context-mode-mcp-ready-${process.pid}`),n=()=>{ea.cleanupBackgrounded(),pr&&pr.close();try{Ji(_y)}catch{}try{Ji(r)}catch{}if(Fr&&Fr.pid&&!Fr.killed)try{Fr.kill("SIGTERM")}catch{}},s=async()=>{try{py=0,Ku()}catch{}n(),process.exit(0)};process.on("exit",n),process.on("SIGINT",()=>{s()}),process.on("SIGTERM",()=>{s()}),yE({onShutdown:()=>s()});let o=new Eu;await tt.connect(o);try{hy(r,String(process.pid))}catch{}try{let{detectPlatform:i,getAdapter:a}=await Promise.resolve().then(()=>(Io(),fd)),c=tt.server.getClientVersion(),u=i(c??void 0);vn=await a(u.platform),c&&console.error(`MCP client: ${c.name} v${c.version} \u2192 ${u.platform}`)}catch{}try{let i=IE(Xi());if(i){for(let[a,c]of Object.entries(i.calls))se.calls[a]=c;for(let[a,c]of Object.entries(i.bytesReturned))se.bytesReturned[a]=c;i.sessionStart>0&&(se.sessionStart=i.sessionStart)}}catch{}e$().then(i=>{i!=="unknown"&&(Hr=i)}),setInterval(()=>{e$().then(i=>{i!=="unknown"&&(Hr=i)})},3600*1e3).unref(),setInterval(()=>Ku(),6e4).unref(),console.error(`Context Mode MCP server v${Ur} running on stdio`),console.error(`Detected runtimes:
789
+ ${pa(Qi)}`),ys()||(console.error(`
790
+ Performance tip: Install Bun for 3-5x faster JS/TS execution`),console.error(" curl -fsSL https://bun.sh/install | bash"))}var Nt,Ur,Qi,Wu,tt,ea,_y,pr,vn,Fr,se,Hr,qu,QE,dF,pF,t$,_F,xF,vF,bF,py,Vu,SF,kF,wF,EF,Ju,Yu,ds,ay,PF,n$,s$,cy,uy,IF,o$,Ki,v$=v(()=>{"use strict";Dw();Lw();Ng();jg();Kw();uE();lE();hE();fa();gE();_E();Vi();EE();RE();AE();LE();Gr();Io();Ll();vl();Wr();go();JE();Yn();Nt=Qt(oF(import.meta.url)),Ur=(()=>{for(let t of["../package.json","./package.json"]){let e=ct(Nt,t);if(ze(e))try{return JSON.parse(fy(e,"utf8")).version}catch{}}return"unknown"})();process.on("unhandledRejection",t=>{process.stderr.write(`[context-mode] unhandledRejection: ${t}
579
791
  `)});process.on("uncaughtException",t=>{process.stderr.write(`[context-mode] uncaughtException: ${t?.message??t}
580
- `)});ji=so(),xu=Ji(ji),Qe=new nu({name:"context-mode",version:Dr});Qe.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});Qe.server.setRequestHandler(Io,async()=>({prompts:[]}));Qe.server.setRequestHandler(Co,async()=>({resources:[]}));Qe.server.setRequestHandler(Oo,async()=>({resourceTemplates:[]}));Di=new Xo({runtimes:ji,projectRoot:()=>Mi()}),kg=pe(Sg(),`cm-fs-preload-${process.pid}.js`);bg(kg,`(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){}})();
581
- `);yr=null;cs=null,jr=null;re={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()},Mr=null,_u=0,Cw=0,tM=3,rM=3600*1e3;Iw=!1;cM=500,uM=2,lM=3e4,dM=256,xg=0;mM=xu.join(", "),fM=io()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",hM="",gM="";Qe.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.${fM} Available: ${mM}.
792
+ `)});Qi=gs(),Wu=ma(Qi),tt=new ku({name:"context-mode",version:Ur});tt.server.registerCapabilities({prompts:{listChanged:!1},resources:{listChanged:!1}});tt.server.setRequestHandler(Bs,async()=>({prompts:[]}));tt.server.setRequestHandler(Hs,async()=>({resources:[]}));tt.server.setRequestHandler(Zs,async()=>({resourceTemplates:[]}));ea=new lo({runtimes:Qi,projectRoot:()=>fr()}),_y=De(yy(),`cm-fs-preload-${process.pid}.js`);hy(_y,`(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){}})();
793
+ `);pr=null;vn=null,Fr=null;se={calls:{},bytesReturned:{},bytesIndexed:0,bytesSandboxed:0,cacheHits:0,cacheBytesSaved:0,sessionStart:Date.now()},Hr=null,qu=0,QE=0,dF=3,pF=3600*1e3;t$=!1;_F=500,xF=2,vF=3e4,bF=256,py=0;SF=Wu.join(", "),kF=ys()?" (Bun detected \u2014 JS/TS runs 3-5x faster)":"",wF="",EF="";tt.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.${kF} Available: ${SF}.
582
794
 
583
795
  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.
584
796
 
585
- 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.
797
+ THINK IN CODE: When you need to analyze, count, filter, compare, or process data \u2014 write code that does the work and console.log() only the answer. Do NOT read raw data into context to process mentally. Program the analysis, don't compute it in your reasoning. Write robust, pure JavaScript (no npm dependencies). Use only Node.js built-ins (fs, path, child_process). Always wrap in try/catch. Handle null/undefined. Works on both Node.js and Bun.`,inputSchema:U.object({language:U.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:U.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), or IO.puts (Elixir) to output a summary to context."),timeout:U.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:U.boolean().optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),intent:U.string().optional().describe(`What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews \u2014 not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.
586
798
 
587
- When reporting results \u2014 terse like caveman. Technical substance exact. Only fluff die. Pattern: [thing] [action] [reason]. [next step].`,inputSchema:M.object({language:M.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:M.string().describe("Source code to execute. Use console.log (JS/TS), print (Python/Ruby/Perl/R), echo (Shell), echo (PHP), fmt.Println (Go), or IO.puts (Elixir) to output a summary to context."),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs (which is the right layer for this policy). Pass an explicit value for long-running builds (Gradle/Maven/SBT)."),background:M.boolean().optional().default(!1).describe("Keep process running after timeout (for servers/daemons). Returns partial output without killing the process. IMPORTANT: Do NOT add setTimeout/self-close timers in background scripts \u2014 the process must stay alive until the timeout detaches it. For server+fetch patterns, prefer putting both server and fetch in ONE ctx_execute call instead of using background."),intent:M.string().optional().describe(`What you're looking for in the output. When provided and output is large (>5KB), indexes output into knowledge base and returns section titles + previews \u2014 not full content. Use ctx_search(queries: [...]) to retrieve specific sections. Example: 'failing tests', 'HTTP 500 errors'.
588
-
589
- TIP: Use specific technical terms, not just concepts. Check 'Searchable terms' in the response for available vocabulary.`)})},async({language:t,code:e,timeout:r,background:n,intent:o})=>{if(t==="shell"){let s=wg(e,"execute");if(s)return s}else{let s=Uw(e,t,"execute");if(s)return s}try{let s=e;(t==="javascript"||t==="typescript")&&(s=`
799
+ 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=xy(e,"execute");if(o)return o}else{let o=l$(e,t,"execute");if(o)return o}try{let o=e;(t==="javascript"||t==="typescript")&&(o=`
590
800
  // FS read instrumentation \u2014 count bytes read via fs.readFileSync/readFile
591
801
  let __cm_fs=0;
592
802
  process.on('exit',()=>{if(__cm_fs>0)try{process.stderr.write('__CM_FS__:'+__cm_fs+'\\n')}catch{}});
@@ -645,20 +855,18 @@ ${e}
645
855
  }
646
856
  __cm_main().catch(e=>{console.error(e);process.exitCode=1});${n?`
647
857
  setInterval(()=>{},2147483647);`:""}
648
- })(typeof require!=='undefined'?require:null);`);let i=await Di.execute({language:t,code:s,timeout:r,background:n}),a=i.stderr?.match(/__CM_NET__:(\d+)/);a&&(re.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&&(re.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let l=i.stdout?.trim();return i.backgrounded&&l?W("ctx_execute",{content:[{type:"text",text:`${l}
858
+ })(typeof require!=='undefined'?require:null);`);let i=await ea.execute({language:t,code:o,timeout:r,background:n}),a=i.stderr?.match(/__CM_NET__:(\d+)/);a&&(se.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&&(se.bytesSandboxed+=parseInt(c[1]),i.stderr=i.stderr.replace(/\n?__CM_FS__:\d+\n?/g,"")),i.timedOut){let d=i.stdout?.trim();return i.backgrounded&&d?K("ctx_execute",{content:[{type:"text",text:`${d}
649
859
 
650
- _(process backgrounded after ${r}ms \u2014 still running)_`}]}):l?W("ctx_execute",{content:[{type:"text",text:`${l}
860
+ _(process backgrounded after ${r}ms \u2014 still running)_`}]}):d?K("ctx_execute",{content:[{type:"text",text:`${d}
651
861
 
652
- _(timed out after ${r}ms \u2014 partial output shown above)_`}]}):W("ctx_execute",{content:[{type:"text",text:`Execution timed out after ${r}ms
862
+ _(timed out after ${r}ms \u2014 partial output shown above)_`}]}):K("ctx_execute",{content:[{type:"text",text:`Execution timed out after ${r}ms
653
863
 
654
864
  stderr:
655
- ${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:l,output:d}=ig({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(d)>Su?(or(Buffer.byteLength(d)),W("ctx_execute",{content:[{type:"text",text:as(d,o,l?`execute:${t}:error`:`execute:${t}`)}],isError:l})):Buffer.byteLength(d)>ku?(or(Buffer.byteLength(d)),W("ctx_execute",{content:[{type:"text",text:as(d,"errors failures exceptions",l?`execute:${t}:error`:`execute:${t}`)}],isError:l})):W("ctx_execute",{content:[{type:"text",text:d}],isError:l})}let u=i.stdout||"(no output)";return o&&o.trim().length>0&&Buffer.byteLength(u)>Su?(or(Buffer.byteLength(u)),W("ctx_execute",{content:[{type:"text",text:as(u,o,`execute:${t}`)}]})):Buffer.byteLength(u)>ku?W("ctx_execute",Vw(u,`execute:${t}`)):W("ctx_execute",{content:[{type:"text",text:u}]})}catch(s){let i=s instanceof Error?s.message:String(s);return W("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});Su=5e3,ku=102400;Qe.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.
865
+ ${i.stderr}`}],isError:!0})}if(i.exitCode!==0){let{isError:d,output:l}=Xg({language:t,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(l)>Ju?(mr(Buffer.byteLength(l)),K("ctx_execute",{content:[{type:"text",text:vo(l,s,d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):Buffer.byteLength(l)>Yu?(mr(Buffer.byteLength(l)),K("ctx_execute",{content:[{type:"text",text:vo(l,"errors failures exceptions",d?`execute:${t}:error`:`execute:${t}`)}],isError:d})):K("ctx_execute",{content:[{type:"text",text:l}],isError:d})}let u=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(u)>Ju?(mr(Buffer.byteLength(u)),K("ctx_execute",{content:[{type:"text",text:vo(u,s,`execute:${t}`)}]})):Buffer.byteLength(u)>Yu?K("ctx_execute",g$(u,`execute:${t}`)):K("ctx_execute",{content:[{type:"text",text:u}]})}catch(o){let i=o instanceof Error?o.message:String(o);return K("ctx_execute",{content:[{type:"text",text:`Runtime error: ${i}`}],isError:!0})}});Ju=5e3,Yu=102400;tt.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.
656
866
 
657
867
  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.
658
868
 
659
- 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.
660
-
661
- When reporting results \u2014 terse like caveman. Technical substance exact. Only fluff die. Pattern: [thing] [action] [reason]. [next step].`,inputSchema:M.object({path:M.string().describe("Absolute file path or relative to project root"),language:M.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:M.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts."),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:M.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:o})=>{let s=pM(t,"execute_file");if(s)return s;if(e==="shell"){let i=wg(r,"execute_file");if(i)return i}else{let i=Uw(r,e,"execute_file");if(i)return i}try{let i=await Di.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}=ig({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return o&&o.trim().length>0&&Buffer.byteLength(u)>Su?(or(Buffer.byteLength(u)),W("ctx_execute_file",{content:[{type:"text",text:as(u,o,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>ku?(or(Buffer.byteLength(u)),W("ctx_execute_file",{content:[{type:"text",text:as(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 o&&o.trim().length>0&&Buffer.byteLength(a)>Su?(or(Buffer.byteLength(a)),W("ctx_execute_file",{content:[{type:"text",text:as(a,o,`file:${t}`)}]})):Buffer.byteLength(a)>ku?W("ctx_execute_file",Vw(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})}});Qe.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.
869
+ THINK IN CODE: Write code that processes FILE_CONTENT and console.log() only the answer. Don't read files into context to analyze mentally. Write robust, pure JavaScript \u2014 no npm deps, try/catch, null-safe. Node.js + Bun compatible.`,inputSchema:U.object({path:U.string().describe("Absolute file path or relative to project root"),language:U.enum(["javascript","typescript","python","shell","ruby","go","rust","php","perl","r","elixir"]).describe("Runtime language"),code:U.string().describe("Code to process FILE_CONTENT (file_content in Elixir). Print summary via console.log/print/echo/IO.puts."),timeout:U.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs."),intent:U.string().optional().describe("What you're looking for in the output. When provided and output is large (>5KB), returns only matching sections via BM25 search instead of truncated output.")})},async({path:t,language:e,code:r,timeout:n,intent:s})=>{let o=d$(t,"ctx_execute_file");if(o)return o;if(e==="shell"){let i=xy(r,"execute_file");if(i)return i}else{let i=l$(r,e,"execute_file");if(i)return i}try{let i=await ea.executeFile({path:t,language:e,code:r,timeout:n});if(i.timedOut)return K("ctx_execute_file",{content:[{type:"text",text:`Timed out processing ${t} after ${n}ms`}],isError:!0});if(i.exitCode!==0){let{isError:c,output:u}=Xg({language:e,exitCode:i.exitCode,stdout:i.stdout,stderr:i.stderr});return s&&s.trim().length>0&&Buffer.byteLength(u)>Ju?(mr(Buffer.byteLength(u)),K("ctx_execute_file",{content:[{type:"text",text:vo(u,s,c?`file:${t}:error`:`file:${t}`)}],isError:c})):Buffer.byteLength(u)>Yu?(mr(Buffer.byteLength(u)),K("ctx_execute_file",{content:[{type:"text",text:vo(u,"errors failures exceptions",c?`file:${t}:error`:`file:${t}`)}],isError:c})):K("ctx_execute_file",{content:[{type:"text",text:u}],isError:c})}let a=i.stdout||"(no output)";return s&&s.trim().length>0&&Buffer.byteLength(a)>Ju?(mr(Buffer.byteLength(a)),K("ctx_execute_file",{content:[{type:"text",text:vo(a,s,`file:${t}`)}]})):Buffer.byteLength(a)>Yu?K("ctx_execute_file",g$(a,`file:${t}`)):K("ctx_execute_file",{content:[{type:"text",text:a}]})}catch(i){let a=i instanceof Error?i.message:String(i);return K("ctx_execute_file",{content:[{type:"text",text:`Runtime error: ${a}`}],isError:!0})}});tt.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.
662
870
 
663
871
  WHEN TO USE:
664
872
  - Documentation from Context7, Skills, or MCP tools (API docs, framework guides, code examples)
@@ -670,40 +878,38 @@ WHEN TO USE:
670
878
 
671
879
  After indexing, use 'ctx_search' to retrieve specific sections on-demand.
672
880
  When \`path\` is provided, a content hash is stored for automatic stale detection in search results.
673
- Do NOT use for: log files, test output, CSV, build output \u2014 use 'ctx_execute_file' for those.`,inputSchema:M.object({content:M.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:M.string().optional().describe("File path to read and index (content never enters context). Provide this OR content."),source:M.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});try{let n=e?eM(e):void 0;if(t)or(Buffer.byteLength(t));else if(n)try{let i=await import("fs");or(i.readFileSync(n).byteLength)}catch{}let s=no().index({content:t,path:n,source:r??n});return W("ctx_index",{content:[{type:"text",text:`Indexed ${s.totalChunks} sections (${s.codeChunks} with code) from: ${s.label}
674
- Use ctx_search(queries: ["..."]) to query this content. Use source: "${s.label}" to scope results.`}]})}catch(n){let o=n instanceof Error?n.message:String(n);return W("ctx_index",{content:[{type:"text",text:`Index error: ${o}`}],isError:!0})}});to=0,hg=Date.now(),xM=6e4,Nw=3,zw=8;Qe.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.
881
+ Do NOT use for: log files, test output, CSV, build output \u2014 use 'ctx_execute_file' for those.`,inputSchema:U.object({content:U.string().optional().describe("Raw text/markdown to index. Provide this OR path, not both."),path:U.string().optional().describe("File path to read and index (content never enters context). Provide this OR content."),source:U.string().optional().describe("Label for the indexed content (e.g., 'Context7: React useEffect', 'Skill: frontend-design')")})},async({content:t,path:e,source:r})=>{if(!t&&!e)return K("ctx_index",{content:[{type:"text",text:"Error: Either content or path must be provided"}],isError:!0});if(e){let n=d$(e,"ctx_index");if(n)return n}try{let n=e?lF(e):void 0;if(t)mr(Buffer.byteLength(t));else if(n)try{let i=await import("fs");mr(i.readFileSync(n).byteLength)}catch{}let o=ps().index({content:t,path:n,source:r??n});return K("ctx_index",{content:[{type:"text",text:`Indexed ${o.totalChunks} sections (${o.codeChunks} with code) from: ${o.label}
882
+ Use ctx_search(queries: ["..."]) to query this content. Use source: "${o.label}" to scope results.`}]})}catch(n){let s=n instanceof Error?n.message:String(n);return K("ctx_index",{content:[{type:"text",text:`Index error: ${s}`}],isError:!0})}});ds=0,ay=Date.now(),PF=6e4,n$=3,s$=8;tt.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.
675
883
 
676
884
  TIPS: 2-4 specific terms per query. Use 'source' to scope results.
677
885
 
678
- SESSION STATE: If skills, roles, or decisions were set earlier in this conversation, they are still active. Do not discard or contradict them.
679
-
680
- When reporting results \u2014 terse like caveman. Technical substance exact. Only fluff die. Pattern: [thing] [action] [reason]. [next step].`,inputSchema:M.object({queries:M.preprocess(Eg,M.array(M.string()).optional().describe("Array of search queries. Batch ALL questions in one call.")),limit:M.number().optional().default(3).describe("Results per query (default: 3)"),source:M.string().optional().describe("Filter to a specific indexed source (partial match)."),contentType:M.enum(["code","prose"]).optional().describe("Filter results by content type: 'code' or 'prose'."),sort:M.enum(["relevance","timeline"]).optional().default("relevance").describe("Sort mode. 'relevance' (default): BM25 ranked, current session only. 'timeline': chronological across current session, prior sessions, and auto-memory.")})},async t=>{try{let e=no(),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.
886
+ 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(by,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=ps(),r=t.sort||"relevance";if(r!=="timeline"&&e.getStats().chunks===0)return K("ctx_search",{content:[{type:"text",text:`Knowledge base is empty \u2014 no content has been indexed yet.
681
887
 
682
888
  ctx_search is a follow-up tool that queries previously indexed content. To gather and index content first, use:
683
889
  \u2022 ctx_batch_execute(commands, queries) \u2014 run commands, auto-index output, and search in one call
684
890
  \u2022 ctx_fetch_and_index(url) \u2014 fetch a URL, index it, then search with ctx_search
685
891
  \u2022 ctx_index(content, source) \u2014 manually index text content
686
892
 
687
- After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,o=[];if(Array.isArray(n.queries)&&n.queries.length>0?o.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&o.push(n.query),o.length===0)return W("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:s=3,source:i,contentType:a}=t,c=Date.now();if(c-hg>xM&&(to=0,hg=c),to++,to>zw)return W("ctx_search",{content:[{type:"text",text:`BLOCKED: ${to} search calls in ${Math.round((c-hg)/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=to>Nw?1:Math.min(s,2),l=40*1024,d=0,p=[],f=null;if(r==="timeline")try{let g=xr(),y=pe(g,`${us()}${Ii()}.db`);je(y)&&(f=new Qn({dbPath:y}))}catch{}let m=cs?.getConfigDir()??(process.env.CLAUDE_CONFIG_DIR||pe(ro(),".claude"));try{for(let g of o){if(d>l){p.push(`## ${g}
893
+ After indexing, ctx_search becomes available for follow-up queries.`}],isError:!0});let n=t,s=[];if(Array.isArray(n.queries)&&n.queries.length>0?s.push(...n.queries):typeof n.query=="string"&&n.query.length>0&&s.push(n.query),s.length===0)return K("ctx_search",{content:[{type:"text",text:"Error: provide query or queries."}],isError:!0});let{limit:o=3,source:i,contentType:a}=t,c=Date.now();if(c-ay>PF&&(ds=0,ay=c),ds++,ds>s$)return K("ctx_search",{content:[{type:"text",text:`BLOCKED: ${ds} search calls in ${Math.round((c-ay)/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=ds>n$?1:Math.min(o,2),d=40*1024,l=0,m=[],f=null;if(r==="timeline")try{let g=at(),y=fr(),_=Mu({projectDir:y,sessionsDir:g});ze(_)&&(f=new Lr({dbPath:_}))}catch{}let p=vn?.getConfigDir()??ly();try{for(let g of s){if(l>d){m.push(`## ${g}
688
894
  (output cap reached)
689
- `);continue}let y;if(r==="timeline"?y=Sw({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:f,projectDir:Mi(),configDir:m,adapter:cs??void 0}):y=e.searchWithFallback(g,u,i,a),y.length===0){p.push(`## ${g}
690
- No results found.`);continue}let _=y.map((x,k)=>{let E=x.origin||"current-session",H=x.timestamp?x.timestamp.slice(0,16).replace("T"," "):"",z=`--- [${E}${H?" | "+H:""} | ${x.source}] ---`,K=`### ${x.title}`,Le=$g(x.content,g,1500,x.highlighted);return`${z}
691
- ${K}
895
+ `);continue}let y;if(r==="timeline"?y=zE({query:g,limit:u,store:e,sort:r,source:i,contentType:a,sessionDB:f,projectDir:fr(),configDir:p,adapter:vn??void 0}):y=e.searchWithFallback(g,u,i,a),y.length===0){m.push(`## ${g}
896
+ No results found.`);continue}let _=y.map((x,S)=>{let w=x.origin||"current-session",I=x.timestamp?x.timestamp.slice(0,16).replace("T"," "):"",O=`--- [${w}${I?" | "+I:""} | ${x.source}] ---`,C=`### ${x.title}`,F=vy(x.content,g,1500,x.highlighted);return`${O}
897
+ ${C}
692
898
 
693
- ${Le}`}).join(`
899
+ ${F}`}).join(`
694
900
 
695
- `);p.push(`## ${g}
901
+ `);m.push(`## ${g}
696
902
 
697
- ${_}`),d+=_.length}}finally{try{f?.close()}catch{}}let h=p.join(`
903
+ ${_}`),l+=_.length}}finally{try{f?.close()}catch{}}let h=m.join(`
698
904
 
699
905
  ---
700
906
 
701
907
  `);if(e.lastRefreshCount>0&&(h=`> Auto-refreshed ${e.lastRefreshCount} stale source${e.lastRefreshCount>1?"s":""} (file changed since indexing).
702
908
 
703
- `+h),to>=Nw&&(h+=`
909
+ `+h),ds>=n$&&(h+=`
704
910
 
705
- \u26A0 search call #${to}/${zw} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),h.trim().length===0){let g=e.listSources(),y=g.length>0?`
706
- Indexed sources: ${g.map(_=>`"${_.label}" (${_.chunkCount} sections)`).join(", ")}`:"";return W("ctx_search",{content:[{type:"text",text:`No results found.${y}`}]})}return W("ctx_search",{content:[{type:"text",text:h}]})}catch(e){let r=e instanceof Error?e.message:String(e);return W("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});gg=null,_g=null;wM=1440*60*1e3,jw=3072;Qe.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.
911
+ \u26A0 search call #${ds}/${s$} in this window. Results limited to ${u}/query. Batch queries: ctx_search(queries: ["q1","q2","q3"]) or use ctx_batch_execute.`),h.trim().length===0){let g=e.listSources(),y=g.length>0?`
912
+ Indexed sources: ${g.map(_=>`"${_.label}" (${_.chunkCount} sections)`).join(", ")}`:"";return K("ctx_search",{content:[{type:"text",text:`No results found.${y}`}]})}return K("ctx_search",{content:[{type:"text",text:h}]})}catch(e){let r=e instanceof Error?e.message:String(e);return K("ctx_search",{content:[{type:"text",text:`Search error: ${r}`}],isError:!0})}});cy=null,uy=null;IF=1440*60*1e3,o$=3072;tt.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.
707
913
 
708
914
  Better than WebFetch: preview is immediate, full content is searchable, raw HTML never enters context.
709
915
 
@@ -713,17 +919,15 @@ PARALLELIZE I/O: For multi-URL research (library evaluation, migration scans, do
713
919
  \u2705 Use concurrency: 4-8 for: library docs sweep, multi-changelog scan, competitive pricing pages, multi-region docs, GitHub raw file pulls.
714
920
  \u274C Single URL \u2192 use the legacy {url, source} shape (concurrency irrelevant).
715
921
  Example: requests: [{url: 'https://react.dev/...', source: 'react'}, {url: 'https://vuejs.org/...', source: 'vue'}], concurrency: 5.
716
- Indexing is serial regardless of concurrency \u2014 fetches race, FTS5 writes don't (avoids SQLite WAL contention).
717
-
718
- When reporting results \u2014 terse like caveman. Technical substance exact. Only fluff die. Pattern: [thing] [action] [reason]. [next step].`,inputSchema:M.object({url:M.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:M.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:M.array(M.object({url:M.string().describe("URL to fetch"),source:M.string().optional().describe("Label for this URL's indexed content")})).min(1).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:M.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:M.boolean().optional().describe("Skip cache and re-fetch even if content was recently indexed")})},async({url:t,source:e,requests:r,concurrency:n,force:o})=>{let s=r||(t?[{url:t,source:e}]:[]);if(s.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&&s.length===1,a=n??1,c=s.map(P=>({run:()=>EM(P.url,P.source,o)})),{settled:u,effectiveConcurrency:l,capped:d}=await Gh(c,{concurrency:a,capByCpuCount:!i&&a>1}),p=[];for(let P=0;P<u.length;P++){let N=u[P];if(N.status==="rejected"){let De=N.reason instanceof Error?N.reason.message:String(N.reason);p.push({kind:"job_error",url:s[P].url,error:De});continue}let ce=N.value;ce.kind==="cached"?(re.cacheHits++,re.cacheBytesSaved+=ce.estimatedBytes,p.push({kind:"cached",label:ce.label,chunkCount:ce.chunkCount,ageStr:ce.ageStr})):ce.kind==="fetch_error"?p.push({kind:"fetch_error",url:ce.url,error:ce.error,reason:ce.reason}):p.push({kind:"fetched",indexed:TM(ce)})}if(i){let P=p[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).
922
+ Fetches parallelize up to your concurrency setting; FTS5 indexing serializes the writes after (SQLite single-writer rule).`,inputSchema:U.object({url:U.string().optional().describe("Single URL to fetch and index (legacy single-shape)"),source:U.string().optional().describe("Label for the indexed content when using single `url` (e.g., 'React useEffect docs', 'Supabase Auth API'). For batch, put source in each requests entry."),requests:U.array(U.object({url:U.string().describe("URL to fetch"),source:U.string().optional().describe("Label for this URL's indexed content")})).min(1).optional().describe("Batch shape: array of {url, source?} entries. Use with concurrency>1 for parallel fetch. Each request indexed under its own source label. Output preserves input order."),concurrency:U.coerce.number().int().min(1).max(8).optional().default(1).describe("Max URLs to fetch in parallel (1-8, default: 1). Use 4-8 for I/O-bound multi-URL batches (library docs, changelogs, pricing pages). Capped by os.cpus().length on small machines (response notes when capped). Indexing is always serial regardless \u2014 only fetches race."),force:U.boolean().optional().describe("Skip cache and re-fetch even if content was recently indexed")})},async({url:t,source:e,requests:r,concurrency:n,force:s})=>{let o=r||(t?[{url:t,source:e}]:[]);if(o.length===0)return K("ctx_fetch_and_index",{content:[{type:"text",text:"ctx_fetch_and_index requires either `url` (single) or `requests: [{url, source?}, ...]` (batch)."}],isError:!0});let i=!r&&o.length===1,a=n??1,c=o.map(T=>({run:()=>NF(T.url,T.source,s)})),{settled:u,effectiveConcurrency:d,capped:l}=await zg(c,{concurrency:a,capByCpuCount:!i&&a>1}),m=[];for(let T=0;T<u.length;T++){let R=u[T];if(R.status==="rejected"){let oe=R.reason instanceof Error?R.reason.message:String(R.reason);m.push({kind:"job_error",url:o[T].url,error:oe});continue}let V=R.value;if(V.kind==="cached"){se.cacheHits++,se.cacheBytesSaved+=V.estimatedBytes;let oe=V.estimatedBytes,fe=V.label;setImmediate(()=>PE({sessionDbPath:Xi(),source:fe,bytesAvoided:oe})),m.push({kind:"cached",label:V.label,chunkCount:V.chunkCount,ageStr:V.ageStr})}else V.kind==="fetch_error"?m.push({kind:"fetch_error",url:V.url,error:V.error,reason:V.reason}):m.push({kind:"fetched",indexed:DF(V)})}if(i){let T=m[0];if(T.kind==="cached")return K("ctx_fetch_and_index",{content:[{type:"text",text:`Cached: **${T.label}** \u2014 ${T.chunkCount} sections, indexed ${T.ageStr} (fresh, TTL: 24h).
719
923
  To refresh: call ctx_fetch_and_index again with \`force: true\`.
720
924
 
721
925
  You MUST call ctx_search() to answer questions about this content \u2014 this cached response contains no content.
722
- Use: ctx_search(queries: [...], source: "${P.label}")`}]});if(P.kind==="fetched"){let N=(P.indexed.totalBytes/1024).toFixed(1),ce=[`Fetched and indexed **${P.indexed.totalChunks} sections** (${N}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(`
723
- `);return W("ctx_fetch_and_index",{content:[{type:"text",text:ce}]})}if(P.kind==="fetch_error"){let N=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:N}],isError:!0})}return W("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${P.error}`}],isError:!0})}let f=384,m=[],h=0,g=0,y=0,_=0,x=0,k=[];for(let P of p)if(P.kind==="cached")y++,m.push(`- [cache] ${P.label} \u2014 ${P.chunkCount} sections (${P.ageStr})`);else if(P.kind==="fetched"){_++,h+=P.indexed.totalChunks,g+=P.indexed.totalBytes;let N=(P.indexed.totalBytes/1024).toFixed(1);m.push(`- [new] ${P.indexed.label} \u2014 ${P.indexed.totalChunks} sections (${N}KB)`);let ce=P.indexed.preview.length>f?P.indexed.preview.slice(0,f).trimEnd()+"\u2026":P.indexed.preview;k.push(`### ${P.indexed.label}
926
+ Use: ctx_search(queries: [...], source: "${T.label}")`}]});if(T.kind==="fetched"){let R=(T.indexed.totalBytes/1024).toFixed(1),V=[`Fetched and indexed **${T.indexed.totalChunks} sections** (${R}KB) from: ${T.indexed.label}`,`Full content indexed in sandbox \u2014 use ctx_search(queries: [...], source: "${T.indexed.label}") for specific lookups.`,"","---","",T.indexed.preview].join(`
927
+ `);return K("ctx_fetch_and_index",{content:[{type:"text",text:V}]})}if(T.kind==="fetch_error"){let R=T.reason==="empty"?`Fetched ${T.url} but got empty content`:T.reason==="read"?`Fetched ${T.url} but could not read subprocess output`:T.reason==="exit"?`Failed to fetch ${T.url}: ${T.error}`:`Fetch error: ${T.error}`;return K("ctx_fetch_and_index",{content:[{type:"text",text:R}],isError:!0})}return K("ctx_fetch_and_index",{content:[{type:"text",text:`Fetch error: ${T.error}`}],isError:!0})}let f=384,p=[],h=0,g=0,y=0,_=0,x=0,S=[];for(let T of m)if(T.kind==="cached")y++,p.push(`- [cache] ${T.label} \u2014 ${T.chunkCount} sections (${T.ageStr})`);else if(T.kind==="fetched"){_++,h+=T.indexed.totalChunks,g+=T.indexed.totalBytes;let R=(T.indexed.totalBytes/1024).toFixed(1);p.push(`- [new] ${T.indexed.label} \u2014 ${T.indexed.totalChunks} sections (${R}KB)`);let V=T.indexed.preview.length>f?T.indexed.preview.slice(0,f).trimEnd()+"\u2026":T.indexed.preview;S.push(`### ${T.indexed.label}
724
928
 
725
- ${ce}`)}else x++,m.push(`- [err] ${P.url}: ${P.error}`);let E=(g/1024).toFixed(1),H=d?` cap=${l}/${YD().length}cpu`:"",z=(P,N,ce)=>`${P} ${P===1?N:ce}`,Le=[`fetched ${s.length} c=${l}${H}. ok=${_} cache=${y} err=${x}. ${z(h,"section","sections")} ${E}KB.`,"",...m,"",'ctx_search(queries: [...], source: "<label>") for full content.',...k.length>0?["","---","",...k]:[]].join(`
726
- `);return W("ctx_fetch_and_index",{content:[{type:"text",text:Le}],isError:x===s.length})});Qe.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.
929
+ ${V}`)}else x++,p.push(`- [err] ${T.url}: ${T.error}`);let w=(g/1024).toFixed(1),I=l?` cap=${d}/${iF().length}cpu`:"",O=(T,R,V)=>`${T} ${T===1?R:V}`,F=[`fetched ${o.length} c=${d}${I}. ok=${_} cache=${y} err=${x}. ${O(h,"section","sections")} ${w}KB.`,"",...p,"",'ctx_search(queries: [...], source: "<label>") for full content.',...S.length>0?["","---","",...S]:[]].join(`
930
+ `);return K("ctx_fetch_and_index",{content:[{type:"text",text:F}],isError:x===o.length})});tt.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.
727
931
 
728
932
  THIS IS THE PRIMARY TOOL. Use this instead of multiple ctx_execute() calls.
729
933
 
@@ -736,61 +940,60 @@ PARALLELIZE I/O: For I/O-bound batches (network calls, slow API queries, multi-U
736
940
  Example: [gh issue view 1, gh issue view 2, gh issue view 3] \u2192 concurrency: 3.
737
941
  Speedup depends on workload \u2014 applies to I/O wait, not CPU work.
738
942
 
739
- 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.
740
-
741
- When reporting results \u2014 terse like caveman. Technical substance exact. Only fluff die. Pattern: [thing] [action] [reason]. [next step].`,inputSchema:M.object({commands:M.preprocess(vM,M.array(M.object({label:M.string().describe("Section header for this command's output (e.g., 'README', 'Package.json', 'Source Tree')"),command:M.string().describe("Shell command to execute")})).min(1).describe("Commands to execute as a batch. Output is labeled with the section header. Default order is sequential; pass concurrency>1 to run in parallel (output stays in input order).")),queries:M.preprocess(Eg,M.array(M.string()).min(1).describe("Search queries to extract information from indexed output. Use 5-8 comprehensive queries. Each returns top 5 matching sections with full content. This is your ONLY chance \u2014 put ALL your questions here. No follow-up calls needed.")),timeout:M.coerce.number().optional().describe("Max execution time in ms. When omitted, no server-side timer fires \u2014 the MCP host's RPC timeout governs. With concurrency=1, the value (when set) is a shared budget across commands; with concurrency>1, it is applied per-command."),concurrency:M.coerce.number().int().min(1).max(8).optional().default(1).describe("Max commands to run in parallel (1-8, default: 1). Use 4-8 for I/O-bound batches (network, gh, curl, multi-repo git reads). Keep at 1 for CPU-bound (npm test, build, lint) or stateful commands (ports, locks). >1 switches to per-command timeouts (no shared budget) and individual `(timed out)` blocks instead of cascading skip.")})},async({commands:t,queries:e,timeout:r,concurrency:n})=>{for(let o of t){let s=wg(o.command,"batch_execute");if(s)return s}try{let o=qw(ji.shell,kg),{outputs:s,timedOut:i}=await Bw(t,{timeout:r,concurrency:n,nodeOptsPrefix:o,onFsBytes:x=>{re.bytesSandboxed+=x}},Di),a=s.join(`
943
+ 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(RF,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(by,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=xy(s.command,"batch_execute");if(o)return o}try{let s=f$(Qi.shell,_y),{outputs:o,timedOut:i}=await h$(t,{timeout:r,concurrency:n,nodeOptsPrefix:s,onFsBytes:x=>{se.bytesSandboxed+=x}},ea),a=o.join(`
742
944
  `),c=Buffer.byteLength(a),u=a.split(`
743
- `).length;if(i&&s.length===0)return W("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});or(c);let l=no(),d=`batch:${t.map(x=>x.label).join(",").slice(0,80)}`,p=l.index({content:a,source:d}),f=l.getChunksBySource(p.sourceId),m=["## Indexed Sections",""],h=[];for(let x of f){let k=Buffer.byteLength(x.content);m.push(`- ${x.title} (${(k/1024).toFixed(1)}KB)`),h.push(x.title)}let g=Hw(l,e,d),y=l.getDistinctiveTerms?l.getDistinctiveTerms(p.sourceId):[],_=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${p.totalChunks} sections. Searched ${e.length} queries.`,"",...m,"",...g,y.length>0?`
945
+ `).length;if(i&&o.length===0)return K("ctx_batch_execute",{content:[{type:"text",text:`Batch timed out after ${r}ms. No output captured.`}],isError:!0});mr(c);let d=ps(),l=`batch:${t.map(x=>x.label).join(",").slice(0,80)}`,m=d.index({content:a,source:l}),f=d.getChunksBySource(m.sourceId),p=["## Indexed Sections",""],h=[];for(let x of f){let S=Buffer.byteLength(x.content);p.push(`- ${x.title} (${(S/1024).toFixed(1)}KB)`),h.push(x.title)}let g=m$(d,e,l),y=d.getDistinctiveTerms?d.getDistinctiveTerms(m.sourceId):[],_=[`Executed ${t.length} commands (${u} lines, ${(c/1024).toFixed(1)}KB). Indexed ${m.totalChunks} sections. Searched ${e.length} queries.`,"",...p,"",...g,y.length>0?`
744
946
  Searchable terms for follow-up: ${y.join(", ")}`:""].join(`
745
- `);return W("ctx_batch_execute",{content:[{type:"text",text:_}]})}catch(o){let s=o instanceof Error?o.message:String(o);return W("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${s}`}],isError:!0})}});Qe.registerTool("ctx_stats",{title:"Session Statistics",description:"Returns context consumption statistics for the current session. Shows total bytes returned to context, breakdown by tool, call counts, estimated token usage, and context savings ratio.",inputSchema:M.object({})},async()=>{let t;try{let e=us(),r=Ii(),n=pe(xr(),`${e}${r}.db`);if(je(n)){let o=zr(),s=new o(n,{readonly:!0});try{let i=new is(s),a=i.queryAll(re),c=i.getMcpToolUsage(),u=Ni();t=gu(a,Dr,Mr,{lifetime:u,mcpUsage:c})}finally{s.close()}}else{let s=new is(Dw()).queryAll(re),i=Ni();t=gu(s,Dr,Mr,{lifetime:i})}}catch{let r=new is(Dw()).queryAll(re),n;try{n=Ni()}catch{}t=gu(r,Dr,Mr,n?{lifetime:n}:void 0)}return W("ctx_stats",{content:[{type:"text",text:t}]})});Qe.registerTool("ctx_doctor",{title:"Run Diagnostics",description:"Diagnose context-mode installation. Runs all checks server-side and returns a plain-text status report with [OK]/[FAIL]/[WARN] prefixes (renderer-safe across MCP clients). No CLI execution needed.",inputSchema:M.object({})},async()=>{let t=["context-mode doctor",""],e=je(ot(kt,"package.json"))?kt:nr(kt),r=11,n=(xu.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${xu.length}/${r} (${n}%) \u2014 ${xu.join(", ")}`),io()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");{let s=new Xo({runtimes:ji});try{let i=await s.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{s.cleanupBackgrounded()}}{let s;try{let i=zr();s=new i(":memory:"),s.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),s.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let a=s.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{s?.close()}catch{}}}let o=ot(e,"hooks","pretooluse.mjs");return je(o)?t.push(`[OK] Hook script: PASS \u2014 ${o}`):t.push(`[FAIL] Hook script: FAIL \u2014 not found at ${o}`),t.push(`[OK] Version: v${Dr}`),W("ctx_doctor",{content:[{type:"text",text:t.join(`
746
- `)}]})});Qe.registerTool("ctx_upgrade",{title:"Upgrade Plugin",description:"Upgrade context-mode to the latest version. Returns a shell command to execute. You MUST run the returned command using your shell tool (Bash, shell_execute, run_in_terminal, etc.) and display the output as a checklist. Tell the user to restart their session after upgrade.",inputSchema:M.object({})},async()=>{let t=je(ot(kt,"package.json"))?kt:nr(kt),e=ot(t,"cli.bundle.mjs"),r=ot(t,"build","cli.js");try{let s=xr(),i=pe(nr(s),"insight-cache");if(je(i)){try{process.platform==="win32"?qt(`for /f "tokens=5" %a in ('netstat -ano ^| findstr :4747') do taskkill /F /PID %a`,{stdio:"pipe"}):qt("lsof -ti:4747 | xargs kill 2>/dev/null",{stdio:"pipe"})}catch{}vu(i,{recursive:!0,force:!0})}}catch{}let n;if(je(e))n=`${ye(e)} upgrade`;else if(je(r))n=`${ye(r)} upgrade`;else{let s="https://github.com/mksglu/context-mode.git",i=["build","hooks","skills","scripts",".claude-plugin"],a=["start.mjs","server.bundle.mjs","cli.bundle.mjs","package.json"],c=['import{execFileSync}from"node:child_process";','import{cpSync,rmSync,existsSync,mkdtempSync}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","${s}",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");',...i.map(d=>`if(existsSync(join(T,${JSON.stringify(d)})))cpSync(join(T,${JSON.stringify(d)}),join(P,${JSON.stringify(d)}),{recursive:true,force:true});`),...a.map(d=>`if(existsSync(join(T,${JSON.stringify(d)})))cpSync(join(T,${JSON.stringify(d)}),join(P,${JSON.stringify(d)}),{force:true});`),'console.log("- [x] Copied build artifacts");','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(`
747
- `),u=ot(t,".ctx-upgrade-inline.mjs"),{writeFileSync:l}=await import("node:fs");l(u,c),n=ye(u)}let o=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",n,"```","","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(`
748
- `);return W("ctx_upgrade",{content:[{type:"text",text:o}]})});Qe.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:"Permanently deletes ALL session data for this project: FTS5 knowledge base (indexed content), session events DB (analytics, metadata, resume snapshots), and session events markdown. Resets in-memory stats. This is irreversible.",inputSchema:M.object({confirm:M.boolean().describe("Must be true to confirm the destructive operation.")})},async({confirm:t})=>{if(!t)return W("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let e=[];if(yr){let r=!1;try{yr.cleanup(),r=!0}catch{}yr=null,r&&e.push("knowledge base (FTS5)")}else{let r=yg(),n=!1;for(let o of["","-wal","-shm"])try{_r(r+o),n=!0}catch{}n&&e.push("knowledge base (FTS5)")}try{let r=pe(ro(),".context-mode","content",`${us()}.db`);for(let n of["","-wal","-shm"])try{_r(r+n)}catch{}}catch{}try{let r=us(),n=Ii(),o=xr(),s=pe(o,`${r}${n}.db`),i=pe(o,`${r}${n}-events.md`),a=pe(o,`${r}${n}.cleanup`),c=!1;for(let l of["","-wal","-shm"])try{_r(s+l),c=!0}catch{}c&&e.push("session events DB");let u=!1;try{_r(i),u=!0}catch{}u&&e.push("session events markdown");try{_r(a)}catch{}}catch{}re.calls={},re.bytesReturned={},re.bytesIndexed=0,re.bytesSandboxed=0,re.cacheHits=0,re.cacheBytesSaved=0,re.sessionStart=Date.now(),e.push("session stats");try{let r=Fw();je(r)&&_r(r)}catch{}return W("ctx_purge",{content:[{type:"text",text:`Purged: ${e.join(", ")}. All session data for this project has been permanently deleted.`}]})});Qe.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:M.object({port:M.coerce.number().optional().describe("Port to serve on (default: 4747)"),sessionDir:M.string().optional().describe("Override INSIGHT_SESSION_DIR: directory containing context-mode session .db files"),contentDir:M.string().optional().describe("Override INSIGHT_CONTENT_DIR: directory containing context-mode content/index .db files"),insightSessionDir:M.string().optional().describe("Alias for sessionDir / INSIGHT_SESSION_DIR"),insightContentDir:M.string().optional().describe("Alias for contentDir / INSIGHT_CONTENT_DIR")})},async({port:t,sessionDir:e,contentDir:r,insightSessionDir:n,insightContentDir:o})=>{let s=t||4747,i=e||n,a=r||o,c=je(ot(kt,"package.json"))?kt:nr(kt),u=ot(c,"insight"),l=i?ot(i):xr(),d=a?ot(a):pe(nr(l),"content"),p=pe(nr(l),"insight-cache");if(!je(pe(u,"server.mjs")))return W("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let f=[],m=!1;zi(p,{recursive:!0});let h=Rw(pe(u,"server.mjs")).mtimeMs,g=je(pe(p,"server.mjs"))?Rw(pe(p,"server.mjs")).mtimeMs:0;if(h>g&&(f.push("Copying source files..."),BD(u,p,{recursive:!0,force:!0}),f.push("Source files copied."),m=!0),!je(pe(p,"node_modules"))||m){f.push("Installing dependencies (first run, ~30s)...");try{qt(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:p,stdio:"pipe",timeout:3e5})}catch{try{vu(pe(p,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!je(pe(p,"node_modules","vite"))||!je(pe(p,"node_modules","better-sqlite3")))throw vu(pe(p,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");f.push("Dependencies installed.")}f.push("Building dashboard..."),qt("npx vite build",{cwd:p,stdio:"pipe",timeout:6e4}),f.push("Build complete.");let _=!1;try{let{request:z}=await import("node:http");await new Promise((K,Le)=>{let P=z(`http://127.0.0.1:${s}/api/overview`,{timeout:2e3},N=>{N.resume(),K()});P.on("error",()=>Le()),P.on("timeout",()=>{P.destroy(),Le()}),P.end()}),_=!0}catch{}if(_&&m){f.push("Killing stale dashboard server (source updated)...");try{process.platform==="win32"?qt(`for /f "tokens=5" %a in ('netstat -ano ^| findstr :${s}') do taskkill /F /PID %a`,{stdio:"pipe"}):qt(`lsof -ti:${s} | xargs kill 2>/dev/null`,{stdio:"pipe"}),await new Promise(z=>setTimeout(z,500))}catch{}f.push("Stale server killed.")}else if(_){f.push("Dashboard already running.");let z=`http://localhost:${s}`,K=process.platform;try{K==="darwin"?qt(`open "${z}"`,{stdio:"pipe"}):K==="win32"?qt(`start "" "${z}"`,{stdio:"pipe"}):qt(`xdg-open "${z}" 2>/dev/null || sensible-browser "${z}" 2>/dev/null`,{stdio:"pipe"})}catch{}return W("ctx_insight",{content:[{type:"text",text:`Dashboard already running at http://localhost:${s}`}]})}if(jr&&jr.pid&&!jr.killed)try{jr.kill("SIGTERM")}catch{}let{spawn:x}=await import("node:child_process"),k=x("node",[pe(p,"server.mjs")],{cwd:p,env:{...process.env,PORT:String(s),INSIGHT_SESSION_DIR:l,INSIGHT_CONTENT_DIR:d,INSIGHT_PARENT_PID:String(process.pid)},detached:!0,stdio:"ignore"});k.on("error",()=>{}),k.unref(),jr=k,await new Promise(z=>setTimeout(z,1500));try{let{request:z}=await import("node:http");await new Promise((K,Le)=>{let P=z(`http://127.0.0.1:${s}/api/overview`,{timeout:3e3},N=>{K(),N.resume()});P.on("error",Le),P.on("timeout",()=>{P.destroy(),Le(new Error("timeout"))}),P.end()})}catch{return W("ctx_insight",{content:[{type:"text",text:`Port ${s} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
947
+ `);return K("ctx_batch_execute",{content:[{type:"text",text:_}]})}catch(s){let o=s instanceof Error?s.message:String(s);return K("ctx_batch_execute",{content:[{type:"text",text:`Batch execution error: ${o}`}],isError:!0})}});tt.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=fr(),r=us(e),n=Mu({projectDir:e,sessionsDir:at()});if(ze(n)){let s=Xt(),o=new s(n,{readonly:!0});try{let i=new xo(o),a=i.queryAll(se),c=i.getMcpToolUsage(),u=Gi({sessionsDir:at()}),d;try{d=Hu()}catch{}let l,m;try{let f=process.env.CLAUDE_SESSION_ID;if(f||(f=o.prepare("SELECT session_id FROM session_events WHERE session_id LIKE '________-____-____-____-____________' ORDER BY created_at DESC LIMIT 1").get()?.session_id),f){l=GE({sessionId:f,sessionsDir:at(),worktreeHash:r});let p=iy({sessionId:f,sessionsDir:at(),worktreeHash:r}),h=iy({sessionsDir:at()});m={conversation:p,lifetime:h}}}catch{}t=Bu(a,Ur,Hr,{lifetime:u,mcpUsage:c,multiAdapter:d,conversation:l,realBytes:m})}finally{o.close()}}else{let o=new xo(i$()).queryAll(se),i=Gi({sessionsDir:at()}),a;try{a=Hu()}catch{}t=Bu(o,Ur,Hr,{lifetime:i,multiAdapter:a})}}catch{let r=new xo(i$()).queryAll(se),n;try{n=Gi({sessionsDir:at()})}catch{}let s;try{s=Hu()}catch{}t=Bu(r,Ur,Hr,n||s?{lifetime:n,multiAdapter:s}:void 0)}return K("ctx_stats",{content:[{type:"text",text:t}]})});tt.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(ct(Nt,"package.json"))?Nt:Qt(Nt),r=11,n=(Wu.length/r*100).toFixed(0);t.push(`[OK] Runtimes: ${Wu.length}/${r} (${n}%) \u2014 ${Wu.join(", ")}`),ys()?t.push("[OK] Performance: FAST (Bun)"):t.push("[WARN] Performance: NORMAL \u2014 install Bun for 3-5x speed boost");{let o=new lo({runtimes:Qi});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=Xt();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 uF();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=ha(s,e);o.length===0&&t.push("[OK] Hook scripts: no direct .mjs script paths to verify");for(let i of o){let a=ct(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${Ur}`),K("ctx_doctor",{content:[{type:"text",text:t.join(`
948
+ `)}]})});tt.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(ct(Nt,"package.json"))?Nt:Qt(Nt),e=ct(t,"cli.bundle.mjs"),r=ct(t,"build","cli.js");try{let o=at(),i=De(Qt(o),"insight-cache");ze(i)&&(Sy(4747),Gu(i,{recursive:!0,force:!0}))}catch{}let n;if(ze(e))n=`${Fe(e)} upgrade`;else if(ze(r))n=`${Fe(r)} upgrade`;else{let i=['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(`
949
+ `),a=ct(t,".ctx-upgrade-inline.mjs"),{writeFileSync:c}=await import("node:fs");c(a,i),n=Fe(a)}let s=["## ctx-upgrade","","Run this command using your shell execution tool:","","```",n,"```","","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(`
950
+ `);return K("ctx_upgrade",{content:[{type:"text",text:s}]})});tt.registerTool("ctx_purge",{title:"Purge Knowledge Base",description:"Permanently deletes ALL session data for this project: FTS5 knowledge base (indexed content), session events DB (analytics, metadata, resume snapshots), and session events markdown. Resets in-memory stats. This is irreversible.",inputSchema:U.object({confirm:U.boolean().describe("Must be true to confirm the destructive operation.")})},async({confirm:t})=>{if(!t)return K("ctx_purge",{content:[{type:"text",text:"Purge cancelled. Pass confirm: true to proceed."}]});let e;try{e=dy()}catch{}if(pr){try{pr.cleanup()}catch{}pr=null}let r=e?Qt(e):void 0,{deleted:n}=wE({projectDir:fr(),sessionsDir:at(),storePath:e,contentDir:r,legacyContentDir:De(gy(),".context-mode","content"),contentHash:cs(fr())});se.calls={},se.bytesReturned={},se.bytesIndexed=0,se.bytesSandboxed=0,se.cacheHits=0,se.cacheBytesSaved=0,se.sessionStart=Date.now(),n.push("session stats");try{let s=u$();ze(s)&&Ji(s)}catch{}return K("ctx_purge",{content:[{type:"text",text:`Purged: ${n.join(", ")}. All session data for this project has been permanently deleted.`}]})});Ki=5e3;tt.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(ct(Nt,"package.json"))?Nt:Qt(Nt),u=ct(c,"insight"),d=i?ct(i):at(),l=a?ct(a):De(Qt(d),"content"),m=De(Qt(d),"insight-cache");if(!ze(De(u,"server.mjs")))return K("ctx_insight",{content:[{type:"text",text:"Error: Insight source not found in plugin. Try upgrading context-mode."}]});try{let f=[],p=!1;Yi(m,{recursive:!0});let h=YE(De(u,"server.mjs")).mtimeMs,g=ze(De(m,"server.mjs"))?YE(De(m,"server.mjs")).mtimeMs:0;if(h>g&&(f.push("Copying source files..."),eF(u,m,{recursive:!0,force:!0}),f.push("Source files copied."),p=!0),!ze(De(m,"node_modules"))||p){f.push("Installing dependencies (first run, ~30s)...");try{XE(process.platform==="win32"?"npm.cmd install --production=false":"npm install --production=false",{cwd:m,stdio:"pipe",timeout:3e5})}catch{try{Gu(De(m,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!ze(De(m,"node_modules","vite"))||!ze(De(m,"node_modules","better-sqlite3")))throw Gu(De(m,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry");f.push("Dependencies installed.")}f.push("Building dashboard..."),XE("npx vite build",{cwd:m,stdio:"pipe",timeout:6e4}),f.push("Build complete.");let _=!1;try{let{request:C}=await import("node:http");await new Promise((F,T)=>{let R=C(`http://127.0.0.1:${o}/api/overview`,{timeout:2e3},V=>{V.resume(),F()});R.on("error",()=>T()),R.on("timeout",()=>{R.destroy(),T()}),R.end()}),_=!0}catch{}if(_&&p){f.push("Killing stale dashboard server (source updated)...");let C=Sy(o);if(C.attemptedPids.length>0&&C.killedPids.length===0)return K("ctx_insight",{content:[{type:"text",text:`Could not free port ${o} (kill failed for ${C.attemptedPids.join(", ")}: ${C.errors.join("; ")}). Try ctx_insight({ port: ${o+1} }) or stop the process manually.`}]});if(C.errors.length>0&&C.attemptedPids.length===0)return K("ctx_insight",{content:[{type:"text",text:`Cannot reclaim port ${o}: ${C.errors.join("; ")}. Stop the process manually or pick another port.`}]});await new Promise(F=>setTimeout(F,500)),f.push(`Stale server killed (${C.killedPids.length} pid${C.killedPids.length===1?"":"s"}).`)}else if(_){f.push("Dashboard already running.");let C=`http://localhost:${o}`,F=my(C),T=F.ok?"":` (auto-open failed: ${F.reason}; navigate manually)`;return K("ctx_insight",{content:[{type:"text",text:`Dashboard already running at ${C}${T}`}]})}if(Fr&&Fr.pid&&!Fr.killed)try{Fr.kill("SIGTERM")}catch{}let{spawn:x}=await import("node:child_process"),S=x("node",[De(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(),Fr=S,await new Promise(C=>setTimeout(C,1500));try{let{request:C}=await import("node:http");await new Promise((F,T)=>{let R=C(`http://127.0.0.1:${o}/api/overview`,{timeout:3e3},V=>{F(),V.resume()});R.on("error",T),R.on("timeout",()=>{R.destroy(),T(new Error("timeout"))}),R.end()})}catch{return K("ctx_insight",{content:[{type:"text",text:`Port ${o} appears to be in use. Either a previous dashboard is still running, or another service is using this port.
749
951
 
750
952
  To fix:
751
- - Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${s}`:`lsof -ti:${s} | xargs kill`}
752
- - Or use a different port: ctx_insight({ port: ${s+1} })`}]})}let E=`http://localhost:${s}`,H=process.platform;try{H==="darwin"?qt(`open "${E}"`,{stdio:"pipe"}):H==="win32"?qt(`start "" "${E}"`,{stdio:"pipe"}):qt(`xdg-open "${E}" 2>/dev/null || sensible-browser "${E}" 2>/dev/null`,{stdio:"pipe"})}catch{}return f.push(`Dashboard running at ${E}`),W("ctx_insight",{content:[{type:"text",text:f.map(z=>`- ${z}`).join(`
953
+ - Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${o}`:`lsof -ti:${o} | xargs kill`}
954
+ - Or use a different port: ctx_insight({ port: ${o+1} })`}]})}let w=`http://localhost:${o}`,I=my(w),O=I.ok?"":` (auto-open failed: ${I.reason}; navigate manually)`;return f.push(`Dashboard running at ${w}${O}`),K("ctx_insight",{content:[{type:"text",text:f.map(C=>`- ${C}`).join(`
753
955
  `)+`
754
956
 
755
- Open: ${E}
756
- PID: ${k.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${k.pid} /F`:`kill ${k.pid}`}`}]})}catch(f){let m=f instanceof Error?f.message:String(f);return W("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${m}`}]})}});PM().catch(t=>{console.error("Fatal:",t),process.exit(1)})});import{stdout as y$,stdin as x$}from"node:process";import*as Fr from"node:readline";var Og=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,Ig=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Ag=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 Tu=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ui=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Zi=/\t{1,1000}/y,Pu=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"),Hi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,a$=new RegExp("\\p{M}+","gu"),c$={limit:1/0,ellipsis:""},Ng=(t,e={},r={})=>{let n=e.limit??1/0,o=e.ellipsis??"",s=e?.ellipsisWidth??(o?Ng(o,c$,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,l=r.emojiWidth??2,d=r.fullWidthWidth??2,p=r.regularWidth??1,f=r.wideWidth??2,m=0,h=0,g=t.length,y=0,_=!1,x=g,k=Math.max(0,n-s),E=0,H=0,z=0,K=0;e:for(;;){if(H>E||h>=g&&h>m){let Le=t.slice(E,H)||t.slice(m,h);y=0;for(let P of Le.replaceAll(a$,"")){let N=P.codePointAt(0)||0;if(Ig(N)?K=d:Ag(N)?K=f:u!==p&&Og(N)?K=u:K=p,z+K>k&&(x=Math.min(x,Math.max(E,m)+y)),z+K>n){_=!0;break e}y+=P.length,z+=K}E=H=0}if(h>=g)break;if(Hi.lastIndex=h,Hi.test(t)){if(y=Hi.lastIndex-h,K=y*p,z+K>k&&(x=Math.min(x,h+Math.floor((k-z)/p))),z+K>n){_=!0;break}z+=K,E=m,H=h,h=m=Hi.lastIndex;continue}if(Tu.lastIndex=h,Tu.test(t)){if(z+i>k&&(x=Math.min(x,h)),z+i>n){_=!0;break}z+=i,E=m,H=h,h=m=Tu.lastIndex;continue}if(Ui.lastIndex=h,Ui.test(t)){if(y=Ui.lastIndex-h,K=y*a,z+K>k&&(x=Math.min(x,h+Math.floor((k-z)/a))),z+K>n){_=!0;break}z+=K,E=m,H=h,h=m=Ui.lastIndex;continue}if(Zi.lastIndex=h,Zi.test(t)){if(y=Zi.lastIndex-h,K=y*c,z+K>k&&(x=Math.min(x,h+Math.floor((k-z)/c))),z+K>n){_=!0;break}z+=K,E=m,H=h,h=m=Zi.lastIndex;continue}if(Pu.lastIndex=h,Pu.test(t)){if(z+l>k&&(x=Math.min(x,h)),z+l>n){_=!0;break}z+=l,E=m,H=h,h=m=Pu.lastIndex;continue}h+=1}return{width:_?k:z,index:_?x:g,truncated:_,ellipsed:_&&n>=s}},zg=Ng;var u$={limit:1/0,ellipsis:"",ellipsisWidth:0},l$=(t,e={})=>zg(t,u$,e).width,st=l$;var qi="\x1B",Fg="\x9B",d$=39,Cu="\x07",Ug="[",p$="]",Zg="m",Ou=`${p$}8;;`,jg=new RegExp(`(?:\\${Ug}(?<code>\\d+)m|\\${Ou}(?<uri>.*)${Cu})`,"y"),Dg=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},Mg=t=>`${qi}${Ug}${t}${Zg}`,Lg=t=>`${qi}${Ou}${t}${Cu}`,Ru=(t,e,r)=>{let n=e[Symbol.iterator](),o=!1,s=!1,i=t.at(-1),a=i===void 0?0:st(i),c=n.next(),u=n.next(),l=0;for(;!c.done;){let d=c.value,p=st(d);a+p<=r?t[t.length-1]+=d:(t.push(d),a=0),(d===qi||d===Fg)&&(o=!0,s=e.startsWith(Ou,l+1)),o?s?d===Cu&&(o=!1,s=!1):d===Zg&&(o=!1):(a+=p,a===r&&!u.done&&(t.push(""),a=0)),c=u,u=n.next(),l+=d.length}i=t.at(-1),!a&&i!==void 0&&i.length&&t.length>1&&(t[t.length-2]+=t.pop())},m$=t=>{let e=t.split(" "),r=e.length;for(;r&&!st(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},f$=(t,e,r={})=>{if(r.trim!==!1&&t.trim()==="")return"";let n="",o,s,i=t.split(" "),a=[""],c=0;for(let d=0;d<i.length;d++){let p=i[d];if(r.trim!==!1){let m=a.at(-1)??"",h=m.trimStart();m.length!==h.length&&(a[a.length-1]=h,c=st(h))}d!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let f=st(p);if(r.hard&&f>e){let m=e-c,h=1+Math.floor((f-m-1)/e);Math.floor((f-1)/e)<h&&a.push(""),Ru(a,p,e),c=st(a.at(-1)??"");continue}if(c+f>e&&c&&f){if(r.wordWrap===!1&&c<e){Ru(a,p,e),c=st(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>e&&r.wordWrap===!1){Ru(a,p,e),c=st(a.at(-1)??"");continue}a[a.length-1]+=p,c+=f}r.trim!==!1&&(a=a.map(d=>m$(d)));let u=a.join(`
757
- `),l=!1;for(let d=0;d<u.length;d++){let p=u[d];if(n+=p,!l)l=p>="\uD800"&&p<="\uDBFF";else continue;if(p===qi||p===Fg){jg.lastIndex=d+1;let m=jg.exec(u)?.groups;if(m?.code!==void 0){let h=Number.parseFloat(m.code);o=h===d$?void 0:h}else m?.uri!==void 0&&(s=m.uri.length===0?void 0:m.uri)}if(u[d+1]===`
758
- `){s&&(n+=Lg(""));let f=o?Dg(o):void 0;o&&f&&(n+=Mg(f))}else p===`
759
- `&&(o&&Dg(o)&&(n+=Mg(o)),s&&(n+=Lg(s)))}return n},h$=/\r?\n/;function oo(t,e,r){return String(t).normalize().split(h$).map(n=>f$(n,e,r)).join(`
760
- `)}var hs=fs(Au(),1);import{ReadStream as qg}from"node:tty";var v$=["up","down","left","right","space","enter","cancel"],b$=["January","February","March","April","May","June","July","August","September","October","November","December"],sr={actions:new Set(v$),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:[...b$],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 Bg(t,e){if(typeof t=="string")return sr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&Bg(r,e))return!0;return!1}var S$=globalThis.process.platform.startsWith("win");function Vg({input:t=x$,output:e=y$,overwrite:r=!0,hideCursor:n=!0}={}){let o=Fr.createInterface({input:t,output:e,prompt:"",tabSize:1});Fr.emitKeypressEvents(t,o),t instanceof qg&&t.isTTY&&t.setRawMode(!0);let s=(i,{name:a,sequence:c})=>{let u=String(i);if(Bg([u,a,c],"cancel")){n&&e.write(hs.cursor.show),process.exit(0);return}if(!r)return;Fr.moveCursor(e,a==="return"?0:-1,a==="return"?-1:0,()=>{Fr.clearLine(e,1,()=>{t.once("keypress",s)})})};return n&&e.write(hs.cursor.hide),t.once("keypress",s),()=>{t.off("keypress",s),n&&e.write(hs.cursor.show),t instanceof qg&&t.isTTY&&!S$&&t.setRawMode(!1),o.terminal=!1,o.close()}}var Nu=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Re,stripVTControlCharacters as SL}from"node:util";import Et from"node:process";var gs=fs(Au(),1);function w$(){return Et.platform!=="win32"?Et.env.TERM!=="linux":!!Et.env.CI||!!Et.env.WT_SESSION||!!Et.env.TERMINUS_SUBLIME||Et.env.ConEmuTask==="{cmd::Cmder}"||Et.env.TERM_PROGRAM==="Terminus-Sublime"||Et.env.TERM_PROGRAM==="vscode"||Et.env.TERM==="xterm-256color"||Et.env.TERM==="alacritty"||Et.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var zu=w$(),$$=()=>process.env.CI==="true";var fe=(t,e)=>zu?t:e,EL=fe("\u25C6","*"),E$=fe("\u25A0","x"),T$=fe("\u25B2","x"),ju=fe("\u25C7","o"),P$=fe("\u250C","T"),Ur=fe("\u2502","|"),R$=fe("\u2514","\u2014"),TL=fe("\u2510","T"),PL=fe("\u2518","\u2014"),RL=fe("\u25CF",">"),CL=fe("\u25CB"," "),OL=fe("\u25FB","[\u2022]"),IL=fe("\u25FC","[+]"),AL=fe("\u25FB","[ ]"),NL=fe("\u25AA","\u2022"),Wg=fe("\u2500","-"),C$=fe("\u256E","+"),O$=fe("\u251C","+"),I$=fe("\u256F","+"),A$=fe("\u2570","+"),zL=fe("\u256D","+"),N$=fe("\u25CF","\u2022"),z$=fe("\u25C6","*"),j$=fe("\u25B2","!"),D$=fe("\u25A0","x");var I={message:(t=[],{symbol:e=Re("gray",Ur),secondarySymbol:r=Re("gray",Ur),output:n=process.stdout,spacing:o=1,withGuide:s}={})=>{let i=[],a=s??sr.withGuide,c=a?r:"",u=a?`${e} `:"",l=a?`${r} `:"";for(let p=0;p<o;p++)i.push(c);let d=Array.isArray(t)?t:t.split(`
761
- `);if(d.length>0){let[p,...f]=d;p.length>0?i.push(`${u}${p}`):i.push(a?e:"");for(let m of f)m.length>0?i.push(`${l}${m}`):i.push(a?r:"")}n.write(`${i.join(`
957
+ Open: ${w}
958
+ PID: ${S.pid} \xB7 Stop: ${process.platform==="win32"?`taskkill /PID ${S.pid} /F`:`kill ${S.pid}`}`}]})}catch(f){let p=f instanceof Error?f.message:String(f);return K("ctx_insight",{content:[{type:"text",text:`Insight setup failed: ${p}`}]})}});MF().catch(t=>{console.error("Fatal:",t),process.exit(1)})});import{stdout as G$,stdin as K$}from"node:process";import*as qr from"node:readline";var Ry=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,Cy=t=>t===12288||t>=65281&&t<=65376||t>=65504&&t<=65510,Oy=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 sl=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,sa=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,oa=/\t{1,1000}/y,ol=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"),ia=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,j$=new RegExp("\\p{M}+","gu"),z$={limit:1/0,ellipsis:""},Iy=(t,e={},r={})=>{let n=e.limit??1/0,s=e.ellipsis??"",o=e?.ellipsisWidth??(s?Iy(s,z$,r).width:0),i=r.ansiWidth??0,a=r.controlWidth??0,c=r.tabWidth??8,u=r.ambiguousWidth??1,d=r.emojiWidth??2,l=r.fullWidthWidth??2,m=r.regularWidth??1,f=r.wideWidth??2,p=0,h=0,g=t.length,y=0,_=!1,x=g,S=Math.max(0,n-o),w=0,I=0,O=0,C=0;e:for(;;){if(I>w||h>=g&&h>p){let F=t.slice(w,I)||t.slice(p,h);y=0;for(let T of F.replaceAll(j$,"")){let R=T.codePointAt(0)||0;if(Cy(R)?C=l:Oy(R)?C=f:u!==m&&Ry(R)?C=u:C=m,O+C>S&&(x=Math.min(x,Math.max(w,p)+y)),O+C>n){_=!0;break e}y+=T.length,O+=C}w=I=0}if(h>=g)break;if(ia.lastIndex=h,ia.test(t)){if(y=ia.lastIndex-h,C=y*m,O+C>S&&(x=Math.min(x,h+Math.floor((S-O)/m))),O+C>n){_=!0;break}O+=C,w=p,I=h,h=p=ia.lastIndex;continue}if(sl.lastIndex=h,sl.test(t)){if(O+i>S&&(x=Math.min(x,h)),O+i>n){_=!0;break}O+=i,w=p,I=h,h=p=sl.lastIndex;continue}if(sa.lastIndex=h,sa.test(t)){if(y=sa.lastIndex-h,C=y*a,O+C>S&&(x=Math.min(x,h+Math.floor((S-O)/a))),O+C>n){_=!0;break}O+=C,w=p,I=h,h=p=sa.lastIndex;continue}if(oa.lastIndex=h,oa.test(t)){if(y=oa.lastIndex-h,C=y*c,O+C>S&&(x=Math.min(x,h+Math.floor((S-O)/c))),O+C>n){_=!0;break}O+=C,w=p,I=h,h=p=oa.lastIndex;continue}if(ol.lastIndex=h,ol.test(t)){if(O+d>S&&(x=Math.min(x,h)),O+d>n){_=!0;break}O+=d,w=p,I=h,h=p=ol.lastIndex;continue}h+=1}return{width:_?S:O,index:_?x:g,truncated:_,ellipsed:_&&n>=o}},Ay=Iy;var L$={limit:1/0,ellipsis:"",ellipsisWidth:0},F$=(t,e={})=>Ay(t,L$,e).width,ut=F$;var aa="\x1B",zy="\x9B",U$=39,al="\x07",Ly="[",H$="]",Fy="m",cl=`${H$}8;;`,Ny=new RegExp(`(?:\\${Ly}(?<code>\\d+)m|\\${cl}(?<uri>.*)${al})`,"y"),Dy=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},My=t=>`${aa}${Ly}${t}${Fy}`,jy=t=>`${aa}${cl}${t}${al}`,il=(t,e,r)=>{let n=e[Symbol.iterator](),s=!1,o=!1,i=t.at(-1),a=i===void 0?0:ut(i),c=n.next(),u=n.next(),d=0;for(;!c.done;){let l=c.value,m=ut(l);a+m<=r?t[t.length-1]+=l:(t.push(l),a=0),(l===aa||l===zy)&&(s=!0,o=e.startsWith(cl,d+1)),s?o?l===al&&(s=!1,o=!1):l===Fy&&(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())},Z$=t=>{let e=t.split(" "),r=e.length;for(;r&&!ut(e[r-1]);)r--;return r===e.length?t:e.slice(0,r).join(" ")+e.slice(r).join("")},B$=(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)??"",h=p.trimStart();p.length!==h.length&&(a[a.length-1]=h,c=ut(h))}l!==0&&(c>=e&&(r.wordWrap===!1||r.trim===!1)&&(a.push(""),c=0),(c||r.trim===!1)&&(a[a.length-1]+=" ",c++));let f=ut(m);if(r.hard&&f>e){let p=e-c,h=1+Math.floor((f-p-1)/e);Math.floor((f-1)/e)<h&&a.push(""),il(a,m,e),c=ut(a.at(-1)??"");continue}if(c+f>e&&c&&f){if(r.wordWrap===!1&&c<e){il(a,m,e),c=ut(a.at(-1)??"");continue}a.push(""),c=0}if(c+f>e&&r.wordWrap===!1){il(a,m,e),c=ut(a.at(-1)??"");continue}a[a.length-1]+=m,c+=f}r.trim!==!1&&(a=a.map(l=>Z$(l)));let u=a.join(`
959
+ `),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===aa||m===zy){Ny.lastIndex=l+1;let p=Ny.exec(u)?.groups;if(p?.code!==void 0){let h=Number.parseFloat(p.code);s=h===U$?void 0:h}else p?.uri!==void 0&&(o=p.uri.length===0?void 0:p.uri)}if(u[l+1]===`
960
+ `){o&&(n+=jy(""));let f=s?Dy(s):void 0;s&&f&&(n+=My(f))}else m===`
961
+ `&&(s&&Dy(s)&&(n+=My(s)),o&&(n+=jy(o)))}return n},q$=/\r?\n/;function fs(t,e,r){return String(t).normalize().split(q$).map(n=>B$(n,e,r)).join(`
962
+ `)}var Eo=wo(ll(),1);import{ReadStream as Hy}from"node:tty";var J$=["up","down","left","right","space","enter","cancel"],Y$=["January","February","March","April","May","June","July","August","September","October","November","December"],hr={actions:new Set(J$),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:[...Y$],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 Zy(t,e){if(typeof t=="string")return hr.aliases.get(t)===e;for(let r of t)if(r!==void 0&&Zy(r,e))return!0;return!1}var X$=globalThis.process.platform.startsWith("win");function By({input:t=K$,output:e=G$,overwrite:r=!0,hideCursor:n=!0}={}){let s=qr.createInterface({input:t,output:e,prompt:"",tabSize:1});qr.emitKeypressEvents(t,s),t instanceof Hy&&t.isTTY&&t.setRawMode(!0);let o=(i,{name:a,sequence:c})=>{let u=String(i);if(Zy([u,a,c],"cancel")){n&&e.write(Eo.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(Eo.cursor.hide),t.once("keypress",o),()=>{t.off("keypress",o),n&&e.write(Eo.cursor.show),t instanceof Hy&&t.isTTY&&!X$&&t.setRawMode(!1),s.terminal=!1,s.close()}}var dl=t=>"columns"in t&&typeof t.columns=="number"?t.columns:80;import{styleText as Ce,stripVTControlCharacters as I2}from"node:util";import Mt from"node:process";var $o=wo(ll(),1);function eT(){return Mt.platform!=="win32"?Mt.env.TERM!=="linux":!!Mt.env.CI||!!Mt.env.WT_SESSION||!!Mt.env.TERMINUS_SUBLIME||Mt.env.ConEmuTask==="{cmd::Cmder}"||Mt.env.TERM_PROGRAM==="Terminus-Sublime"||Mt.env.TERM_PROGRAM==="vscode"||Mt.env.TERM==="xterm-256color"||Mt.env.TERM==="alacritty"||Mt.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var pl=eT(),tT=()=>process.env.CI==="true";var ge=(t,e)=>pl?t:e,M2=ge("\u25C6","*"),rT=ge("\u25A0","x"),nT=ge("\u25B2","x"),ml=ge("\u25C7","o"),sT=ge("\u250C","T"),Vr=ge("\u2502","|"),oT=ge("\u2514","\u2014"),j2=ge("\u2510","T"),z2=ge("\u2518","\u2014"),L2=ge("\u25CF",">"),F2=ge("\u25CB"," "),U2=ge("\u25FB","[\u2022]"),H2=ge("\u25FC","[+]"),Z2=ge("\u25FB","[ ]"),B2=ge("\u25AA","\u2022"),qy=ge("\u2500","-"),iT=ge("\u256E","+"),aT=ge("\u251C","+"),cT=ge("\u256F","+"),uT=ge("\u2570","+"),q2=ge("\u256D","+"),lT=ge("\u25CF","\u2022"),dT=ge("\u25C6","*"),pT=ge("\u25B2","!"),mT=ge("\u25A0","x");var D={message:(t=[],{symbol:e=Ce("gray",Vr),secondarySymbol:r=Ce("gray",Vr),output:n=process.stdout,spacing:s=1,withGuide:o}={})=>{let i=[],a=o??hr.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(`
963
+ `);if(l.length>0){let[m,...f]=l;m.length>0?i.push(`${u}${m}`):i.push(a?e:"");for(let p of f)p.length>0?i.push(`${d}${p}`):i.push(a?r:"")}n.write(`${i.join(`
762
964
  `)}
763
- `)},info:(t,e)=>{I.message(t,{...e,symbol:Re("blue",N$)})},success:(t,e)=>{I.message(t,{...e,symbol:Re("green",z$)})},step:(t,e)=>{I.message(t,{...e,symbol:Re("green",ju)})},warn:(t,e)=>{I.message(t,{...e,symbol:Re("yellow",j$)})},warning:(t,e)=>{I.warn(t,e)},error:(t,e)=>{I.message(t,{...e,symbol:Re("red",D$)})}};var Du=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??sr.withGuide?`${Re("gray",P$)} `:"";r.write(`${n}${t}
764
- `)},Bi=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??sr.withGuide?`${Re("gray",Ur)}
765
- ${Re("gray",R$)} `:"";r.write(`${n}${t}
766
-
767
- `)};var M$=t=>Re("dim",t),L$=(t,e,r)=>{let n={hard:!0,trim:!1},o=oo(t,e,n).split(`
768
- `),s=o.reduce((c,u)=>Math.max(st(u),c),0),i=o.map(r).reduce((c,u)=>Math.max(st(u),c),0),a=e-(i-s);return oo(t,a,n)},Mu=(t="",e="",r)=>{let n=r?.output??Et.stdout,o=r?.withGuide??sr.withGuide,s=r?.format??M$,i=["",...L$(t,Nu(n)-6,s).split(`
769
- `).map(s),""],a=st(e),c=Math.max(i.reduce((p,f)=>{let m=st(f);return m>p?m:p},0),a)+2,u=i.map(p=>`${Re("gray",Ur)} ${p}${" ".repeat(c-st(p))}${Re("gray",Ur)}`).join(`
770
- `),l=o?`${Re("gray",Ur)}
771
- `:"",d=o?O$:A$;n.write(`${l}${Re("green",ju)} ${Re("reset",e)} ${Re("gray",Wg.repeat(Math.max(c-a-1,1))+C$)}
965
+ `)},info:(t,e)=>{D.message(t,{...e,symbol:Ce("blue",lT)})},success:(t,e)=>{D.message(t,{...e,symbol:Ce("green",dT)})},step:(t,e)=>{D.message(t,{...e,symbol:Ce("green",ml)})},warn:(t,e)=>{D.message(t,{...e,symbol:Ce("yellow",pT)})},warning:(t,e)=>{D.warn(t,e)},error:(t,e)=>{D.message(t,{...e,symbol:Ce("red",mT)})}};var fl=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??hr.withGuide?`${Ce("gray",sT)} `:"";r.write(`${n}${t}
966
+ `)},ca=(t="",e)=>{let r=e?.output??process.stdout,n=e?.withGuide??hr.withGuide?`${Ce("gray",Vr)}
967
+ ${Ce("gray",oT)} `:"";r.write(`${n}${t}
968
+
969
+ `)};var fT=t=>Ce("dim",t),hT=(t,e,r)=>{let n={hard:!0,trim:!1},s=fs(t,e,n).split(`
970
+ `),o=s.reduce((c,u)=>Math.max(ut(u),c),0),i=s.map(r).reduce((c,u)=>Math.max(ut(u),c),0),a=e-(i-o);return fs(t,a,n)},hl=(t="",e="",r)=>{let n=r?.output??Mt.stdout,s=r?.withGuide??hr.withGuide,o=r?.format??fT,i=["",...hT(t,dl(n)-6,o).split(`
971
+ `).map(o),""],a=ut(e),c=Math.max(i.reduce((m,f)=>{let p=ut(f);return p>m?p:m},0),a)+2,u=i.map(m=>`${Ce("gray",Vr)} ${m}${" ".repeat(c-ut(m))}${Ce("gray",Vr)}`).join(`
972
+ `),d=s?`${Ce("gray",Vr)}
973
+ `:"",l=s?aT:uT;n.write(`${d}${Ce("green",ml)} ${Ce("reset",e)} ${Ce("gray",qy.repeat(Math.max(c-a-1,1))+iT)}
772
974
  ${u}
773
- ${Re("gray",d+Wg.repeat(c+2)+I$)}
774
- `)};var F$=t=>Re("magenta",t),Lu=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:o,frames:s=zu?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=zu?80:120,signal:a,...c}={})=>{let u=$$(),l,d,p=!1,f=!1,m="",h,g=performance.now(),y=Nu(r),_=c?.styleFrame??F$,x=Pe=>{let $t=Pe>1?o??sr.messages.error:n??sr.messages.cancel;f=Pe===1,p&&(De($t,Pe),f&&typeof e=="function"&&e())},k=()=>x(2),E=()=>x(1),H=()=>{process.on("uncaughtExceptionMonitor",k),process.on("unhandledRejection",k),process.on("SIGINT",E),process.on("SIGTERM",E),process.on("exit",x),a&&a.addEventListener("abort",E)},z=()=>{process.removeListener("uncaughtExceptionMonitor",k),process.removeListener("unhandledRejection",k),process.removeListener("SIGINT",E),process.removeListener("SIGTERM",E),process.removeListener("exit",x),a&&a.removeEventListener("abort",E)},K=()=>{if(h===void 0)return;u&&r.write(`
775
- `);let Pe=oo(h,y,{hard:!0,trim:!1}).split(`
776
- `);Pe.length>1&&r.write(gs.cursor.up(Pe.length-1)),r.write(gs.cursor.to(0)),r.write(gs.erase.down())},Le=Pe=>Pe.replace(/\.+$/,""),P=Pe=>{let $t=(performance.now()-Pe)/1e3,vr=Math.floor($t/60),br=Math.floor($t%60);return vr>0?`[${vr}m ${br}s]`:`[${br}s]`},N=c.withGuide??sr.withGuide,ce=(Pe="")=>{p=!0,l=Vg({output:r}),m=Le(Pe),g=performance.now(),N&&r.write(`${Re("gray",Ur)}
777
- `);let $t=0,vr=0;H(),d=setInterval(()=>{if(u&&m===h)return;K(),h=m;let br=_(s[$t]),Fi;if(u)Fi=`${br} ${m}...`;else if(t==="timer")Fi=`${br} ${m} ${P(g)}`;else{let e$=".".repeat(Math.floor(vr)).slice(0,3);Fi=`${br} ${m}${e$}`}let Qw=oo(Fi,y,{hard:!0,trim:!1});r.write(Qw),$t=$t+1<s.length?$t+1:0,vr=vr<4?vr+.125:0},i)},De=(Pe="",$t=0,vr=!1)=>{if(!p)return;p=!1,clearInterval(d),K();let br=$t===0?Re("green",ju):$t===1?Re("red",E$):Re("red",T$);m=Pe??m,vr||(t==="timer"?r.write(`${br} ${m} ${P(g)}
778
- `):r.write(`${br} ${m}
779
- `)),z(),l()};return{start:ce,stop:(Pe="")=>De(Pe,0),message:(Pe="")=>{m=Le(Pe??m)},cancel:(Pe="")=>De(Pe,1),error:(Pe="")=>De(Pe,2),clear:()=>De("",0,!0),get isCancelled(){return f}}},jL={light:fe("\u2500","-"),heavy:fe("\u2501","="),block:fe("\u2588","#")};var DL=`${Re("gray",Ur)} `;var w=fs(Jg(),1);Yi();ca();import{execFileSync as ls,execFile as RM}from"node:child_process";import{readFileSync as Li,writeFileSync as CM,cpSync as Kw,accessSync as Jw,existsSync as wt,rmSync as ds,closeSync as OM,openSync as IM,chmodSync as AM,constants as Yw}from"node:fs";import{request as NM}from"node:https";import{resolve as ve,dirname as Pg,join as dt}from"node:path";import{tmpdir as zM,devNull as jM,homedir as ps}from"node:os";import{fileURLToPath as DM,pathToFileURL as Rg}from"node:url";var MM={"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",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 LM(t,e){try{OM(2),IM(jM,"w")}catch{process.stderr.write=(()=>!0)}let r=MM[t]?.[e];r||process.exit(1);let n=ms();await import(Rg(dt(n,r)).href)}var Lr=process.argv.slice(2);Lr[0]==="doctor"?BM().then(t=>process.exit(t)):Lr[0]==="upgrade"?WM():Lr[0]==="hook"?LM(Lr[1],Lr[2]):Lr[0]==="insight"?VM(Lr[1]?Number(Lr[1]):4747):Lr[0]==="statusline"?GM():Promise.resolve().then(()=>(Gw(),Ww));function yV(t){return t.replace(/\\/g,"/")}var $u=process.platform==="win32";function wu(t,e={}){ls($u?"npm.cmd":"npm",t,{...e,...$u?{shell:!0}:{}})}function FM(t,e={}){let{execSync:r}=Cg("node:child_process");r($u?t.replace(/^npm /,"npm.cmd "):t,{...e,...$u?{shell:!0}:{}})}function UM(t,e=process.platform,r=RM){let n={stdio:"ignore"},o=()=>console.error(`
780
- Could not auto-open browser. Open manually: ${t}`);try{if(e==="darwin")r("open",[t],n);else if(e==="win32")r("cmd",["/c","start","",t],n);else try{r("xdg-open",[t],n)}catch{try{r("sensible-browser",[t],n)}catch{o()}}}catch{o()}}function ZM(){let t=DM(import.meta.url),e=Pg(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?ve(e,".."):e}function HM(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?ve(r,t,...e):ve(ps(),"AppData","Local",t,...e)}return ve(ps(),".cache",t,...e)}function ms(){let t=wr().platform;return t==="opencode"||t==="kilo"?HM(t):ZM()}function Xw(){try{return JSON.parse(Li(ve(ms(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function qM(){return new Promise(t=>{let e=NM("https://registry.npmjs.org/context-mode/latest",{headers:{Connection:"close"}},r=>{let n="";r.on("data",o=>{n+=o}),r.on("end",()=>{try{let o=JSON.parse(n);t(o.version??"unknown")}catch{t("unknown")}})});e.on("error",()=>t("unknown")),e.setTimeout(5e3,()=>{e.destroy(),t("unknown")}),e.end()})}async function BM(){process.stdout.isTTY&&console.clear();let t=wr(),e=await bs(t.platform);Du(w.default.bgMagenta(w.default.white(" context-mode doctor "))),I.info(`Platform: ${w.default.cyan(e.name)}`+w.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let r=0,n=Lu();n.start("Running diagnostics");let o,s;try{o=so(),s=Ji(o)}catch{return n.stop("Diagnostics partial"),I.warn(w.default.yellow("Could not detect runtimes")+w.default.dim(" \u2014 module may be missing, restart session after upgrade")),Bi(w.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),Mu(Ki(o),"Runtimes"),io()?I.success(w.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):I.warn(w.default.yellow("Performance: NORMAL")+" \u2014 Using Node.js (install Bun for 3-5x speed boost)");let i=11,a=(s.length/i*100).toFixed(0);s.length<2?(r++,I.error(w.default.red(`Language coverage: ${s.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+w.default.dim(` \u2014 ${s.join(", ")||"none"}`))):I.info(`Language coverage: ${s.length}/${i} (${a}%)`+w.default.dim(` \u2014 ${s.join(", ")}`)),I.step("Testing server initialization...");try{let{PolyglotExecutor:h}=await Promise.resolve().then(()=>(Wh(),Zk)),y=await new h({runtimes:o}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(y.exitCode===0&&y.stdout.trim()==="ok")I.success(w.default.green("Server test: PASS"));else{r++;let _=y.stderr?.trim()?` (${y.stderr.trim().slice(0,200)})`:"";I.error(w.default.red("Server test: FAIL")+` \u2014 exit ${y.exitCode}${_}`)}}catch(h){let g=h instanceof Error?h.message:String(h);g.includes("Cannot find module")||g.includes("MODULE_NOT_FOUND")?I.warn(w.default.yellow("Server test: SKIP")+w.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,I.error(w.default.red("Server test: FAIL")+` \u2014 ${g}`))}I.step(`Checking ${e.name} hooks configuration...`);let c=ms(),u=e.validateHooks(c);for(let h of u)h.status==="pass"?I.success(w.default.green(`${h.check}: PASS`)+` \u2014 ${h.message}`):I.error(w.default.red(`${h.check}: FAIL`)+` \u2014 ${h.message}`+(h.fix?w.default.dim(`
781
- Run: ${h.fix}`):""));I.step("Checking hook script...");let l=ve(c,"hooks","pretooluse.mjs");try{Jw(l,Yw.R_OK),I.success(w.default.green("Hook script exists: PASS")+w.default.dim(` \u2014 ${l}`))}catch{I.error(w.default.red("Hook script exists: FAIL")+w.default.dim(` \u2014 not found at ${l}`))}I.step(`Checking ${e.name} plugin registration...`);let d=e.checkPluginRegistration();d.status==="pass"?I.success(w.default.green("Plugin enabled: PASS")+w.default.dim(` \u2014 ${d.message}`)):I.warn(w.default.yellow("Plugin enabled: WARN")+` \u2014 ${d.message}`),I.step("Checking FTS5 / SQLite...");try{let h=(await Promise.resolve().then(()=>(ns(),Vk))).loadDatabase(),g=new h(":memory:");g.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),g.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let y=g.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();g.close(),y&&y.content==="hello world"?I.success(w.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(r++,I.error(w.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(h){let g=h instanceof Error?h.message:String(h);g.includes("Cannot find module")||g.includes("MODULE_NOT_FOUND")?I.warn(w.default.yellow("FTS5 / better-sqlite3: SKIP")+w.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,(/Could not locate the bindings file/i.test(g)||/bindings\.node/i.test(g)||/\bbindings\b/i.test(g))&&process.platform==="win32"?I.error(w.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${g}`+w.default.dim(`
975
+ ${Ce("gray",l+qy.repeat(c+2)+cT)}
976
+ `)};var gT=t=>Ce("magenta",t),gl=({indicator:t="dots",onCancel:e,output:r=process.stdout,cancelMessage:n,errorMessage:s,frames:o=pl?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:i=pl?80:120,signal:a,...c}={})=>{let u=tT(),d,l,m=!1,f=!1,p="",h,g=performance.now(),y=dl(r),_=c?.styleFrame??gT,x=fe=>{let gt=fe>1?s??hr.messages.error:n??hr.messages.cancel;f=fe===1,m&&(oe(gt,fe),f&&typeof e=="function"&&e())},S=()=>x(2),w=()=>x(1),I=()=>{process.on("uncaughtExceptionMonitor",S),process.on("unhandledRejection",S),process.on("SIGINT",w),process.on("SIGTERM",w),process.on("exit",x),a&&a.addEventListener("abort",w)},O=()=>{process.removeListener("uncaughtExceptionMonitor",S),process.removeListener("unhandledRejection",S),process.removeListener("SIGINT",w),process.removeListener("SIGTERM",w),process.removeListener("exit",x),a&&a.removeEventListener("abort",w)},C=()=>{if(h===void 0)return;u&&r.write(`
977
+ `);let fe=fs(h,y,{hard:!0,trim:!1}).split(`
978
+ `);fe.length>1&&r.write($o.cursor.up(fe.length-1)),r.write($o.cursor.to(0)),r.write($o.erase.down())},F=fe=>fe.replace(/\.+$/,""),T=fe=>{let gt=(performance.now()-fe)/1e3,Dt=Math.floor(gt/60),yt=Math.floor(gt%60);return Dt>0?`[${Dt}m ${yt}s]`:`[${yt}s]`},R=c.withGuide??hr.withGuide,V=(fe="")=>{m=!0,d=By({output:r}),p=F(fe),g=performance.now(),R&&r.write(`${Ce("gray",Vr)}
979
+ `);let gt=0,Dt=0;I(),l=setInterval(()=>{if(u&&p===h)return;C(),h=p;let yt=_(o[gt]),ms;if(u)ms=`${yt} ${p}...`;else if(t==="timer")ms=`${yt} ${p} ${T(g)}`;else{let rl=".".repeat(Math.floor(Dt)).slice(0,3);ms=`${yt} ${p}${rl}`}let tl=fs(ms,y,{hard:!0,trim:!1});r.write(tl),gt=gt+1<o.length?gt+1:0,Dt=Dt<4?Dt+.125:0},i)},oe=(fe="",gt=0,Dt=!1)=>{if(!m)return;m=!1,clearInterval(l),C();let yt=gt===0?Ce("green",ml):gt===1?Ce("red",rT):Ce("red",nT);p=fe??p,Dt||(t==="timer"?r.write(`${yt} ${p} ${T(g)}
980
+ `):r.write(`${yt} ${p}
981
+ `)),O(),d()};return{start:V,stop:(fe="")=>oe(fe,0),message:(fe="")=>{p=F(fe??p)},cancel:(fe="")=>oe(fe,1),error:(fe="")=>oe(fe,2),clear:()=>oe("",0,!0),get isCancelled(){return f}}},V2={light:ge("\u2500","-"),heavy:ge("\u2501","="),block:ge("\u2588","#")};var W2=`${Ce("gray",Vr)} `;var E=wo(Gy(),1);fa();vl();Wr();Io();import{execFileSync as bo,execFile as jF}from"node:child_process";import{readFileSync as ta,writeFileSync as zF,cpSync as b$,accessSync as k$,existsSync as $t,rmSync as So,closeSync as LF,openSync as FF,chmodSync as UF,constants as w$}from"node:fs";import{request as HF}from"node:https";import{resolve as be,dirname as ky,join as ht}from"node:path";import{tmpdir as ZF,devNull as BF,homedir as S$}from"node:os";import{fileURLToPath as qF,pathToFileURL as wy}from"node:url";function VF(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 WF={"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 GF(t,e){try{LF(2),FF(BF,"w")}catch{process.stderr.write=(()=>!0)}let r=WF[t]?.[e];r||process.exit(1);let n=ko();await import(wy(ht(n,r)).href)}var Zr=process.argv.slice(2);Zr[0]==="doctor"?e2().then(t=>process.exit(t)):Zr[0]==="upgrade"?r2().catch(t=>{let e=t instanceof Error?t.message:String(t);D.error(E.default.red(e)),process.exit(1)}):Zr[0]==="hook"?GF(Zr[1],Zr[2]):Zr[0]==="insight"?t2(Zr[1]?Number(Zr[1]):4747):Zr[0]==="statusline"?n2():Promise.resolve().then(()=>(v$(),x$));function aW(t){return t.replace(/\\/g,"/")}var el=process.platform==="win32";function Qu(t,e={}){bo(el?"npm.cmd":"npm",t,{...e,...el?{shell:!0}:{}})}function KF(t,e={}){let{execSync:r}=Py("node:child_process");r(el?t.replace(/^npm /,"npm.cmd "):t,{...e,...el?{shell:!0}:{}})}function JF(t,e=process.platform,r=jF){let n={stdio:"ignore"},s=()=>console.error(`
982
+ Could not auto-open browser. Open manually: ${t}`),o=VF(t,e),i=!1;for(let{cmd:a,args:c}of o)try{r(a,c,n),i=!0;break}catch{}i||s()}function YF(){let t=qF(import.meta.url),e=ky(t);return e.endsWith("/build")||e.endsWith("\\build")||e.endsWith("/src")||e.endsWith("\\src")?be(e,".."):e}function XF(t){let e=["packages","context-mode@latest","node_modules","context-mode"];if(process.platform==="win32"){let r=process.env.LOCALAPPDATA;return r?be(r,t,...e):be(S$(),"AppData","Local",t,...e)}return be(S$(),".cache",t,...e)}function ko(){let t=gr().platform;return t==="opencode"||t==="kilo"?XF(t):YF()}function E$(){try{return JSON.parse(ta(be(ko(),"package.json"),"utf-8")).version??"unknown"}catch{return"unknown"}}async function QF(){return new Promise(t=>{let e=HF("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 e2(){process.stdout.isTTY&&console.clear();let t=gr(),e=await Oo(t.platform);fl(E.default.bgMagenta(E.default.white(" context-mode doctor "))),D.info(`Platform: ${E.default.cyan(e.name)}`+E.default.dim(` (${t.confidence} confidence \u2014 ${t.reason})`));let r=0,n=gl();n.start("Running diagnostics");let s,o;try{s=gs(),o=ma(s)}catch{return n.stop("Diagnostics partial"),D.warn(E.default.yellow("Could not detect runtimes")+E.default.dim(" \u2014 module may be missing, restart session after upgrade")),ca(E.default.yellow("Doctor could not fully run \u2014 try again after restarting")),1}n.stop("Diagnostics complete"),hl(pa(s),"Runtimes"),ys()?D.success(E.default.green("Performance: FAST")+" \u2014 Bun detected for JS/TS execution"):D.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++,D.error(E.default.red(`Language coverage: ${o.length}/${i} (${a}%)`)+" \u2014 too few runtimes detected"+E.default.dim(` \u2014 ${o.join(", ")||"none"}`))):D.info(`Language coverage: ${o.length}/${i} (${a}%)`+E.default.dim(` \u2014 ${o.join(", ")}`)),D.step("Testing server initialization...");try{let{PolyglotExecutor:h}=await Promise.resolve().then(()=>(jg(),Gw)),y=await new h({runtimes:s}).execute({language:"javascript",code:'console.log("ok");',timeout:5e3});if(y.exitCode===0&&y.stdout.trim()==="ok")D.success(E.default.green("Server test: PASS"));else{r++;let _=y.stderr?.trim()?` (${y.stderr.trim().slice(0,200)})`:"";D.error(E.default.red("Server test: FAIL")+` \u2014 exit ${y.exitCode}${_}`)}}catch(h){let g=h instanceof Error?h.message:String(h);g.includes("Cannot find module")||g.includes("MODULE_NOT_FOUND")?D.warn(E.default.yellow("Server test: SKIP")+E.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,D.error(E.default.red("Server test: FAIL")+` \u2014 ${g}`))}D.step(`Checking ${e.name} hooks configuration...`);let c=ko(),u=e.validateHooks(c);for(let h of u)h.status==="pass"?D.success(E.default.green(`${h.check}: PASS`)+` \u2014 ${h.message}`):h.status==="warn"?D.warn(E.default.yellow(`${h.check}: WARN`)+` \u2014 ${h.message}`+(h.fix?E.default.dim(`
983
+ Run: ${h.fix}`):"")):D.error(E.default.red(`${h.check}: FAIL`)+` \u2014 ${h.message}`+(h.fix?E.default.dim(`
984
+ Run: ${h.fix}`):""));D.step("Checking hook scripts...");let d=ha(e,c);if(d.length===0)D.success(E.default.green("Hook scripts: PASS")+E.default.dim(" \u2014 no direct .mjs script paths to verify"));else for(let h of d){let g=be(c,h);try{k$(g,w$.R_OK),D.success(E.default.green("Hook script exists: PASS")+E.default.dim(` \u2014 ${g}`))}catch{D.error(E.default.red("Hook script exists: FAIL")+E.default.dim(` \u2014 not found at ${g}`))}}D.step(`Checking ${e.name} plugin registration...`);let l=e.checkPluginRegistration();l.status==="pass"?D.success(E.default.green("Plugin enabled: PASS")+E.default.dim(` \u2014 ${l.message}`)):D.warn(E.default.yellow("Plugin enabled: WARN")+` \u2014 ${l.message}`),D.step("Checking FTS5 / SQLite...");try{let h=(await Promise.resolve().then(()=>(go(),Qw))).loadDatabase(),g=new h(":memory:");g.exec("CREATE VIRTUAL TABLE fts_test USING fts5(content)"),g.exec("INSERT INTO fts_test(content) VALUES ('hello world')");let y=g.prepare("SELECT * FROM fts_test WHERE fts_test MATCH 'hello'").get();g.close(),y&&y.content==="hello world"?D.success(E.default.green("FTS5 / SQLite: PASS")+" \u2014 native module works"):(r++,D.error(E.default.red("FTS5 / SQLite: FAIL")+" \u2014 query returned unexpected result"))}catch(h){let g=h instanceof Error?h.message:String(h);g.includes("Cannot find module")||g.includes("MODULE_NOT_FOUND")?D.warn(E.default.yellow("FTS5 / better-sqlite3: SKIP")+E.default.dim(" \u2014 module not available (restart session after upgrade)")):(r++,(/Could not locate the bindings file/i.test(g)||/bindings\.node/i.test(g)||/\bbindings\b/i.test(g))&&process.platform==="win32"?D.error(E.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${g}`+E.default.dim(`
782
985
  Root cause: prebuild-install was likely not on PATH, so install fell through to node-gyp without an MSVC toolchain (Windows).
783
986
  Try (primary): npm install better-sqlite3 # re-resolves the dep tree and re-links the prebuild-install bin shim to fetch a prebuilt binary
784
- Try (fallback): npm rebuild better-sqlite3`)):I.error(w.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${g}`+w.default.dim(`
785
- Try: npm rebuild better-sqlite3`)))}I.step("Checking versions...");let p=Xw(),f=await qM(),m=e.getInstalledVersion();return f==="unknown"?I.warn(w.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, could not reach npm registry`):p===f?I.success(w.default.green("npm (MCP): PASS")+` \u2014 v${p}`):I.warn(w.default.yellow("npm (MCP): WARN")+` \u2014 local v${p}, latest v${f}`+w.default.dim(`
786
- Run: /context-mode:ctx-upgrade`)),m==="not installed"?I.info(w.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):f!=="unknown"&&m===f?I.success(w.default.green(`${e.name}: PASS`)+` \u2014 v${m}`):f!=="unknown"?I.warn(w.default.yellow(`${e.name}: WARN`)+` \u2014 v${m}, latest v${f}`+w.default.dim(`
787
- Run: /context-mode:ctx-upgrade`)):I.info(`${e.name}: v${m}`+w.default.dim(" \u2014 could not verify against npm registry")),r>0?(Bi(w.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(Bi(s.length>=4?w.default.green("Diagnostics complete!"):w.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function VM(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:o,cpSync:s}=await import("node:fs"),i=ve(ms(),"insight"),a=wr(),u=(await bs(a.platform)).getSessionDir(),l=dt(Pg(u),"content"),d=dt(Pg(u),"insight-cache");wt(dt(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),o(d,{recursive:!0});let p=n(dt(i,"server.mjs")).mtimeMs,f=wt(dt(d,"server.mjs"))?n(dt(d,"server.mjs")).mtimeMs:0;if(p>f&&(console.log("Copying Insight source..."),s(i,d,{recursive:!0,force:!0})),!wt(dt(d,"node_modules"))){console.log("Installing dependencies (first run)...");try{FM("npm install --production=false",{cwd:d,stdio:"inherit",timeout:3e5})}catch{try{ds(dt(d,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!wt(dt(d,"node_modules","vite"))||!wt(dt(d,"node_modules","better-sqlite3")))throw ds(dt(d,"node_modules"),{recursive:!0,force:!0}),new Error("npm install incomplete \u2014 please retry")}console.log("Building dashboard..."),e("npx vite build",{cwd:d,stdio:"pipe",timeout:6e4});let m=`http://localhost:${t}`;console.log(`
987
+ Try (fallback): npm rebuild better-sqlite3`)):D.error(E.default.red("FTS5 / better-sqlite3: FAIL")+` \u2014 ${g}`+E.default.dim(`
988
+ Try: npm rebuild better-sqlite3`)))}D.step("Checking versions...");let m=E$(),f=await QF(),p=e.getInstalledVersion();return f==="unknown"?D.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, could not reach npm registry`):m===f?D.success(E.default.green("npm (MCP): PASS")+` \u2014 v${m}`):D.warn(E.default.yellow("npm (MCP): WARN")+` \u2014 local v${m}, latest v${f}`+E.default.dim(`
989
+ Run: /context-mode:ctx-upgrade`)),p==="not installed"?D.info(E.default.dim(`${e.name}: not installed`)+" \u2014 using standalone MCP mode"):f!=="unknown"&&p===f?D.success(E.default.green(`${e.name}: PASS`)+` \u2014 v${p}`):f!=="unknown"?D.warn(E.default.yellow(`${e.name}: WARN`)+` \u2014 v${p}, latest v${f}`+E.default.dim(`
990
+ Run: /context-mode:ctx-upgrade`)):D.info(`${e.name}: v${p}`+E.default.dim(" \u2014 could not verify against npm registry")),r>0?(ca(E.default.red(`Diagnostics failed \u2014 ${r} critical issue(s) found`)),1):(ca(o.length>=4?E.default.green("Diagnostics complete!"):E.default.yellow("Some checks need attention \u2014 see above for details")),0)}async function t2(t){try{let{execSync:e,spawn:r}=await import("node:child_process"),{statSync:n,mkdirSync:s,cpSync:o}=await import("node:fs"),i=be(ko(),"insight"),a=gr(),u=(await Oo(a.platform)).getSessionDir(),d=ht(ky(u),"content"),l=ht(ky(u),"insight-cache");$t(ht(i,"server.mjs"))||(console.error("Error: Insight source not found. Try upgrading context-mode."),process.exit(1)),s(l,{recursive:!0});let m=n(ht(i,"server.mjs")).mtimeMs,f=$t(ht(l,"server.mjs"))?n(ht(l,"server.mjs")).mtimeMs:0;if(m>f&&(console.log("Copying Insight source..."),o(i,l,{recursive:!0,force:!0})),!$t(ht(l,"node_modules"))){console.log("Installing dependencies (first run)...");try{KF("npm install --production=false",{cwd:l,stdio:"inherit",timeout:3e5})}catch{try{So(ht(l,"node_modules"),{recursive:!0,force:!0})}catch{}throw new Error("npm install failed \u2014 please retry")}if(!$t(ht(l,"node_modules","vite"))||!$t(ht(l,"node_modules","better-sqlite3")))throw So(ht(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(`
788
991
  context-mode Insight
789
- ${m}
790
- `);let h=r("node",[dt(d,"server.mjs")],{cwd:d,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:l},stdio:"inherit"});h.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((y,_)=>{let x=g(`http://127.0.0.1:${t}/api/overview`,{timeout:3e3},k=>{y(),k.resume()});x.on("error",_),x.on("timeout",()=>{x.destroy(),_(new Error("timeout"))}),x.end()})}catch{console.error(`
992
+ ${p}
993
+ `);let h=r("node",[ht(l,"server.mjs")],{cwd:l,env:{...process.env,PORT:String(t),INSIGHT_SESSION_DIR:u,INSIGHT_CONTENT_DIR:d},stdio:"inherit"});h.on("error",()=>{}),await new Promise(g=>setTimeout(g,1500));try{let{request:g}=await import("node:http");await new Promise((y,_)=>{let x=g(`http://127.0.0.1:${t}/api/overview`,{timeout:3e3},S=>{y(),S.resume()});x.on("error",_),x.on("timeout",()=>{x.destroy(),_(new Error("timeout"))}),x.end()})}catch{console.error(`
791
994
  Error: Port ${t} appears to be in use. Either a previous dashboard is still running, or another service is using this port.`),console.error(`
792
- To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),h.kill(),process.exit(1)}UM(m),process.on("SIGINT",()=>{h.kill(),process.exit(0)}),process.on("SIGTERM",()=>{h.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
793
- Insight error: ${r}`),process.exit(1)}}async function WM(){process.stdout.isTTY&&console.clear();let t=wr(),e=await bs(t.platform);Du(w.default.bgCyan(w.default.black(" context-mode upgrade "))),I.info(`Platform: ${w.default.cyan(e.name)}`+w.default.dim(` (${t.confidence} confidence)`));let r=ms(),n=[],o=Lu(),s=ve(ps(),".claude","plugins","marketplaces","context-mode");if(wt(dt(s,".git"))){o.start("Syncing marketplace clone");try{ls("git",["-C",s,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(o.stop(w.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),I.info(w.default.dim(` Run manually: git -C "${s}" stash && git pull --ff-only`))):(ls("git",["-C",s,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),ls("git",["-C",s,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),o.stop(w.default.green("Marketplace clone synced")),n.push("Marketplace clone updated to upstream"))}catch(p){let f=p instanceof Error?p.message:String(p);o.stop(w.default.yellow("Marketplace sync skipped")),I.warn(w.default.yellow("git refresh on marketplace failed")+` \u2014 ${f}`),I.info(w.default.dim(" Continuing \u2014 cache dir update will still happen."))}}I.step("Pulling latest from GitHub...");let i=Xw(),a=dt(zM(),`context-mode-upgrade-${Date.now()}`);o.start("Cloning mksglu/context-mode");try{ls("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",a],{stdio:"pipe",timeout:3e4}),o.stop("Downloaded");let p=a,m=JSON.parse(Li(ve(p,"package.json"),"utf-8")).version??"unknown";if(m===i){I.success(w.default.green("Already on latest")+` \u2014 v${i}`),ds(a,{recursive:!0,force:!0});return}else I.info(`Update available: ${w.default.yellow("v"+i)} \u2192 ${w.default.green("v"+m)}`);o.start("Installing dependencies & building"),wu(["install","--no-audit","--no-fund"],{cwd:p,stdio:"pipe",timeout:12e4}),wu(["run","build"],{cwd:p,stdio:"pipe",timeout:6e4}),o.stop("Built successfully"),o.start("Updating files in-place");let g=[...JSON.parse(Li(ve(p,"package.json"),"utf-8")).files||[],"src","package.json"];for(let _ of g)try{ds(ve(r,_),{recursive:!0,force:!0}),Kw(ve(p,_),ve(r,_),{recursive:!0})}catch{}let y={mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}};if(CM(ve(r,".mcp.json"),JSON.stringify(y,null,2)+`
794
- `),o.stop(w.default.green(`Updated in-place to v${m}`)),e.updatePluginRegistry(r,m),I.info(w.default.dim(" Registry synced to "+r)),o.start("Installing production dependencies"),wu(["install","--production","--no-audit","--no-fund"],{cwd:r,stdio:"pipe",timeout:6e4}),o.stop("Dependencies ready"),t.platform!=="opencode"&&t.platform!=="kilo"){o.start("Rebuilding native addons");let _=ve(r,"node_modules","better-sqlite3","build","Release","better_sqlite3.node");if(wt(_))o.stop(w.default.green("Native addons OK")+w.default.dim(" \u2014 binding present")),n.push("better-sqlite3 binding already present (no rebuild needed)");else try{let x=Rg(ve(r,"scripts","heal-better-sqlite3.mjs")).href,{healBetterSqlite3Binding:k}=await import(x),E=k(r);E?.healed?(o.stop(w.default.green("Native addons healed")+w.default.dim(` (${E.reason})`)),n.push(`Healed better-sqlite3 binding via ${E.reason}`)):(o.stop(w.default.yellow("Native addon heal needs manual step")),I.warn(w.default.dim(` Run: cd "${r}" && npm install better-sqlite3`)))}catch(x){let k=x instanceof Error?x.message:String(x);o.stop(w.default.yellow("Native addon heal unavailable")),I.warn(w.default.yellow("better-sqlite3 heal helper missing")+` \u2014 ${k}`+w.default.dim(`
795
- Try manually: cd "${r}" && npm rebuild better-sqlite3`))}}o.start("Updating npm global package");try{wu(["install","-g",r,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),o.stop(w.default.green("npm global updated")),n.push("Updated npm global package")}catch{o.stop(w.default.yellow("npm global update skipped")),I.info(w.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}ds(a,{recursive:!0,force:!0});try{let _=ve(ps(),".claude","plugins","installed_plugins.json");if(wt(_)){let k=JSON.parse(Li(_,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(k))for(let E of k){let H=E.installPath;if(H&&H!==r&&wt(H)){let z=ve(p,"skills");wt(z)&&(Kw(z,ve(H,"skills"),{recursive:!0}),n.push("Synced skills to active install path"))}}}}catch{}n.push(m!==i?`Updated v${i} \u2192 v${m}`:`Reinstalled v${i} from GitHub`),I.success(w.default.green("Plugin reinstalled from GitHub!")+w.default.dim(` \u2014 v${m}`))}catch(p){let f=p instanceof Error?p.message:String(p);o.stop(w.default.red("Update failed")),I.error(w.default.red("GitHub pull failed")+` \u2014 ${f}`),I.info(w.default.dim("Continuing with hooks/settings fix..."));try{ds(a,{recursive:!0,force:!0})}catch{}}I.step(`Backing up ${e.name} settings...`);let c=e.backupSettings();c?.endsWith(".bak")?(I.success(w.default.green("Backup created")+w.default.dim(" -> "+c)),n.push("Backed up settings")):c?I.success(w.default.green("Backup skipped")+w.default.dim(" \u2014 no changes needed")):I.warn(w.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),I.step(`Configuring ${e.name} hooks...`);let u=e.configureAllHooks(r);for(let p of u)I.info(w.default.dim(` ${p}`)),n.push(p);I.success(w.default.green("Hooks configured")+w.default.dim(` \u2014 ${e.name}`)),I.step("Setting hook script permissions...");let l=e.setHookPermissions(r);if(process.platform!=="win32")for(let p of["build/cli.js","cli.bundle.mjs"]){let f=ve(r,p);try{Jw(f,Yw.F_OK),AM(f,493),l.push(f)}catch{}}l.length>0?(I.success(w.default.green("Permissions set")+w.default.dim(` \u2014 ${l.length} hook script(s)`)),n.push(`Set ${l.length} hook scripts as executable`)):I.error(w.default.red("No hook scripts found")+w.default.dim(" \u2014 expected in "+ve(r,"hooks"))),n.length>0?Mu(n.map(p=>w.default.green(" + ")+p).join(`
796
- `),"Changes Applied"):I.info(w.default.dim("No changes were needed."));let d=e.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";I.warn(w.default.yellow("Restart for new MCP tools to take effect.")+w.default.dim(` (${d})`)),I.step("Running doctor to verify..."),console.log();try{let p=ve(r,"cli.bundle.mjs"),f=ve(r,"build","cli.js"),m=wt(p)?p:f;ls("node",[m,"doctor"],{stdio:"inherit",timeout:3e4,cwd:r})}catch{I.warn(w.default.yellow("Doctor had warnings")+w.default.dim(` \u2014 restart your ${e.name} session to pick up the new version`))}}function GM(){let t=[ve(ms(),"bin","statusline.mjs"),ve(ps(),".claude","plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let r=ve(ps(),".claude","plugins","installed_plugins.json");if(wt(r)){let o=JSON.parse(Li(r,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(o))for(let s of o){let i=s?.installPath;typeof i=="string"&&i&&t.push(ve(i,"bin","statusline.mjs"))}}}catch{}let e=t.find(r=>wt(r));e||process.exit(0),import(Rg(e).href).catch(()=>{process.exit(0)})}export{FM as npmExec,wu as npmExecFile,UM as openInBrowser,yV as toUnixPath};
995
+ To fix:`),console.error(` Kill the existing process: ${process.platform==="win32"?`netstat -ano | findstr :${t}`:`lsof -ti:${t} | xargs kill`}`),console.error(` Or use a different port: context-mode insight ${t+1}`),h.kill(),process.exit(1)}JF(p),process.on("SIGINT",()=>{h.kill(),process.exit(0)}),process.on("SIGTERM",()=>{h.kill(),process.exit(0)})}catch(e){let r=e instanceof Error?e.message:String(e);console.error(`
996
+ Insight error: ${r}`),process.exit(1)}}async function r2(){process.stdout.isTTY&&console.clear();let t=gr(),e=await Oo(t.platform);fl(E.default.bgCyan(E.default.black(" context-mode upgrade "))),D.info(`Platform: ${E.default.cyan(e.name)}`+E.default.dim(` (${t.confidence} confidence)`));let r=ko(),n=[],s=gl(),o=be(We(),"plugins","marketplaces","context-mode");if($t(ht(o,".git"))){s.start("Syncing marketplace clone");try{bo("git",["-C",o,"status","--porcelain"],{stdio:"pipe",encoding:"utf-8",timeout:5e3}).trim()?(s.stop(E.default.yellow("Marketplace clone has local edits \u2014 skipping git pull")),D.info(E.default.dim(` Run manually: git -C "${o}" stash && git pull --ff-only`))):(bo("git",["-C",o,"fetch","--tags","origin"],{stdio:"pipe",timeout:3e4}),bo("git",["-C",o,"reset","--hard","origin/HEAD"],{stdio:"pipe",timeout:1e4}),s.stop(E.default.green("Marketplace clone synced")),n.push("Marketplace clone updated to upstream"))}catch(l){let m=l instanceof Error?l.message:String(l);s.stop(E.default.yellow("Marketplace sync skipped")),D.warn(E.default.yellow("git refresh on marketplace failed")+` \u2014 ${m}`),D.info(E.default.dim(" Continuing \u2014 cache dir update will still happen."))}}D.step("Pulling latest from GitHub...");let i=E$(),a=ht(ZF(),`context-mode-upgrade-${Date.now()}`);s.start("Cloning mksglu/context-mode");try{bo("git",["clone","--depth","1","https://github.com/mksglu/context-mode.git",a],{stdio:"pipe",timeout:3e4}),s.stop("Downloaded");let l=a,f=JSON.parse(ta(be(l,"package.json"),"utf-8")).version??"unknown";if(f===i)D.success(E.default.green("Already on latest")+` \u2014 v${i}`),So(a,{recursive:!0,force:!0});else{D.info(`Update available: ${E.default.yellow("v"+i)} \u2192 ${E.default.green("v"+f)}`),s.start("Installing dependencies & building"),Qu(["install","--no-audit","--no-fund"],{cwd:l,stdio:"pipe",timeout:12e4}),Qu(["run","build"],{cwd:l,stdio:"pipe",timeout:6e4}),s.stop("Built successfully"),s.start("Updating files in-place");let h=[...JSON.parse(ta(be(l,"package.json"),"utf-8")).files||[],"src","package.json"];for(let y of h)try{So(be(r,y),{recursive:!0,force:!0}),b$(be(l,y),be(r,y),{recursive:!0})}catch{}let g={mcpServers:{"context-mode":{command:"node",args:["${CLAUDE_PLUGIN_ROOT}/start.mjs"]}}};if(zF(be(r,".mcp.json"),JSON.stringify(g,null,2)+`
997
+ `),s.stop(E.default.green(`Updated in-place to v${f}`)),e.updatePluginRegistry(r,f),D.info(E.default.dim(" Registry synced to "+r)),s.start("Installing production dependencies"),Qu(["install","--production","--no-audit","--no-fund"],{cwd:r,stdio:"pipe",timeout:6e4}),s.stop("Dependencies ready"),t.platform!=="opencode"&&t.platform!=="kilo"){s.start("Verifying native addon ABI");let y=be(r,"node_modules","better-sqlite3","build","Release",`better_sqlite3.abi${process.versions.modules}.node`);try{let _=be(r,"hooks","ensure-deps.mjs");if(!$t(_))throw new Error(`missing ${_}`);await import(`${wy(_).href}?upgrade=${Date.now()}`),$t(y)?(s.stop(E.default.green("Native addons OK")+E.default.dim(" \u2014 ABI cache present")),n.push(`better-sqlite3 ABI ${process.versions.modules} cache ready`)):(s.stop(E.default.yellow("Native addon ABI cache missing")),D.warn(E.default.dim(` Try manually: cd "${r}" && npm rebuild better-sqlite3`)))}catch(_){let x=_ instanceof Error?_.message:String(_);s.stop(E.default.yellow("Native addon ABI bootstrap unavailable")),D.warn(E.default.yellow("better-sqlite3 ABI repair did not run")+` \u2014 ${x}`+E.default.dim(`
998
+ Try manually: cd "${r}" && npm rebuild better-sqlite3`))}}s.start("Updating npm global package");try{Qu(["install","-g",r,"--no-audit","--no-fund"],{stdio:"pipe",timeout:3e4}),s.stop(E.default.green("npm global updated")),n.push("Updated npm global package")}catch{s.stop(E.default.yellow("npm global update skipped")),D.info(E.default.dim(" Could not update global npm \u2014 may need sudo or standalone install"))}So(a,{recursive:!0,force:!0});try{let y=be(We(),"plugins","installed_plugins.json");if($t(y)){let x=JSON.parse(ta(y,"utf-8"))?.plugins?.["context-mode@context-mode"];if(Array.isArray(x))for(let S of x){let w=S.installPath;if(w&&w!==r&&$t(w)){let I=be(l,"skills");$t(I)&&(b$(I,be(w,"skills"),{recursive:!0}),n.push("Synced skills to active install path"))}}}}catch{}n.push(`Updated v${i} \u2192 v${f}`),D.success(E.default.green("Plugin reinstalled from GitHub!")+E.default.dim(` \u2014 v${f}`))}}catch(l){let m=l instanceof Error?l.message:String(l);s.stop(E.default.red("Update failed")),D.error(E.default.red("GitHub pull failed")+` \u2014 ${m}`),D.info(E.default.dim("Continuing with hooks/settings fix..."));try{So(a,{recursive:!0,force:!0})}catch{}}D.step(`Backing up ${e.name} settings...`);let c=e.backupSettings();c?.endsWith(".bak")?(D.success(E.default.green("Backup created")+E.default.dim(" -> "+c)),n.push("Backed up settings")):c?D.success(E.default.green("Backup skipped")+E.default.dim(" \u2014 no changes needed")):D.warn(E.default.yellow("No existing settings to backup")+" \u2014 a new one will be created"),D.step(`Configuring ${e.name} hooks...`);try{let l=e.configureAllHooks(r);for(let m of l)D.info(E.default.dim(` ${m}`)),n.push(m);D.success(E.default.green("Hooks configured")+E.default.dim(` \u2014 ${e.name}`))}catch(l){let m=l instanceof Error?l.message:String(l);throw new Error(`Hook configuration failed: ${m}`)}D.step("Setting hook script permissions...");let u=e.setHookPermissions(r);if(process.platform!=="win32")for(let l of["build/cli.js","cli.bundle.mjs"]){let m=be(r,l);try{k$(m,w$.F_OK),UF(m,493),u.push(m)}catch{}}u.length>0?(D.success(E.default.green("Permissions set")+E.default.dim(` \u2014 ${u.length} hook script(s)`)),n.push(`Set ${u.length} hook scripts as executable`)):D.error(E.default.red("No hook scripts found")+E.default.dim(" \u2014 expected in "+be(r,"hooks"))),n.length>0?hl(n.map(l=>E.default.green(" + ")+l).join(`
999
+ `),"Changes Applied"):D.info(E.default.dim("No changes were needed."));let d=e.name==="Claude Code"?"/reload-plugins, new terminal, or restart session":"new terminal or restart session";D.warn(E.default.yellow("Restart for new MCP tools to take effect.")+E.default.dim(` (${d})`)),D.step("Running doctor to verify..."),console.log();try{let l=be(r,"cli.bundle.mjs"),m=be(r,"build","cli.js"),f=$t(l)?l:m;bo("node",[f,"doctor"],{stdio:"inherit",timeout:3e4,cwd:r})}catch{D.warn(E.default.yellow("Doctor had warnings")+E.default.dim(` \u2014 restart your ${e.name} session to pick up the new version`))}}function n2(){let t=We(),e=[be(ko(),"bin","statusline.mjs"),be(t,"plugins","marketplaces","context-mode","bin","statusline.mjs")];try{let n=be(t,"plugins","installed_plugins.json");if($t(n)){let o=JSON.parse(ta(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(be(a,"bin","statusline.mjs"))}}}catch{}let r=e.find(n=>$t(n));r||process.exit(0),import(wy(r).href).catch(()=>{process.exit(0)})}export{KF as npmExec,Qu as npmExecFile,JF as openInBrowser,aW as toUnixPath};