var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __typeError = (msg) => {
  throw TypeError(msg);
};
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __esm = (fn, res) => function __init() {
  return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
};
var __commonJS = (cb, mod) => function __require() {
  return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);

// src/utils/path.ts
function getVaultPath(app) {
  var _a3;
  const basePath = (_a3 = app.vault.adapter) == null ? void 0 : _a3.basePath;
  return typeof basePath === "string" ? basePath : null;
}
function getEnvValue(key) {
  const hasKey = (name) => Object.prototype.hasOwnProperty.call(process.env, name);
  if (hasKey(key)) {
    return process.env[key];
  }
  if (process.platform !== "win32") {
    return void 0;
  }
  const upper = key.toUpperCase();
  if (hasKey(upper)) {
    return process.env[upper];
  }
  const lower = key.toLowerCase();
  if (hasKey(lower)) {
    return process.env[lower];
  }
  const matchKey = Object.keys(process.env).find((name) => name.toLowerCase() === key.toLowerCase());
  return matchKey ? process.env[matchKey] : void 0;
}
function expandEnvironmentVariables(value) {
  if (!value.includes("%") && !value.includes("$") && !value.includes("!")) {
    return value;
  }
  const isWindows2 = process.platform === "win32";
  let expanded = value;
  expanded = expanded.replace(/%([A-Za-z_][A-Za-z0-9_]*(?:\([A-Za-z0-9_]+\))?[A-Za-z0-9_]*)%/g, (match, name) => {
    const envValue = getEnvValue(name);
    return envValue !== void 0 ? envValue : match;
  });
  if (isWindows2) {
    expanded = expanded.replace(/!([A-Za-z_][A-Za-z0-9_]*)!/g, (match, name) => {
      const envValue = getEnvValue(name);
      return envValue !== void 0 ? envValue : match;
    });
    expanded = expanded.replace(/\$env:([A-Za-z_][A-Za-z0-9_]*)/gi, (match, name) => {
      const envValue = getEnvValue(name);
      return envValue !== void 0 ? envValue : match;
    });
  }
  expanded = expanded.replace(/\$([A-Za-z_][A-Za-z0-9_]*)|\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (match, name1, name2) => {
    const key = name1 != null ? name1 : name2;
    if (!key) return match;
    const envValue = getEnvValue(key);
    return envValue !== void 0 ? envValue : match;
  });
  return expanded;
}
function expandHomePath(p) {
  const expanded = expandEnvironmentVariables(p);
  if (expanded === "~") {
    return os2.homedir();
  }
  if (expanded.startsWith("~/")) {
    return path2.join(os2.homedir(), expanded.slice(2));
  }
  if (expanded.startsWith("~\\")) {
    return path2.join(os2.homedir(), expanded.slice(2));
  }
  return expanded;
}
function stripSurroundingQuotes(value) {
  if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
    return value.slice(1, -1);
  }
  return value;
}
function parsePathEntries(pathValue) {
  if (!pathValue) {
    return [];
  }
  const delimiter = process.platform === "win32" ? ";" : ":";
  return pathValue.split(delimiter).map((segment) => stripSurroundingQuotes(segment.trim())).filter((segment) => {
    if (!segment) return false;
    const upper = segment.toUpperCase();
    return upper !== "$PATH" && upper !== "${PATH}" && upper !== "%PATH%";
  }).map((segment) => translateMsysPath(expandHomePath(segment)));
}
function isNvmBuiltInLatestAlias(alias) {
  return NVM_LATEST_INSTALLED_ALIASES.has(alias);
}
function findMatchingNvmVersion(entries, resolvedAlias) {
  if (isNvmBuiltInLatestAlias(resolvedAlias)) {
    return entries[0];
  }
  const version2 = resolvedAlias.replace(/^v/, "");
  return entries.find((entry) => {
    const entryVersion = entry.slice(1);
    return entryVersion === version2 || entryVersion.startsWith(version2 + ".");
  });
}
function resolveNvmAlias(nvmDir, alias, depth = 0) {
  if (depth > 5) return null;
  if (/^\d/.test(alias) || alias.startsWith("v")) return alias;
  if (isNvmBuiltInLatestAlias(alias)) return alias;
  try {
    const aliasFile = path2.join(nvmDir, "alias", ...alias.split("/"));
    const target = fs2.readFileSync(aliasFile, "utf8").trim();
    if (!target) return null;
    return resolveNvmAlias(nvmDir, target, depth + 1);
  } catch (e2) {
    return null;
  }
}
function resolveNvmDefaultBin(home) {
  const nvmDir = process.env.NVM_DIR || path2.join(home, ".nvm");
  try {
    const alias = fs2.readFileSync(path2.join(nvmDir, "alias", "default"), "utf8").trim();
    if (!alias) return null;
    const resolved = resolveNvmAlias(nvmDir, alias);
    if (!resolved) return null;
    const versionsDir = path2.join(nvmDir, "versions", "node");
    const entries = fs2.readdirSync(versionsDir).filter((entry) => entry.startsWith("v")).sort((a2, b10) => b10.localeCompare(a2, void 0, { numeric: true }));
    const matched = findMatchingNvmVersion(entries, resolved);
    if (matched) {
      const binDir = path2.join(versionsDir, matched, "bin");
      if (fs2.existsSync(binDir)) return binDir;
    }
  } catch (e2) {
  }
  return null;
}
function resolveRealPath(p) {
  var _a3;
  const realpathFn = (_a3 = fs2.realpathSync.native) != null ? _a3 : fs2.realpathSync;
  try {
    return realpathFn(p);
  } catch (e2) {
    const absolute = path2.resolve(p);
    let current = absolute;
    const suffix = [];
    for (; ; ) {
      try {
        if (fs2.existsSync(current)) {
          const resolvedExisting = realpathFn(current);
          return suffix.length > 0 ? path2.join(resolvedExisting, ...suffix.reverse()) : resolvedExisting;
        }
      } catch (e4) {
      }
      const parent = path2.dirname(current);
      if (parent === current) {
        return absolute;
      }
      suffix.push(path2.basename(current));
      current = parent;
    }
  }
}
function translateMsysPath(value) {
  var _a3;
  if (process.platform !== "win32") {
    return value;
  }
  const msysMatch = value.match(/^\/([a-zA-Z])(\/.*)?$/);
  if (msysMatch) {
    const driveLetter = msysMatch[1].toUpperCase();
    const restOfPath = (_a3 = msysMatch[2]) != null ? _a3 : "";
    return `${driveLetter}:${restOfPath.replace(/\//g, "\\")}`;
  }
  return value;
}
function normalizePathBeforeResolution(p) {
  const expanded = expandHomePath(p);
  return translateMsysPath(expanded);
}
function normalizeWindowsPathPrefix(value) {
  if (process.platform !== "win32") {
    return value;
  }
  const normalized = translateMsysPath(value);
  if (normalized.startsWith("\\\\?\\UNC\\")) {
    return `\\\\${normalized.slice("\\\\?\\UNC\\".length)}`;
  }
  if (normalized.startsWith("\\\\?\\")) {
    return normalized.slice("\\\\?\\".length);
  }
  return normalized;
}
function normalizePathForFilesystem(value) {
  if (!value || typeof value !== "string") {
    return "";
  }
  const expanded = normalizePathBeforeResolution(value);
  const normalized = (() => {
    try {
      return process.platform === "win32" ? path2.win32.normalize(expanded) : path2.normalize(expanded);
    } catch (e2) {
      return expanded;
    }
  })();
  return normalizeWindowsPathPrefix(normalized);
}
function normalizePathForComparison(value) {
  if (!value || typeof value !== "string") {
    return "";
  }
  const expanded = normalizePathBeforeResolution(value);
  const normalized = (() => {
    try {
      return process.platform === "win32" ? path2.win32.normalize(expanded) : path2.normalize(expanded);
    } catch (e2) {
      return expanded;
    }
  })();
  const normalizedWithPrefix = normalizeWindowsPathPrefix(normalized).replace(/\\/g, "/").replace(/\/+$/, "");
  return process.platform === "win32" ? normalizedWithPrefix.toLowerCase() : normalizedWithPrefix;
}
function isPathWithinDirectory(candidatePath, directoryPath, relativeBasePath) {
  if (!candidatePath || !directoryPath) {
    return false;
  }
  const directoryReal = normalizePathForComparison(resolveRealPath(directoryPath));
  const normalizedCandidate = normalizePathForFilesystem(candidatePath);
  if (!normalizedCandidate) {
    return false;
  }
  const absCandidate = path2.isAbsolute(normalizedCandidate) ? normalizedCandidate : path2.resolve(relativeBasePath != null ? relativeBasePath : directoryPath, normalizedCandidate);
  const resolvedCandidate = normalizePathForComparison(resolveRealPath(absCandidate));
  return resolvedCandidate === directoryReal || resolvedCandidate.startsWith(directoryReal + "/");
}
function isPathWithinVault(candidatePath, vaultPath) {
  return isPathWithinDirectory(candidatePath, vaultPath, vaultPath);
}
function normalizePathForVault(rawPath, vaultPath) {
  if (!rawPath) return null;
  const normalizedRaw = normalizePathForFilesystem(rawPath);
  if (!normalizedRaw) return null;
  if (vaultPath && isPathWithinVault(normalizedRaw, vaultPath)) {
    const absolute = path2.isAbsolute(normalizedRaw) ? normalizedRaw : path2.resolve(vaultPath, normalizedRaw);
    const relative4 = path2.relative(vaultPath, absolute);
    return relative4 ? relative4.replace(/\\/g, "/") : null;
  }
  return normalizedRaw.replace(/\\/g, "/");
}
var fs2, os2, path2, NVM_LATEST_INSTALLED_ALIASES;
var init_path = __esm({
  "src/utils/path.ts"() {
    fs2 = __toESM(require("fs"));
    os2 = __toESM(require("os"));
    path2 = __toESM(require("path"));
    NVM_LATEST_INSTALLED_ALIASES = /* @__PURE__ */ new Set(["node", "stable"]);
  }
});

// src/utils/env.ts
var env_exports = {};
__export(env_exports, {
  MAX_CONTEXT_LIMIT: () => MAX_CONTEXT_LIMIT,
  MIN_CONTEXT_LIMIT: () => MIN_CONTEXT_LIMIT,
  cliPathRequiresNode: () => cliPathRequiresNode,
  findNodeDirectory: () => findNodeDirectory,
  findNodeExecutable: () => findNodeExecutable,
  formatContextLimit: () => formatContextLimit,
  getEnhancedPath: () => getEnhancedPath,
  getHostnameKey: () => getHostnameKey,
  getMissingNodeError: () => getMissingNodeError,
  parseContextLimit: () => parseContextLimit,
  parseEnvironmentVariables: () => parseEnvironmentVariables
});
function getHomeDir() {
  return process.env.HOME || process.env.USERPROFILE || "";
}
function getAppProvidedCliPaths() {
  if (process.platform === "darwin") {
    const appBundleMatch = process.execPath.match(/^(.+?\.app)\//);
    if (appBundleMatch) {
      return [path4.join(appBundleMatch[1], "Contents", "MacOS")];
    }
    return [path4.dirname(process.execPath)];
  }
  if (process.platform === "win32") {
    return [path4.dirname(process.execPath)];
  }
  return [];
}
function getExtraBinaryPaths() {
  const home = getHomeDir();
  if (isWindows) {
    const paths = [];
    const localAppData = process.env.LOCALAPPDATA;
    const appData = process.env.APPDATA;
    const programFiles = process.env.ProgramFiles || "C:\\Program Files";
    const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
    const programData = process.env.ProgramData || "C:\\ProgramData";
    if (appData) {
      paths.push(path4.join(appData, "npm"));
    }
    if (localAppData) {
      paths.push(path4.join(localAppData, "Programs", "nodejs"));
      paths.push(path4.join(localAppData, "Programs", "node"));
    }
    paths.push(path4.join(programFiles, "nodejs"));
    paths.push(path4.join(programFilesX86, "nodejs"));
    const nvmSymlink = process.env.NVM_SYMLINK;
    if (nvmSymlink) {
      paths.push(nvmSymlink);
    }
    const nvmHome = process.env.NVM_HOME;
    if (nvmHome) {
      paths.push(nvmHome);
    } else if (appData) {
      paths.push(path4.join(appData, "nvm"));
    }
    const voltaHome = process.env.VOLTA_HOME;
    if (voltaHome) {
      paths.push(path4.join(voltaHome, "bin"));
    } else if (home) {
      paths.push(path4.join(home, ".volta", "bin"));
    }
    const fnmMultishell = process.env.FNM_MULTISHELL_PATH;
    if (fnmMultishell) {
      paths.push(fnmMultishell);
    }
    const fnmDir = process.env.FNM_DIR;
    if (fnmDir) {
      paths.push(fnmDir);
    } else if (localAppData) {
      paths.push(path4.join(localAppData, "fnm"));
    }
    const chocolateyInstall = process.env.ChocolateyInstall;
    if (chocolateyInstall) {
      paths.push(path4.join(chocolateyInstall, "bin"));
    } else {
      paths.push(path4.join(programData, "chocolatey", "bin"));
    }
    const scoopDir = process.env.SCOOP;
    if (scoopDir) {
      paths.push(path4.join(scoopDir, "shims"));
      paths.push(path4.join(scoopDir, "apps", "nodejs", "current", "bin"));
      paths.push(path4.join(scoopDir, "apps", "nodejs", "current"));
    } else if (home) {
      paths.push(path4.join(home, "scoop", "shims"));
      paths.push(path4.join(home, "scoop", "apps", "nodejs", "current", "bin"));
      paths.push(path4.join(home, "scoop", "apps", "nodejs", "current"));
    }
    paths.push(path4.join(programFiles, "Docker", "Docker", "resources", "bin"));
    if (home) {
      paths.push(path4.join(home, ".local", "bin"));
      paths.push(path4.join(home, ".bun", "bin"));
      paths.push(path4.join(home, ".opencode", "bin"));
    }
    paths.push(...getAppProvidedCliPaths());
    return paths;
  } else {
    const paths = [
      "/usr/local/bin",
      "/opt/homebrew/bin",
      // macOS ARM Homebrew
      "/usr/bin",
      "/bin"
    ];
    const voltaHome = process.env.VOLTA_HOME;
    if (voltaHome) {
      paths.push(path4.join(voltaHome, "bin"));
    }
    const asdfRoot = process.env.ASDF_DATA_DIR || process.env.ASDF_DIR;
    if (asdfRoot) {
      paths.push(path4.join(asdfRoot, "shims"));
      paths.push(path4.join(asdfRoot, "bin"));
    }
    const fnmMultishell = process.env.FNM_MULTISHELL_PATH;
    if (fnmMultishell) {
      paths.push(fnmMultishell);
    }
    const fnmDir = process.env.FNM_DIR;
    if (fnmDir) {
      paths.push(fnmDir);
    }
    if (home) {
      paths.push(path4.join(home, ".local", "bin"));
      paths.push(path4.join(home, ".bun", "bin"));
      paths.push(path4.join(home, ".opencode", "bin"));
      paths.push(path4.join(home, ".docker", "bin"));
      paths.push(path4.join(home, ".volta", "bin"));
      paths.push(path4.join(home, ".asdf", "shims"));
      paths.push(path4.join(home, ".asdf", "bin"));
      paths.push(path4.join(home, ".fnm"));
      const nvmBin = process.env.NVM_BIN;
      if (nvmBin) {
        paths.push(nvmBin);
      } else {
        const nvmDefault = resolveNvmDefaultBin(home);
        if (nvmDefault) {
          paths.push(nvmDefault);
        }
      }
    }
    paths.push(...getAppProvidedCliPaths());
    return paths;
  }
}
function findNodeDirectory(additionalPaths) {
  const searchPaths = getExtraBinaryPaths();
  const currentPath = process.env.PATH || "";
  const pathDirs = parsePathEntries(currentPath);
  const additionalDirs = additionalPaths ? parsePathEntries(additionalPaths) : [];
  const allPaths = [...additionalDirs, ...searchPaths, ...pathDirs];
  for (const dir of allPaths) {
    if (!dir) continue;
    try {
      const nodePath2 = path4.join(dir, NODE_EXECUTABLE);
      if (fs4.existsSync(nodePath2)) {
        const stat = fs4.statSync(nodePath2);
        if (stat.isFile()) {
          return dir;
        }
      }
    } catch (e2) {
    }
  }
  return null;
}
function findNodeExecutable(additionalPaths) {
  const nodeDir = findNodeDirectory(additionalPaths);
  if (nodeDir) {
    return path4.join(nodeDir, NODE_EXECUTABLE);
  }
  return null;
}
function cliPathRequiresNode(cliPath) {
  const jsExtensions = [".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx"];
  const lower = cliPath.toLowerCase();
  if (jsExtensions.some((ext) => lower.endsWith(ext))) {
    return true;
  }
  try {
    if (!fs4.existsSync(cliPath)) {
      return false;
    }
    const stat = fs4.statSync(cliPath);
    if (!stat.isFile()) {
      return false;
    }
    let fd2 = null;
    try {
      fd2 = fs4.openSync(cliPath, "r");
      const buffer = Buffer.alloc(200);
      const bytesRead = fs4.readSync(fd2, buffer, 0, buffer.length, 0);
      const header = buffer.slice(0, bytesRead).toString("utf8");
      return header.startsWith("#!") && header.toLowerCase().includes("node");
    } finally {
      if (fd2 !== null) {
        try {
          fs4.closeSync(fd2);
        } catch (e2) {
        }
      }
    }
  } catch (e2) {
    return false;
  }
}
function getMissingNodeError(cliPath, enhancedPath) {
  if (!cliPathRequiresNode(cliPath)) {
    return null;
  }
  const nodePath2 = findNodeExecutable(enhancedPath);
  if (nodePath2) {
    return null;
  }
  return "Claude Code CLI requires Node.js, but Node was not found on PATH. Install Node.js or use the native Claude Code binary, then restart Obsidian.";
}
function getEnhancedPath(additionalPaths, cliPath) {
  const extraPaths = getExtraBinaryPaths().filter((p) => p);
  const currentPath = process.env.PATH || "";
  const segments = [];
  if (additionalPaths) {
    segments.push(...parsePathEntries(additionalPaths));
  }
  let cliDirHasNode = false;
  if (cliPath) {
    try {
      const cliDir = path4.dirname(cliPath);
      const nodeInCliDir = path4.join(cliDir, NODE_EXECUTABLE);
      if (fs4.existsSync(nodeInCliDir)) {
        const stat = fs4.statSync(nodeInCliDir);
        if (stat.isFile()) {
          segments.push(cliDir);
          cliDirHasNode = true;
        }
      }
    } catch (e2) {
    }
  }
  if (cliPath && cliPathRequiresNode(cliPath) && !cliDirHasNode) {
    const nodeDir = findNodeDirectory();
    if (nodeDir) {
      segments.push(nodeDir);
    }
  }
  segments.push(...extraPaths);
  if (currentPath) {
    segments.push(...parsePathEntries(currentPath));
  }
  const seen = /* @__PURE__ */ new Set();
  const unique = segments.filter((p) => {
    const normalized = isWindows ? p.toLowerCase() : p;
    if (seen.has(normalized)) return false;
    seen.add(normalized);
    return true;
  });
  return unique.join(PATH_SEPARATOR);
}
function parseEnvironmentVariables(input) {
  const result = {};
  for (const line of input.split(/\r?\n/)) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) continue;
    const normalized = trimmed.startsWith("export ") ? trimmed.slice(7) : trimmed;
    const eqIndex = normalized.indexOf("=");
    if (eqIndex > 0) {
      const key = normalized.substring(0, eqIndex).trim();
      let value = normalized.substring(eqIndex + 1).trim();
      if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
        value = value.slice(1, -1);
      }
      if (key) {
        result[key] = value;
      }
    }
  }
  return result;
}
function getHostnameKey() {
  return os4.hostname();
}
function parseContextLimit(input) {
  var _a3;
  const trimmed = input.trim().toLowerCase().replace(/,/g, "");
  if (!trimmed) return null;
  const match = trimmed.match(/^(\d+(?:\.\d+)?)\s*(k|m)?$/);
  if (!match) return null;
  const value = parseFloat(match[1]);
  const suffix = match[2];
  if (isNaN(value) || value <= 0) return null;
  const MULTIPLIERS = { k: 1e3, m: 1e6 };
  const multiplier = suffix ? (_a3 = MULTIPLIERS[suffix]) != null ? _a3 : 1 : 1;
  const result = Math.round(value * multiplier);
  if (result < MIN_CONTEXT_LIMIT || result > MAX_CONTEXT_LIMIT) return null;
  return result;
}
function formatContextLimit(tokens) {
  if (tokens >= 1e6 && tokens % 1e6 === 0) {
    return `${tokens / 1e6}m`;
  }
  if (tokens >= 1e3 && tokens % 1e3 === 0) {
    return `${tokens / 1e3}k`;
  }
  return tokens.toLocaleString();
}
var fs4, os4, path4, isWindows, PATH_SEPARATOR, NODE_EXECUTABLE, MIN_CONTEXT_LIMIT, MAX_CONTEXT_LIMIT;
var init_env = __esm({
  "src/utils/env.ts"() {
    fs4 = __toESM(require("fs"));
    os4 = __toESM(require("os"));
    path4 = __toESM(require("path"));
    init_path();
    isWindows = process.platform === "win32";
    PATH_SEPARATOR = isWindows ? ";" : ":";
    NODE_EXECUTABLE = isWindows ? "node.exe" : "node";
    MIN_CONTEXT_LIMIT = 1e3;
    MAX_CONTEXT_LIMIT = 1e7;
  }
});

// node_modules/ajv/dist/compile/codegen/code.js
var require_code = __commonJS({
  "node_modules/ajv/dist/compile/codegen/code.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.regexpCode = exports.getEsmExportName = exports.getProperty = exports.safeStringify = exports.stringify = exports.strConcat = exports.addCodeArg = exports.str = exports._ = exports.nil = exports._Code = exports.Name = exports.IDENTIFIER = exports._CodeOrName = void 0;
    var _CodeOrName = class {
    };
    exports._CodeOrName = _CodeOrName;
    exports.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
    var Name = class extends _CodeOrName {
      constructor(s4) {
        super();
        if (!exports.IDENTIFIER.test(s4))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s4;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        return false;
      }
      get names() {
        return { [this.str]: 1 };
      }
    };
    exports.Name = Name;
    var _Code = class extends _CodeOrName {
      constructor(code) {
        super();
        this._items = typeof code === "string" ? [code] : code;
      }
      toString() {
        return this.str;
      }
      emptyStr() {
        if (this._items.length > 1)
          return false;
        const item = this._items[0];
        return item === "" || item === '""';
      }
      get str() {
        var _a3;
        return (_a3 = this._str) !== null && _a3 !== void 0 ? _a3 : this._str = this._items.reduce((s4, c) => `${s4}${c}`, "");
      }
      get names() {
        var _a3;
        return (_a3 = this._names) !== null && _a3 !== void 0 ? _a3 : this._names = this._items.reduce((names, c) => {
          if (c instanceof Name)
            names[c.str] = (names[c.str] || 0) + 1;
          return names;
        }, {});
      }
    };
    exports._Code = _Code;
    exports.nil = new _Code("");
    function _10(strs, ...args) {
      const code = [strs[0]];
      let i2 = 0;
      while (i2 < args.length) {
        addCodeArg(code, args[i2]);
        code.push(strs[++i2]);
      }
      return new _Code(code);
    }
    exports._ = _10;
    var plus = new _Code("+");
    function str(strs, ...args) {
      const expr = [safeStringify(strs[0])];
      let i2 = 0;
      while (i2 < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i2]);
        expr.push(plus, safeStringify(strs[++i2]));
      }
      optimize(expr);
      return new _Code(expr);
    }
    exports.str = str;
    function addCodeArg(code, arg) {
      if (arg instanceof _Code)
        code.push(...arg._items);
      else if (arg instanceof Name)
        code.push(arg);
      else
        code.push(interpolate(arg));
    }
    exports.addCodeArg = addCodeArg;
    function optimize(expr) {
      let i2 = 1;
      while (i2 < expr.length - 1) {
        if (expr[i2] === plus) {
          const res = mergeExprItems(expr[i2 - 1], expr[i2 + 1]);
          if (res !== void 0) {
            expr.splice(i2 - 1, 3, res);
            continue;
          }
          expr[i2++] = "+";
        }
        i2++;
      }
    }
    function mergeExprItems(a2, b10) {
      if (b10 === '""')
        return a2;
      if (a2 === '""')
        return b10;
      if (typeof a2 == "string") {
        if (b10 instanceof Name || a2[a2.length - 1] !== '"')
          return;
        if (typeof b10 != "string")
          return `${a2.slice(0, -1)}${b10}"`;
        if (b10[0] === '"')
          return a2.slice(0, -1) + b10.slice(1);
        return;
      }
      if (typeof b10 == "string" && b10[0] === '"' && !(a2 instanceof Name))
        return `"${a2}${b10.slice(1)}`;
      return;
    }
    function strConcat(c1, c2) {
      return c2.emptyStr() ? c1 : c1.emptyStr() ? c2 : str`${c1}${c2}`;
    }
    exports.strConcat = strConcat;
    function interpolate(x) {
      return typeof x == "number" || typeof x == "boolean" || x === null ? x : safeStringify(Array.isArray(x) ? x.join(",") : x);
    }
    function stringify2(x) {
      return new _Code(safeStringify(x));
    }
    exports.stringify = stringify2;
    function safeStringify(x) {
      return JSON.stringify(x).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
    }
    exports.safeStringify = safeStringify;
    function getProperty(key) {
      return typeof key == "string" && exports.IDENTIFIER.test(key) ? new _Code(`.${key}`) : _10`[${key}]`;
    }
    exports.getProperty = getProperty;
    function getEsmExportName(key) {
      if (typeof key == "string" && exports.IDENTIFIER.test(key)) {
        return new _Code(`${key}`);
      }
      throw new Error(`CodeGen: invalid export name: ${key}, use explicit $id name mapping`);
    }
    exports.getEsmExportName = getEsmExportName;
    function regexpCode(rx) {
      return new _Code(rx.toString());
    }
    exports.regexpCode = regexpCode;
  }
});

// node_modules/ajv/dist/compile/codegen/scope.js
var require_scope = __commonJS({
  "node_modules/ajv/dist/compile/codegen/scope.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.ValueScope = exports.ValueScopeName = exports.Scope = exports.varKinds = exports.UsedValueState = void 0;
    var code_1 = require_code();
    var ValueError = class extends Error {
      constructor(name) {
        super(`CodeGen: "code" for ${name} not defined`);
        this.value = name.value;
      }
    };
    var UsedValueState;
    (function(UsedValueState2) {
      UsedValueState2[UsedValueState2["Started"] = 0] = "Started";
      UsedValueState2[UsedValueState2["Completed"] = 1] = "Completed";
    })(UsedValueState || (exports.UsedValueState = UsedValueState = {}));
    exports.varKinds = {
      const: new code_1.Name("const"),
      let: new code_1.Name("let"),
      var: new code_1.Name("var")
    };
    var Scope2 = class {
      constructor({ prefixes, parent } = {}) {
        this._names = {};
        this._prefixes = prefixes;
        this._parent = parent;
      }
      toName(nameOrPrefix) {
        return nameOrPrefix instanceof code_1.Name ? nameOrPrefix : this.name(nameOrPrefix);
      }
      name(prefix) {
        return new code_1.Name(this._newName(prefix));
      }
      _newName(prefix) {
        const ng = this._names[prefix] || this._nameGroup(prefix);
        return `${prefix}${ng.index++}`;
      }
      _nameGroup(prefix) {
        var _a3, _b2;
        if (((_b2 = (_a3 = this._parent) === null || _a3 === void 0 ? void 0 : _a3._prefixes) === null || _b2 === void 0 ? void 0 : _b2.has(prefix)) || this._prefixes && !this._prefixes.has(prefix)) {
          throw new Error(`CodeGen: prefix "${prefix}" is not allowed in this scope`);
        }
        return this._names[prefix] = { prefix, index: 0 };
      }
    };
    exports.Scope = Scope2;
    var ValueScopeName = class extends code_1.Name {
      constructor(prefix, nameStr) {
        super(nameStr);
        this.prefix = prefix;
      }
      setValue(value, { property, itemIndex }) {
        this.value = value;
        this.scopePath = (0, code_1._)`.${new code_1.Name(property)}[${itemIndex}]`;
      }
    };
    exports.ValueScopeName = ValueScopeName;
    var line = (0, code_1._)`\n`;
    var ValueScope = class extends Scope2 {
      constructor(opts) {
        super(opts);
        this._values = {};
        this._scope = opts.scope;
        this.opts = { ...opts, _n: opts.lines ? line : code_1.nil };
      }
      get() {
        return this._scope;
      }
      name(prefix) {
        return new ValueScopeName(prefix, this._newName(prefix));
      }
      value(nameOrPrefix, value) {
        var _a3;
        if (value.ref === void 0)
          throw new Error("CodeGen: ref must be passed in value");
        const name = this.toName(nameOrPrefix);
        const { prefix } = name;
        const valueKey = (_a3 = value.key) !== null && _a3 !== void 0 ? _a3 : value.ref;
        let vs = this._values[prefix];
        if (vs) {
          const _name = vs.get(valueKey);
          if (_name)
            return _name;
        } else {
          vs = this._values[prefix] = /* @__PURE__ */ new Map();
        }
        vs.set(valueKey, name);
        const s4 = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s4.length;
        s4[itemIndex] = value.ref;
        name.setValue(value, { property: prefix, itemIndex });
        return name;
      }
      getValue(prefix, keyOrRef) {
        const vs = this._values[prefix];
        if (!vs)
          return;
        return vs.get(keyOrRef);
      }
      scopeRefs(scopeName, values = this._values) {
        return this._reduceValues(values, (name) => {
          if (name.scopePath === void 0)
            throw new Error(`CodeGen: name "${name}" has no value`);
          return (0, code_1._)`${scopeName}${name.scopePath}`;
        });
      }
      scopeCode(values = this._values, usedValues, getCode) {
        return this._reduceValues(values, (name) => {
          if (name.value === void 0)
            throw new Error(`CodeGen: name "${name}" has no value`);
          return name.value.code;
        }, usedValues, getCode);
      }
      _reduceValues(values, valueCode, usedValues = {}, getCode) {
        let code = code_1.nil;
        for (const prefix in values) {
          const vs = values[prefix];
          if (!vs)
            continue;
          const nameSet = usedValues[prefix] = usedValues[prefix] || /* @__PURE__ */ new Map();
          vs.forEach((name) => {
            if (nameSet.has(name))
              return;
            nameSet.set(name, UsedValueState.Started);
            let c = valueCode(name);
            if (c) {
              const def = this.opts.es5 ? exports.varKinds.var : exports.varKinds.const;
              code = (0, code_1._)`${code}${def} ${name} = ${c};${this.opts._n}`;
            } else if (c = getCode === null || getCode === void 0 ? void 0 : getCode(name)) {
              code = (0, code_1._)`${code}${c}${this.opts._n}`;
            } else {
              throw new ValueError(name);
            }
            nameSet.set(name, UsedValueState.Completed);
          });
        }
        return code;
      }
    };
    exports.ValueScope = ValueScope;
  }
});

// node_modules/ajv/dist/compile/codegen/index.js
var require_codegen = __commonJS({
  "node_modules/ajv/dist/compile/codegen/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.or = exports.and = exports.not = exports.CodeGen = exports.operators = exports.varKinds = exports.ValueScopeName = exports.ValueScope = exports.Scope = exports.Name = exports.regexpCode = exports.stringify = exports.getProperty = exports.nil = exports.strConcat = exports.str = exports._ = void 0;
    var code_1 = require_code();
    var scope_1 = require_scope();
    var code_2 = require_code();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return code_2._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return code_2.str;
    } });
    Object.defineProperty(exports, "strConcat", { enumerable: true, get: function() {
      return code_2.strConcat;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return code_2.nil;
    } });
    Object.defineProperty(exports, "getProperty", { enumerable: true, get: function() {
      return code_2.getProperty;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return code_2.stringify;
    } });
    Object.defineProperty(exports, "regexpCode", { enumerable: true, get: function() {
      return code_2.regexpCode;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return code_2.Name;
    } });
    var scope_2 = require_scope();
    Object.defineProperty(exports, "Scope", { enumerable: true, get: function() {
      return scope_2.Scope;
    } });
    Object.defineProperty(exports, "ValueScope", { enumerable: true, get: function() {
      return scope_2.ValueScope;
    } });
    Object.defineProperty(exports, "ValueScopeName", { enumerable: true, get: function() {
      return scope_2.ValueScopeName;
    } });
    Object.defineProperty(exports, "varKinds", { enumerable: true, get: function() {
      return scope_2.varKinds;
    } });
    exports.operators = {
      GT: new code_1._Code(">"),
      GTE: new code_1._Code(">="),
      LT: new code_1._Code("<"),
      LTE: new code_1._Code("<="),
      EQ: new code_1._Code("==="),
      NEQ: new code_1._Code("!=="),
      NOT: new code_1._Code("!"),
      OR: new code_1._Code("||"),
      AND: new code_1._Code("&&"),
      ADD: new code_1._Code("+")
    };
    var Node = class {
      optimizeNodes() {
        return this;
      }
      optimizeNames(_names, _constants) {
        return this;
      }
    };
    var Def = class extends Node {
      constructor(varKind, name, rhs) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.rhs = rhs;
      }
      render({ es5, _n }) {
        const varKind = es5 ? scope_1.varKinds.var : this.varKind;
        const rhs = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
        return `${varKind} ${this.name}${rhs};` + _n;
      }
      optimizeNames(names, constants) {
        if (!names[this.name.str])
          return;
        if (this.rhs)
          this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
      }
      get names() {
        return this.rhs instanceof code_1._CodeOrName ? this.rhs.names : {};
      }
    };
    var Assign = class extends Node {
      constructor(lhs, rhs, sideEffects) {
        super();
        this.lhs = lhs;
        this.rhs = rhs;
        this.sideEffects = sideEffects;
      }
      render({ _n }) {
        return `${this.lhs} = ${this.rhs};` + _n;
      }
      optimizeNames(names, constants) {
        if (this.lhs instanceof code_1.Name && !names[this.lhs.str] && !this.sideEffects)
          return;
        this.rhs = optimizeExpr(this.rhs, names, constants);
        return this;
      }
      get names() {
        const names = this.lhs instanceof code_1.Name ? {} : { ...this.lhs.names };
        return addExprNames(names, this.rhs);
      }
    };
    var AssignOp = class extends Assign {
      constructor(lhs, op, rhs, sideEffects) {
        super(lhs, rhs, sideEffects);
        this.op = op;
      }
      render({ _n }) {
        return `${this.lhs} ${this.op}= ${this.rhs};` + _n;
      }
    };
    var Label = class extends Node {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        return `${this.label}:` + _n;
      }
    };
    var Break = class extends Node {
      constructor(label) {
        super();
        this.label = label;
        this.names = {};
      }
      render({ _n }) {
        const label = this.label ? ` ${this.label}` : "";
        return `break${label};` + _n;
      }
    };
    var Throw = class extends Node {
      constructor(error48) {
        super();
        this.error = error48;
      }
      render({ _n }) {
        return `throw ${this.error};` + _n;
      }
      get names() {
        return this.error.names;
      }
    };
    var AnyCode = class extends Node {
      constructor(code) {
        super();
        this.code = code;
      }
      render({ _n }) {
        return `${this.code};` + _n;
      }
      optimizeNodes() {
        return `${this.code}` ? this : void 0;
      }
      optimizeNames(names, constants) {
        this.code = optimizeExpr(this.code, names, constants);
        return this;
      }
      get names() {
        return this.code instanceof code_1._CodeOrName ? this.code.names : {};
      }
    };
    var ParentNode = class extends Node {
      constructor(nodes = []) {
        super();
        this.nodes = nodes;
      }
      render(opts) {
        return this.nodes.reduce((code, n) => code + n.render(opts), "");
      }
      optimizeNodes() {
        const { nodes } = this;
        let i2 = nodes.length;
        while (i2--) {
          const n = nodes[i2].optimizeNodes();
          if (Array.isArray(n))
            nodes.splice(i2, 1, ...n);
          else if (n)
            nodes[i2] = n;
          else
            nodes.splice(i2, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants) {
        const { nodes } = this;
        let i2 = nodes.length;
        while (i2--) {
          const n = nodes[i2];
          if (n.optimizeNames(names, constants))
            continue;
          subtractNames(names, n.names);
          nodes.splice(i2, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      get names() {
        return this.nodes.reduce((names, n) => addNames(names, n.names), {});
      }
    };
    var BlockNode = class extends ParentNode {
      render(opts) {
        return "{" + opts._n + super.render(opts) + "}" + opts._n;
      }
    };
    var Root = class extends ParentNode {
    };
    var Else = class extends BlockNode {
    };
    Else.kind = "else";
    var If = class _If extends BlockNode {
      constructor(condition, nodes) {
        super(nodes);
        this.condition = condition;
      }
      render(opts) {
        let code = `if(${this.condition})` + super.render(opts);
        if (this.else)
          code += "else " + this.else.render(opts);
        return code;
      }
      optimizeNodes() {
        super.optimizeNodes();
        const cond = this.condition;
        if (cond === true)
          return this.nodes;
        let e2 = this.else;
        if (e2) {
          const ns = e2.optimizeNodes();
          e2 = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e2) {
          if (cond === false)
            return e2 instanceof _If ? e2 : e2.nodes;
          if (this.nodes.length)
            return this;
          return new _If(not(cond), e2 instanceof _If ? [e2] : e2.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names, constants) {
        var _a3;
        this.else = (_a3 = this.else) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
        if (!(super.optimizeNames(names, constants) || this.else))
          return;
        this.condition = optimizeExpr(this.condition, names, constants);
        return this;
      }
      get names() {
        const names = super.names;
        addExprNames(names, this.condition);
        if (this.else)
          addNames(names, this.else.names);
        return names;
      }
    };
    If.kind = "if";
    var For = class extends BlockNode {
    };
    For.kind = "for";
    var ForLoop = class extends For {
      constructor(iteration) {
        super();
        this.iteration = iteration;
      }
      render(opts) {
        return `for(${this.iteration})` + super.render(opts);
      }
      optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
          return;
        this.iteration = optimizeExpr(this.iteration, names, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iteration.names);
      }
    };
    var ForRange = class extends For {
      constructor(varKind, name, from, to) {
        super();
        this.varKind = varKind;
        this.name = name;
        this.from = from;
        this.to = to;
      }
      render(opts) {
        const varKind = opts.es5 ? scope_1.varKinds.var : this.varKind;
        const { name, from, to } = this;
        return `for(${varKind} ${name}=${from}; ${name}<${to}; ${name}++)` + super.render(opts);
      }
      get names() {
        const names = addExprNames(super.names, this.from);
        return addExprNames(names, this.to);
      }
    };
    var ForIter = class extends For {
      constructor(loop, varKind, name, iterable) {
        super();
        this.loop = loop;
        this.varKind = varKind;
        this.name = name;
        this.iterable = iterable;
      }
      render(opts) {
        return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render(opts);
      }
      optimizeNames(names, constants) {
        if (!super.optimizeNames(names, constants))
          return;
        this.iterable = optimizeExpr(this.iterable, names, constants);
        return this;
      }
      get names() {
        return addNames(super.names, this.iterable.names);
      }
    };
    var Func = class extends BlockNode {
      constructor(name, args, async) {
        super();
        this.name = name;
        this.args = args;
        this.async = async;
      }
      render(opts) {
        const _async = this.async ? "async " : "";
        return `${_async}function ${this.name}(${this.args})` + super.render(opts);
      }
    };
    Func.kind = "func";
    var Return = class extends ParentNode {
      render(opts) {
        return "return " + super.render(opts);
      }
    };
    Return.kind = "return";
    var Try = class extends BlockNode {
      render(opts) {
        let code = "try" + super.render(opts);
        if (this.catch)
          code += this.catch.render(opts);
        if (this.finally)
          code += this.finally.render(opts);
        return code;
      }
      optimizeNodes() {
        var _a3, _b2;
        super.optimizeNodes();
        (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNodes();
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
        return this;
      }
      optimizeNames(names, constants) {
        var _a3, _b2;
        super.optimizeNames(names, constants);
        (_a3 = this.catch) === null || _a3 === void 0 ? void 0 : _a3.optimizeNames(names, constants);
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNames(names, constants);
        return this;
      }
      get names() {
        const names = super.names;
        if (this.catch)
          addNames(names, this.catch.names);
        if (this.finally)
          addNames(names, this.finally.names);
        return names;
      }
    };
    var Catch = class extends BlockNode {
      constructor(error48) {
        super();
        this.error = error48;
      }
      render(opts) {
        return `catch(${this.error})` + super.render(opts);
      }
    };
    Catch.kind = "catch";
    var Finally = class extends BlockNode {
      render(opts) {
        return "finally" + super.render(opts);
      }
    };
    Finally.kind = "finally";
    var CodeGen = class {
      constructor(extScope, opts = {}) {
        this._values = {};
        this._blockStarts = [];
        this._constants = {};
        this.opts = { ...opts, _n: opts.lines ? "\n" : "" };
        this._extScope = extScope;
        this._scope = new scope_1.Scope({ parent: extScope });
        this._nodes = [new Root()];
      }
      toString() {
        return this._root.render(this.opts);
      }
      // returns unique name in the internal scope
      name(prefix) {
        return this._scope.name(prefix);
      }
      // reserves unique name in the external scope
      scopeName(prefix) {
        return this._extScope.name(prefix);
      }
      // reserves unique name in the external scope and assigns value to it
      scopeValue(prefixOrName, value) {
        const name = this._extScope.value(prefixOrName, value);
        const vs = this._values[name.prefix] || (this._values[name.prefix] = /* @__PURE__ */ new Set());
        vs.add(name);
        return name;
      }
      getScopeValue(prefix, keyOrRef) {
        return this._extScope.getValue(prefix, keyOrRef);
      }
      // return code that assigns values in the external scope to the names that are used internally
      // (same names that were returned by gen.scopeName or gen.scopeValue)
      scopeRefs(scopeName) {
        return this._extScope.scopeRefs(scopeName, this._values);
      }
      scopeCode() {
        return this._extScope.scopeCode(this._values);
      }
      _def(varKind, nameOrPrefix, rhs, constant) {
        const name = this._scope.toName(nameOrPrefix);
        if (rhs !== void 0 && constant)
          this._constants[name.str] = rhs;
        this._leafNode(new Def(varKind, name, rhs));
        return name;
      }
      // `const` declaration (`var` in es5 mode)
      const(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.const, nameOrPrefix, rhs, _constant);
      }
      // `let` declaration with optional assignment (`var` in es5 mode)
      let(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.let, nameOrPrefix, rhs, _constant);
      }
      // `var` declaration with optional assignment
      var(nameOrPrefix, rhs, _constant) {
        return this._def(scope_1.varKinds.var, nameOrPrefix, rhs, _constant);
      }
      // assignment code
      assign(lhs, rhs, sideEffects) {
        return this._leafNode(new Assign(lhs, rhs, sideEffects));
      }
      // `+=` code
      add(lhs, rhs) {
        return this._leafNode(new AssignOp(lhs, exports.operators.ADD, rhs));
      }
      // appends passed SafeExpr to code or executes Block
      code(c) {
        if (typeof c == "function")
          c();
        else if (c !== code_1.nil)
          this._leafNode(new AnyCode(c));
        return this;
      }
      // returns code for object literal for the passed argument list of key-value pairs
      object(...keyValues) {
        const code = ["{"];
        for (const [key, value] of keyValues) {
          if (code.length > 1)
            code.push(",");
          code.push(key);
          if (key !== value || this.opts.es5) {
            code.push(":");
            (0, code_1.addCodeArg)(code, value);
          }
        }
        code.push("}");
        return new code_1._Code(code);
      }
      // `if` clause (or statement if `thenBody` and, optionally, `elseBody` are passed)
      if(condition, thenBody, elseBody) {
        this._blockNode(new If(condition));
        if (thenBody && elseBody) {
          this.code(thenBody).else().code(elseBody).endIf();
        } else if (thenBody) {
          this.code(thenBody).endIf();
        } else if (elseBody) {
          throw new Error('CodeGen: "else" body without "then" body');
        }
        return this;
      }
      // `else if` clause - invalid without `if` or after `else` clauses
      elseIf(condition) {
        return this._elseNode(new If(condition));
      }
      // `else` clause - only valid after `if` or `else if` clauses
      else() {
        return this._elseNode(new Else());
      }
      // end `if` statement (needed if gen.if was used only with condition)
      endIf() {
        return this._endBlockNode(If, Else);
      }
      _for(node, forBody) {
        this._blockNode(node);
        if (forBody)
          this.code(forBody).endFor();
        return this;
      }
      // a generic `for` clause (or statement if `forBody` is passed)
      for(iteration, forBody) {
        return this._for(new ForLoop(iteration), forBody);
      }
      // `for` statement for a range of values
      forRange(nameOrPrefix, from, to, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.let) {
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForRange(varKind, name, from, to), () => forBody(name));
      }
      // `for-of` statement (in es5 mode replace with a normal for loop)
      forOf(nameOrPrefix, iterable, forBody, varKind = scope_1.varKinds.const) {
        const name = this._scope.toName(nameOrPrefix);
        if (this.opts.es5) {
          const arr = iterable instanceof code_1.Name ? iterable : this.var("_arr", iterable);
          return this.forRange("_i", 0, (0, code_1._)`${arr}.length`, (i2) => {
            this.var(name, (0, code_1._)`${arr}[${i2}]`);
            forBody(name);
          });
        }
        return this._for(new ForIter("of", varKind, name, iterable), () => forBody(name));
      }
      // `for-in` statement.
      // With option `ownProperties` replaced with a `for-of` loop for object keys
      forIn(nameOrPrefix, obj, forBody, varKind = this.opts.es5 ? scope_1.varKinds.var : scope_1.varKinds.const) {
        if (this.opts.ownProperties) {
          return this.forOf(nameOrPrefix, (0, code_1._)`Object.keys(${obj})`, forBody);
        }
        const name = this._scope.toName(nameOrPrefix);
        return this._for(new ForIter("in", varKind, name, obj), () => forBody(name));
      }
      // end `for` loop
      endFor() {
        return this._endBlockNode(For);
      }
      // `label` statement
      label(label) {
        return this._leafNode(new Label(label));
      }
      // `break` statement
      break(label) {
        return this._leafNode(new Break(label));
      }
      // `return` statement
      return(value) {
        const node = new Return();
        this._blockNode(node);
        this.code(value);
        if (node.nodes.length !== 1)
          throw new Error('CodeGen: "return" should have one node');
        return this._endBlockNode(Return);
      }
      // `try` statement
      try(tryBody, catchCode, finallyCode) {
        if (!catchCode && !finallyCode)
          throw new Error('CodeGen: "try" without "catch" and "finally"');
        const node = new Try();
        this._blockNode(node);
        this.code(tryBody);
        if (catchCode) {
          const error48 = this.name("e");
          this._currNode = node.catch = new Catch(error48);
          catchCode(error48);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error48) {
        return this._leafNode(new Throw(error48));
      }
      // start self-balancing block
      block(body, nodeCount) {
        this._blockStarts.push(this._nodes.length);
        if (body)
          this.code(body).endBlock(nodeCount);
        return this;
      }
      // end the current self-balancing block
      endBlock(nodeCount) {
        const len = this._blockStarts.pop();
        if (len === void 0)
          throw new Error("CodeGen: not in self-balancing block");
        const toClose = this._nodes.length - len;
        if (toClose < 0 || nodeCount !== void 0 && toClose !== nodeCount) {
          throw new Error(`CodeGen: wrong number of nodes: ${toClose} vs ${nodeCount} expected`);
        }
        this._nodes.length = len;
        return this;
      }
      // `function` heading (or definition if funcBody is passed)
      func(name, args = code_1.nil, async, funcBody) {
        this._blockNode(new Func(name, args, async));
        if (funcBody)
          this.code(funcBody).endFunc();
        return this;
      }
      // end function definition
      endFunc() {
        return this._endBlockNode(Func);
      }
      optimize(n = 1) {
        while (n-- > 0) {
          this._root.optimizeNodes();
          this._root.optimizeNames(this._root.names, this._constants);
        }
      }
      _leafNode(node) {
        this._currNode.nodes.push(node);
        return this;
      }
      _blockNode(node) {
        this._currNode.nodes.push(node);
        this._nodes.push(node);
      }
      _endBlockNode(N12, N22) {
        const n = this._currNode;
        if (n instanceof N12 || N22 && n instanceof N22) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N22 ? `${N12.kind}/${N22.kind}` : N12.kind}"`);
      }
      _elseNode(node) {
        const n = this._currNode;
        if (!(n instanceof If)) {
          throw new Error('CodeGen: "else" without "if"');
        }
        this._currNode = n.else = node;
        return this;
      }
      get _root() {
        return this._nodes[0];
      }
      get _currNode() {
        const ns = this._nodes;
        return ns[ns.length - 1];
      }
      set _currNode(node) {
        const ns = this._nodes;
        ns[ns.length - 1] = node;
      }
    };
    exports.CodeGen = CodeGen;
    function addNames(names, from) {
      for (const n in from)
        names[n] = (names[n] || 0) + (from[n] || 0);
      return names;
    }
    function addExprNames(names, from) {
      return from instanceof code_1._CodeOrName ? addNames(names, from.names) : names;
    }
    function optimizeExpr(expr, names, constants) {
      if (expr instanceof code_1.Name)
        return replaceName(expr);
      if (!canOptimize(expr))
        return expr;
      return new code_1._Code(expr._items.reduce((items, c) => {
        if (c instanceof code_1.Name)
          c = replaceName(c);
        if (c instanceof code_1._Code)
          items.push(...c._items);
        else
          items.push(c);
        return items;
      }, []));
      function replaceName(n) {
        const c = constants[n.str];
        if (c === void 0 || names[n.str] !== 1)
          return n;
        delete names[n.str];
        return c;
      }
      function canOptimize(e2) {
        return e2 instanceof code_1._Code && e2._items.some((c) => c instanceof code_1.Name && names[c.str] === 1 && constants[c.str] !== void 0);
      }
    }
    function subtractNames(names, from) {
      for (const n in from)
        names[n] = (names[n] || 0) - (from[n] || 0);
    }
    function not(x) {
      return typeof x == "boolean" || typeof x == "number" || x === null ? !x : (0, code_1._)`!${par(x)}`;
    }
    exports.not = not;
    var andCode = mappend(exports.operators.AND);
    function and(...args) {
      return args.reduce(andCode);
    }
    exports.and = and;
    var orCode = mappend(exports.operators.OR);
    function or(...args) {
      return args.reduce(orCode);
    }
    exports.or = or;
    function mappend(op) {
      return (x, y9) => x === code_1.nil ? y9 : y9 === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y9)}`;
    }
    function par(x) {
      return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
    }
  }
});

// node_modules/ajv/dist/compile/util.js
var require_util = __commonJS({
  "node_modules/ajv/dist/compile/util.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.checkStrictMode = exports.getErrorPath = exports.Type = exports.useFunc = exports.setEvaluated = exports.evaluatedPropsToName = exports.mergeEvaluated = exports.eachItem = exports.unescapeJsonPointer = exports.escapeJsonPointer = exports.escapeFragment = exports.unescapeFragment = exports.schemaRefOrVal = exports.schemaHasRulesButRef = exports.schemaHasRules = exports.checkUnknownRules = exports.alwaysValidSchema = exports.toHash = void 0;
    var codegen_1 = require_codegen();
    var code_1 = require_code();
    function toHash(arr) {
      const hash2 = {};
      for (const item of arr)
        hash2[item] = true;
      return hash2;
    }
    exports.toHash = toHash;
    function alwaysValidSchema(it, schema) {
      if (typeof schema == "boolean")
        return schema;
      if (Object.keys(schema).length === 0)
        return true;
      checkUnknownRules(it, schema);
      return !schemaHasRules(schema, it.self.RULES.all);
    }
    exports.alwaysValidSchema = alwaysValidSchema;
    function checkUnknownRules(it, schema = it.schema) {
      const { opts, self: self2 } = it;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self2.RULES.keywords;
      for (const key in schema) {
        if (!rules[key])
          checkStrictMode(it, `unknown keyword: "${key}"`);
      }
    }
    exports.checkUnknownRules = checkUnknownRules;
    function schemaHasRules(schema, rules) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (rules[key])
          return true;
      return false;
    }
    exports.schemaHasRules = schemaHasRules;
    function schemaHasRulesButRef(schema, RULES) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (key !== "$ref" && RULES.all[key])
          return true;
      return false;
    }
    exports.schemaHasRulesButRef = schemaHasRulesButRef;
    function schemaRefOrVal({ topSchemaRef, schemaPath }, schema, keyword, $data) {
      if (!$data) {
        if (typeof schema == "number" || typeof schema == "boolean")
          return schema;
        if (typeof schema == "string")
          return (0, codegen_1._)`${schema}`;
      }
      return (0, codegen_1._)`${topSchemaRef}${schemaPath}${(0, codegen_1.getProperty)(keyword)}`;
    }
    exports.schemaRefOrVal = schemaRefOrVal;
    function unescapeFragment(str) {
      return unescapeJsonPointer(decodeURIComponent(str));
    }
    exports.unescapeFragment = unescapeFragment;
    function escapeFragment(str) {
      return encodeURIComponent(escapeJsonPointer(str));
    }
    exports.escapeFragment = escapeFragment;
    function escapeJsonPointer(str) {
      if (typeof str == "number")
        return `${str}`;
      return str.replace(/~/g, "~0").replace(/\//g, "~1");
    }
    exports.escapeJsonPointer = escapeJsonPointer;
    function unescapeJsonPointer(str) {
      return str.replace(/~1/g, "/").replace(/~0/g, "~");
    }
    exports.unescapeJsonPointer = unescapeJsonPointer;
    function eachItem(xs, f2) {
      if (Array.isArray(xs)) {
        for (const x of xs)
          f2(x);
      } else {
        f2(xs);
      }
    }
    exports.eachItem = eachItem;
    function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues3, resultToName }) {
      return (gen, from, to, toName) => {
        const res = to === void 0 ? from : to instanceof codegen_1.Name ? (from instanceof codegen_1.Name ? mergeNames(gen, from, to) : mergeToName(gen, from, to), to) : from instanceof codegen_1.Name ? (mergeToName(gen, to, from), from) : mergeValues3(from, to);
        return toName === codegen_1.Name && !(res instanceof codegen_1.Name) ? resultToName(gen, res) : res;
      };
    }
    exports.mergeEvaluated = {
      props: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => {
          gen.if((0, codegen_1._)`${from} === true`, () => gen.assign(to, true), () => gen.assign(to, (0, codegen_1._)`${to} || {}`).code((0, codegen_1._)`Object.assign(${to}, ${from})`));
        }),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => {
          if (from === true) {
            gen.assign(to, true);
          } else {
            gen.assign(to, (0, codegen_1._)`${to} || {}`);
            setEvaluated(gen, to, from);
          }
        }),
        mergeValues: (from, to) => from === true ? true : { ...from, ...to },
        resultToName: evaluatedPropsToName
      }),
      items: makeMergeEvaluated({
        mergeNames: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true && ${from} !== undefined`, () => gen.assign(to, (0, codegen_1._)`${from} === true ? true : ${to} > ${from} ? ${to} : ${from}`)),
        mergeToName: (gen, from, to) => gen.if((0, codegen_1._)`${to} !== true`, () => gen.assign(to, from === true ? true : (0, codegen_1._)`${to} > ${from} ? ${to} : ${from}`)),
        mergeValues: (from, to) => from === true ? true : Math.max(from, to),
        resultToName: (gen, items) => gen.var("items", items)
      })
    };
    function evaluatedPropsToName(gen, ps) {
      if (ps === true)
        return gen.var("props", true);
      const props = gen.var("props", (0, codegen_1._)`{}`);
      if (ps !== void 0)
        setEvaluated(gen, props, ps);
      return props;
    }
    exports.evaluatedPropsToName = evaluatedPropsToName;
    function setEvaluated(gen, props, ps) {
      Object.keys(ps).forEach((p) => gen.assign((0, codegen_1._)`${props}${(0, codegen_1.getProperty)(p)}`, true));
    }
    exports.setEvaluated = setEvaluated;
    var snippets = {};
    function useFunc(gen, f2) {
      return gen.scopeValue("func", {
        ref: f2,
        code: snippets[f2.code] || (snippets[f2.code] = new code_1._Code(f2.code))
      });
    }
    exports.useFunc = useFunc;
    var Type;
    (function(Type2) {
      Type2[Type2["Num"] = 0] = "Num";
      Type2[Type2["Str"] = 1] = "Str";
    })(Type || (exports.Type = Type = {}));
    function getErrorPath(dataProp, dataPropType, jsPropertySyntax) {
      if (dataProp instanceof codegen_1.Name) {
        const isNumber = dataPropType === Type.Num;
        return jsPropertySyntax ? isNumber ? (0, codegen_1._)`"[" + ${dataProp} + "]"` : (0, codegen_1._)`"['" + ${dataProp} + "']"` : isNumber ? (0, codegen_1._)`"/" + ${dataProp}` : (0, codegen_1._)`"/" + ${dataProp}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
      }
      return jsPropertySyntax ? (0, codegen_1.getProperty)(dataProp).toString() : "/" + escapeJsonPointer(dataProp);
    }
    exports.getErrorPath = getErrorPath;
    function checkStrictMode(it, msg, mode = it.opts.strictSchema) {
      if (!mode)
        return;
      msg = `strict mode: ${msg}`;
      if (mode === true)
        throw new Error(msg);
      it.self.logger.warn(msg);
    }
    exports.checkStrictMode = checkStrictMode;
  }
});

// node_modules/ajv/dist/compile/names.js
var require_names = __commonJS({
  "node_modules/ajv/dist/compile/names.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var names = {
      // validation function arguments
      data: new codegen_1.Name("data"),
      // data passed to validation function
      // args passed from referencing schema
      valCxt: new codegen_1.Name("valCxt"),
      // validation/data context - should not be used directly, it is destructured to the names below
      instancePath: new codegen_1.Name("instancePath"),
      parentData: new codegen_1.Name("parentData"),
      parentDataProperty: new codegen_1.Name("parentDataProperty"),
      rootData: new codegen_1.Name("rootData"),
      // root data - same as the data passed to the first/top validation function
      dynamicAnchors: new codegen_1.Name("dynamicAnchors"),
      // used to support recursiveRef and dynamicRef
      // function scoped variables
      vErrors: new codegen_1.Name("vErrors"),
      // null or array of validation errors
      errors: new codegen_1.Name("errors"),
      // counter of validation errors
      this: new codegen_1.Name("this"),
      // "globals"
      self: new codegen_1.Name("self"),
      scope: new codegen_1.Name("scope"),
      // JTD serialize/parse name for JSON string and position
      json: new codegen_1.Name("json"),
      jsonPos: new codegen_1.Name("jsonPos"),
      jsonLen: new codegen_1.Name("jsonLen"),
      jsonPart: new codegen_1.Name("jsonPart")
    };
    exports.default = names;
  }
});

// node_modules/ajv/dist/compile/errors.js
var require_errors = __commonJS({
  "node_modules/ajv/dist/compile/errors.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.extendErrors = exports.resetErrorsCount = exports.reportExtraError = exports.reportError = exports.keyword$DataError = exports.keywordError = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var names_1 = require_names();
    exports.keywordError = {
      message: ({ keyword }) => (0, codegen_1.str)`must pass "${keyword}" keyword validation`
    };
    exports.keyword$DataError = {
      message: ({ keyword, schemaType }) => schemaType ? (0, codegen_1.str)`"${keyword}" keyword must be ${schemaType} ($data)` : (0, codegen_1.str)`"${keyword}" keyword is invalid ($data)`
    };
    function reportError(cxt, error48 = exports.keywordError, errorPaths, overrideAllErrors) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error48, errorPaths);
      if (overrideAllErrors !== null && overrideAllErrors !== void 0 ? overrideAllErrors : compositeRule || allErrors) {
        addError(gen, errObj);
      } else {
        returnErrors(it, (0, codegen_1._)`[${errObj}]`);
      }
    }
    exports.reportError = reportError;
    function reportExtraError(cxt, error48 = exports.keywordError, errorPaths) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error48, errorPaths);
      addError(gen, errObj);
      if (!(compositeRule || allErrors)) {
        returnErrors(it, names_1.default.vErrors);
      }
    }
    exports.reportExtraError = reportExtraError;
    function resetErrorsCount(gen, errsCount) {
      gen.assign(names_1.default.errors, errsCount);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} !== null`, () => gen.if(errsCount, () => gen.assign((0, codegen_1._)`${names_1.default.vErrors}.length`, errsCount), () => gen.assign(names_1.default.vErrors, null)));
    }
    exports.resetErrorsCount = resetErrorsCount;
    function extendErrors({ gen, keyword, schemaValue, data, errsCount, it }) {
      if (errsCount === void 0)
        throw new Error("ajv implementation error");
      const err = gen.name("err");
      gen.forRange("i", errsCount, names_1.default.errors, (i2) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i2}]`);
        gen.if((0, codegen_1._)`${err}.instancePath === undefined`, () => gen.assign((0, codegen_1._)`${err}.instancePath`, (0, codegen_1.strConcat)(names_1.default.instancePath, it.errorPath)));
        gen.assign((0, codegen_1._)`${err}.schemaPath`, (0, codegen_1.str)`${it.errSchemaPath}/${keyword}`);
        if (it.opts.verbose) {
          gen.assign((0, codegen_1._)`${err}.schema`, schemaValue);
          gen.assign((0, codegen_1._)`${err}.data`, data);
        }
      });
    }
    exports.extendErrors = extendErrors;
    function addError(gen, errObj) {
      const err = gen.const("err", errObj);
      gen.if((0, codegen_1._)`${names_1.default.vErrors} === null`, () => gen.assign(names_1.default.vErrors, (0, codegen_1._)`[${err}]`), (0, codegen_1._)`${names_1.default.vErrors}.push(${err})`);
      gen.code((0, codegen_1._)`${names_1.default.errors}++`);
    }
    function returnErrors(it, errs) {
      const { gen, validateName, schemaEnv } = it;
      if (schemaEnv.$async) {
        gen.throw((0, codegen_1._)`new ${it.ValidationError}(${errs})`);
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, errs);
        gen.return(false);
      }
    }
    var E10 = {
      keyword: new codegen_1.Name("keyword"),
      schemaPath: new codegen_1.Name("schemaPath"),
      // also used in JTD errors
      params: new codegen_1.Name("params"),
      propertyName: new codegen_1.Name("propertyName"),
      message: new codegen_1.Name("message"),
      schema: new codegen_1.Name("schema"),
      parentSchema: new codegen_1.Name("parentSchema")
    };
    function errorObjectCode(cxt, error48, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error48, errorPaths);
    }
    function errorObject(cxt, error48, errorPaths = {}) {
      const { gen, it } = cxt;
      const keyValues = [
        errorInstancePath(it, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error48, keyValues);
      return gen.object(...keyValues);
    }
    function errorInstancePath({ errorPath }, { instancePath }) {
      const instPath = instancePath ? (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(instancePath, util_1.Type.Str)}` : errorPath;
      return [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, instPath)];
    }
    function errorSchemaPath({ keyword, it: { errSchemaPath } }, { schemaPath, parentSchema }) {
      let schPath = parentSchema ? errSchemaPath : (0, codegen_1.str)`${errSchemaPath}/${keyword}`;
      if (schemaPath) {
        schPath = (0, codegen_1.str)`${schPath}${(0, util_1.getErrorPath)(schemaPath, util_1.Type.Str)}`;
      }
      return [E10.schemaPath, schPath];
    }
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword, data, schemaValue, it } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it;
      keyValues.push([E10.keyword, keyword], [E10.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
      if (opts.messages) {
        keyValues.push([E10.message, typeof message == "function" ? message(cxt) : message]);
      }
      if (opts.verbose) {
        keyValues.push([E10.schema, schemaValue], [E10.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
      }
      if (propertyName)
        keyValues.push([E10.propertyName, propertyName]);
    }
  }
});

// node_modules/ajv/dist/compile/validate/boolSchema.js
var require_boolSchema = __commonJS({
  "node_modules/ajv/dist/compile/validate/boolSchema.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.boolOrEmptySchema = exports.topBoolOrEmptySchema = void 0;
    var errors_1 = require_errors();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var boolError = {
      message: "boolean schema is false"
    };
    function topBoolOrEmptySchema(it) {
      const { gen, schema, validateName } = it;
      if (schema === false) {
        falseSchemaError(it, false);
      } else if (typeof schema == "object" && schema.$async === true) {
        gen.return(names_1.default.data);
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, null);
        gen.return(true);
      }
    }
    exports.topBoolOrEmptySchema = topBoolOrEmptySchema;
    function boolOrEmptySchema(it, valid) {
      const { gen, schema } = it;
      if (schema === false) {
        gen.var(valid, false);
        falseSchemaError(it);
      } else {
        gen.var(valid, true);
      }
    }
    exports.boolOrEmptySchema = boolOrEmptySchema;
    function falseSchemaError(it, overrideAllErrors) {
      const { gen, data } = it;
      const cxt = {
        gen,
        keyword: "false schema",
        data,
        schema: false,
        schemaCode: false,
        schemaValue: false,
        params: {},
        it
      };
      (0, errors_1.reportError)(cxt, boolError, void 0, overrideAllErrors);
    }
  }
});

// node_modules/ajv/dist/compile/rules.js
var require_rules = __commonJS({
  "node_modules/ajv/dist/compile/rules.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getRules = exports.isJSONType = void 0;
    var _jsonTypes = ["string", "number", "integer", "boolean", "null", "object", "array"];
    var jsonTypes = new Set(_jsonTypes);
    function isJSONType(x) {
      return typeof x == "string" && jsonTypes.has(x);
    }
    exports.isJSONType = isJSONType;
    function getRules() {
      const groups = {
        number: { type: "number", rules: [] },
        string: { type: "string", rules: [] },
        array: { type: "array", rules: [] },
        object: { type: "object", rules: [] }
      };
      return {
        types: { ...groups, integer: true, boolean: true, null: true },
        rules: [{ rules: [] }, groups.number, groups.string, groups.array, groups.object],
        post: { rules: [] },
        all: {},
        keywords: {}
      };
    }
    exports.getRules = getRules;
  }
});

// node_modules/ajv/dist/compile/validate/applicability.js
var require_applicability = __commonJS({
  "node_modules/ajv/dist/compile/validate/applicability.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.shouldUseRule = exports.shouldUseGroup = exports.schemaHasRulesForType = void 0;
    function schemaHasRulesForType({ schema, self: self2 }, type) {
      const group = self2.RULES.types[type];
      return group && group !== true && shouldUseGroup(schema, group);
    }
    exports.schemaHasRulesForType = schemaHasRulesForType;
    function shouldUseGroup(schema, group) {
      return group.rules.some((rule) => shouldUseRule(schema, rule));
    }
    exports.shouldUseGroup = shouldUseGroup;
    function shouldUseRule(schema, rule) {
      var _a3;
      return schema[rule.keyword] !== void 0 || ((_a3 = rule.definition.implements) === null || _a3 === void 0 ? void 0 : _a3.some((kwd) => schema[kwd] !== void 0));
    }
    exports.shouldUseRule = shouldUseRule;
  }
});

// node_modules/ajv/dist/compile/validate/dataType.js
var require_dataType = __commonJS({
  "node_modules/ajv/dist/compile/validate/dataType.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.reportTypeError = exports.checkDataTypes = exports.checkDataType = exports.coerceAndCheckDataType = exports.getJSONTypes = exports.getSchemaTypes = exports.DataType = void 0;
    var rules_1 = require_rules();
    var applicability_1 = require_applicability();
    var errors_1 = require_errors();
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var DataType;
    (function(DataType2) {
      DataType2[DataType2["Correct"] = 0] = "Correct";
      DataType2[DataType2["Wrong"] = 1] = "Wrong";
    })(DataType || (exports.DataType = DataType = {}));
    function getSchemaTypes(schema) {
      const types = getJSONTypes(schema.type);
      const hasNull = types.includes("null");
      if (hasNull) {
        if (schema.nullable === false)
          throw new Error("type: null contradicts nullable: false");
      } else {
        if (!types.length && schema.nullable !== void 0) {
          throw new Error('"nullable" cannot be used without "type"');
        }
        if (schema.nullable === true)
          types.push("null");
      }
      return types;
    }
    exports.getSchemaTypes = getSchemaTypes;
    function getJSONTypes(ts) {
      const types = Array.isArray(ts) ? ts : ts ? [ts] : [];
      if (types.every(rules_1.isJSONType))
        return types;
      throw new Error("type must be JSONType or JSONType[]: " + types.join(","));
    }
    exports.getJSONTypes = getJSONTypes;
    function coerceAndCheckDataType(it, types) {
      const { gen, data, opts } = it;
      const coerceTo = coerceToTypes(types, opts.coerceTypes);
      const checkTypes = types.length > 0 && !(coerceTo.length === 0 && types.length === 1 && (0, applicability_1.schemaHasRulesForType)(it, types[0]));
      if (checkTypes) {
        const wrongType = checkDataTypes(types, data, opts.strictNumbers, DataType.Wrong);
        gen.if(wrongType, () => {
          if (coerceTo.length)
            coerceData(it, types, coerceTo);
          else
            reportTypeError(it);
        });
      }
      return checkTypes;
    }
    exports.coerceAndCheckDataType = coerceAndCheckDataType;
    var COERCIBLE = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
    function coerceToTypes(types, coerceTypes) {
      return coerceTypes ? types.filter((t2) => COERCIBLE.has(t2) || coerceTypes === "array" && t2 === "array") : [];
    }
    function coerceData(it, types, coerceTo) {
      const { gen, data, opts } = it;
      const dataType = gen.let("dataType", (0, codegen_1._)`typeof ${data}`);
      const coerced = gen.let("coerced", (0, codegen_1._)`undefined`);
      if (opts.coerceTypes === "array") {
        gen.if((0, codegen_1._)`${dataType} == 'object' && Array.isArray(${data}) && ${data}.length == 1`, () => gen.assign(data, (0, codegen_1._)`${data}[0]`).assign(dataType, (0, codegen_1._)`typeof ${data}`).if(checkDataTypes(types, data, opts.strictNumbers), () => gen.assign(coerced, data)));
      }
      gen.if((0, codegen_1._)`${coerced} !== undefined`);
      for (const t2 of coerceTo) {
        if (COERCIBLE.has(t2) || t2 === "array" && opts.coerceTypes === "array") {
          coerceSpecificType(t2);
        }
      }
      gen.else();
      reportTypeError(it);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it, coerced);
      });
      function coerceSpecificType(t2) {
        switch (t2) {
          case "string":
            gen.elseIf((0, codegen_1._)`${dataType} == "number" || ${dataType} == "boolean"`).assign(coerced, (0, codegen_1._)`"" + ${data}`).elseIf((0, codegen_1._)`${data} === null`).assign(coerced, (0, codegen_1._)`""`);
            return;
          case "number":
            gen.elseIf((0, codegen_1._)`${dataType} == "boolean" || ${data} === null
              || (${dataType} == "string" && ${data} && ${data} == +${data})`).assign(coerced, (0, codegen_1._)`+${data}`);
            return;
          case "integer":
            gen.elseIf((0, codegen_1._)`${dataType} === "boolean" || ${data} === null
              || (${dataType} === "string" && ${data} && ${data} == +${data} && !(${data} % 1))`).assign(coerced, (0, codegen_1._)`+${data}`);
            return;
          case "boolean":
            gen.elseIf((0, codegen_1._)`${data} === "false" || ${data} === 0 || ${data} === null`).assign(coerced, false).elseIf((0, codegen_1._)`${data} === "true" || ${data} === 1`).assign(coerced, true);
            return;
          case "null":
            gen.elseIf((0, codegen_1._)`${data} === "" || ${data} === 0 || ${data} === false`);
            gen.assign(coerced, null);
            return;
          case "array":
            gen.elseIf((0, codegen_1._)`${dataType} === "string" || ${dataType} === "number"
              || ${dataType} === "boolean" || ${data} === null`).assign(coerced, (0, codegen_1._)`[${data}]`);
        }
      }
    }
    function assignParentData({ gen, parentData, parentDataProperty }, expr) {
      gen.if((0, codegen_1._)`${parentData} !== undefined`, () => gen.assign((0, codegen_1._)`${parentData}[${parentDataProperty}]`, expr));
    }
    function checkDataType(dataType, data, strictNums, correct = DataType.Correct) {
      const EQ2 = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
      let cond;
      switch (dataType) {
        case "null":
          return (0, codegen_1._)`${data} ${EQ2} null`;
        case "array":
          cond = (0, codegen_1._)`Array.isArray(${data})`;
          break;
        case "object":
          cond = (0, codegen_1._)`${data} && typeof ${data} == "object" && !Array.isArray(${data})`;
          break;
        case "integer":
          cond = numCond((0, codegen_1._)`!(${data} % 1) && !isNaN(${data})`);
          break;
        case "number":
          cond = numCond();
          break;
        default:
          return (0, codegen_1._)`typeof ${data} ${EQ2} ${dataType}`;
      }
      return correct === DataType.Correct ? cond : (0, codegen_1.not)(cond);
      function numCond(_cond = codegen_1.nil) {
        return (0, codegen_1.and)((0, codegen_1._)`typeof ${data} == "number"`, _cond, strictNums ? (0, codegen_1._)`isFinite(${data})` : codegen_1.nil);
      }
    }
    exports.checkDataType = checkDataType;
    function checkDataTypes(dataTypes, data, strictNums, correct) {
      if (dataTypes.length === 1) {
        return checkDataType(dataTypes[0], data, strictNums, correct);
      }
      let cond;
      const types = (0, util_1.toHash)(dataTypes);
      if (types.array && types.object) {
        const notObj = (0, codegen_1._)`typeof ${data} != "object"`;
        cond = types.null ? notObj : (0, codegen_1._)`!${data} || ${notObj}`;
        delete types.null;
        delete types.array;
        delete types.object;
      } else {
        cond = codegen_1.nil;
      }
      if (types.number)
        delete types.integer;
      for (const t2 in types)
        cond = (0, codegen_1.and)(cond, checkDataType(t2, data, strictNums, correct));
      return cond;
    }
    exports.checkDataTypes = checkDataTypes;
    var typeError = {
      message: ({ schema }) => `must be ${schema}`,
      params: ({ schema, schemaValue }) => typeof schema == "string" ? (0, codegen_1._)`{type: ${schema}}` : (0, codegen_1._)`{type: ${schemaValue}}`
    };
    function reportTypeError(it) {
      const cxt = getTypeErrorContext(it);
      (0, errors_1.reportError)(cxt, typeError);
    }
    exports.reportTypeError = reportTypeError;
    function getTypeErrorContext(it) {
      const { gen, data, schema } = it;
      const schemaCode = (0, util_1.schemaRefOrVal)(it, schema, "type");
      return {
        gen,
        keyword: "type",
        data,
        schema: schema.type,
        schemaCode,
        schemaValue: schemaCode,
        parentSchema: schema,
        params: {},
        it
      };
    }
  }
});

// node_modules/ajv/dist/compile/validate/defaults.js
var require_defaults = __commonJS({
  "node_modules/ajv/dist/compile/validate/defaults.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.assignDefaults = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    function assignDefaults(it, ty) {
      const { properties, items } = it.schema;
      if (ty === "object" && properties) {
        for (const key in properties) {
          assignDefault(it, key, properties[key].default);
        }
      } else if (ty === "array" && Array.isArray(items)) {
        items.forEach((sch, i2) => assignDefault(it, i2, sch.default));
      }
    }
    exports.assignDefaults = assignDefaults;
    function assignDefault(it, prop, defaultValue) {
      const { gen, compositeRule, data, opts } = it;
      if (defaultValue === void 0)
        return;
      const childData = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(prop)}`;
      if (compositeRule) {
        (0, util_1.checkStrictMode)(it, `default is ignored for: ${childData}`);
        return;
      }
      let condition = (0, codegen_1._)`${childData} === undefined`;
      if (opts.useDefaults === "empty") {
        condition = (0, codegen_1._)`${condition} || ${childData} === null || ${childData} === ""`;
      }
      gen.if(condition, (0, codegen_1._)`${childData} = ${(0, codegen_1.stringify)(defaultValue)}`);
    }
  }
});

// node_modules/ajv/dist/vocabularies/code.js
var require_code2 = __commonJS({
  "node_modules/ajv/dist/vocabularies/code.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateUnion = exports.validateArray = exports.usePattern = exports.callValidateCode = exports.schemaProperties = exports.allSchemaProperties = exports.noPropertyInData = exports.propertyInData = exports.isOwnProperty = exports.hasPropFunc = exports.reportMissingProp = exports.checkMissingProp = exports.checkReportMissingProp = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var names_1 = require_names();
    var util_2 = require_util();
    function checkReportMissingProp(cxt, prop) {
      const { gen, data, it } = cxt;
      gen.if(noPropertyInData(gen, data, prop, it.opts.ownProperties), () => {
        cxt.setParams({ missingProperty: (0, codegen_1._)`${prop}` }, true);
        cxt.error();
      });
    }
    exports.checkReportMissingProp = checkReportMissingProp;
    function checkMissingProp({ gen, data, it: { opts } }, properties, missing) {
      return (0, codegen_1.or)(...properties.map((prop) => (0, codegen_1.and)(noPropertyInData(gen, data, prop, opts.ownProperties), (0, codegen_1._)`${missing} = ${prop}`)));
    }
    exports.checkMissingProp = checkMissingProp;
    function reportMissingProp(cxt, missing) {
      cxt.setParams({ missingProperty: missing }, true);
      cxt.error();
    }
    exports.reportMissingProp = reportMissingProp;
    function hasPropFunc(gen) {
      return gen.scopeValue("func", {
        // eslint-disable-next-line @typescript-eslint/unbound-method
        ref: Object.prototype.hasOwnProperty,
        code: (0, codegen_1._)`Object.prototype.hasOwnProperty`
      });
    }
    exports.hasPropFunc = hasPropFunc;
    function isOwnProperty(gen, data, property) {
      return (0, codegen_1._)`${hasPropFunc(gen)}.call(${data}, ${property})`;
    }
    exports.isOwnProperty = isOwnProperty;
    function propertyInData(gen, data, property, ownProperties) {
      const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} !== undefined`;
      return ownProperties ? (0, codegen_1._)`${cond} && ${isOwnProperty(gen, data, property)}` : cond;
    }
    exports.propertyInData = propertyInData;
    function noPropertyInData(gen, data, property, ownProperties) {
      const cond = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(property)} === undefined`;
      return ownProperties ? (0, codegen_1.or)(cond, (0, codegen_1.not)(isOwnProperty(gen, data, property))) : cond;
    }
    exports.noPropertyInData = noPropertyInData;
    function allSchemaProperties(schemaMap) {
      return schemaMap ? Object.keys(schemaMap).filter((p) => p !== "__proto__") : [];
    }
    exports.allSchemaProperties = allSchemaProperties;
    function schemaProperties(it, schemaMap) {
      return allSchemaProperties(schemaMap).filter((p) => !(0, util_1.alwaysValidSchema)(it, schemaMap[p]));
    }
    exports.schemaProperties = schemaProperties;
    function callValidateCode({ schemaCode, data, it: { gen, topSchemaRef, schemaPath, errorPath }, it }, func, context, passSchema) {
      const dataAndSchema = passSchema ? (0, codegen_1._)`${schemaCode}, ${data}, ${topSchemaRef}${schemaPath}` : data;
      const valCxt = [
        [names_1.default.instancePath, (0, codegen_1.strConcat)(names_1.default.instancePath, errorPath)],
        [names_1.default.parentData, it.parentData],
        [names_1.default.parentDataProperty, it.parentDataProperty],
        [names_1.default.rootData, names_1.default.rootData]
      ];
      if (it.opts.dynamicRef)
        valCxt.push([names_1.default.dynamicAnchors, names_1.default.dynamicAnchors]);
      const args = (0, codegen_1._)`${dataAndSchema}, ${gen.object(...valCxt)}`;
      return context !== codegen_1.nil ? (0, codegen_1._)`${func}.call(${context}, ${args})` : (0, codegen_1._)`${func}(${args})`;
    }
    exports.callValidateCode = callValidateCode;
    var newRegExp = (0, codegen_1._)`new RegExp`;
    function usePattern({ gen, it: { opts } }, pattern) {
      const u = opts.unicodeRegExp ? "u" : "";
      const { regExp } = opts.code;
      const rx = regExp(pattern, u);
      return gen.scopeValue("pattern", {
        key: rx.toString(),
        ref: rx,
        code: (0, codegen_1._)`${regExp.code === "new RegExp" ? newRegExp : (0, util_2.useFunc)(gen, regExp)}(${pattern}, ${u})`
      });
    }
    exports.usePattern = usePattern;
    function validateArray(cxt) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      if (it.allErrors) {
        const validArr = gen.let("valid", true);
        validateItems(() => gen.assign(validArr, false));
        return validArr;
      }
      gen.var(valid, true);
      validateItems(() => gen.break());
      return valid;
      function validateItems(notValid) {
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        gen.forRange("i", 0, len, (i2) => {
          cxt.subschema({
            keyword,
            dataProp: i2,
            dataPropType: util_1.Type.Num
          }, valid);
          gen.if((0, codegen_1.not)(valid), notValid);
        });
      }
    }
    exports.validateArray = validateArray;
    function validateUnion(cxt) {
      const { gen, schema, keyword, it } = cxt;
      if (!Array.isArray(schema))
        throw new Error("ajv implementation error");
      const alwaysValid = schema.some((sch) => (0, util_1.alwaysValidSchema)(it, sch));
      if (alwaysValid && !it.opts.unevaluated)
        return;
      const valid = gen.let("valid", false);
      const schValid = gen.name("_valid");
      gen.block(() => schema.forEach((_sch, i2) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i2,
          compositeRule: true
        }, schValid);
        gen.assign(valid, (0, codegen_1._)`${valid} || ${schValid}`);
        const merged = cxt.mergeValidEvaluated(schCxt, schValid);
        if (!merged)
          gen.if((0, codegen_1.not)(valid));
      }));
      cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
    }
    exports.validateUnion = validateUnion;
  }
});

// node_modules/ajv/dist/compile/validate/keyword.js
var require_keyword = __commonJS({
  "node_modules/ajv/dist/compile/validate/keyword.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateKeywordUsage = exports.validSchemaType = exports.funcKeywordCode = exports.macroKeywordCode = void 0;
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var code_1 = require_code2();
    var errors_1 = require_errors();
    function macroKeywordCode(cxt, def) {
      const { gen, keyword, schema, parentSchema, it } = cxt;
      const macroSchema = def.macro.call(it.self, schema, parentSchema, it);
      const schemaRef = useKeyword(gen, keyword, macroSchema);
      if (it.opts.validateSchema !== false)
        it.self.validateSchema(macroSchema, true);
      const valid = gen.name("valid");
      cxt.subschema({
        schema: macroSchema,
        schemaPath: codegen_1.nil,
        errSchemaPath: `${it.errSchemaPath}/${keyword}`,
        topSchemaRef: schemaRef,
        compositeRule: true
      }, valid);
      cxt.pass(valid, () => cxt.error(true));
    }
    exports.macroKeywordCode = macroKeywordCode;
    function funcKeywordCode(cxt, def) {
      var _a3;
      const { gen, keyword, schema, parentSchema, $data, it } = cxt;
      checkAsyncKeyword(it, def);
      const validate = !$data && def.compile ? def.compile.call(it.self, schema, parentSchema, it) : def.validate;
      const validateRef = useKeyword(gen, keyword, validate);
      const valid = gen.let("valid");
      cxt.block$data(valid, validateKeyword);
      cxt.ok((_a3 = def.valid) !== null && _a3 !== void 0 ? _a3 : valid);
      function validateKeyword() {
        if (def.errors === false) {
          assignValid();
          if (def.modifying)
            modifyData(cxt);
          reportErrs(() => cxt.error());
        } else {
          const ruleErrs = def.async ? validateAsync() : validateSync();
          if (def.modifying)
            modifyData(cxt);
          reportErrs(() => addErrs(cxt, ruleErrs));
        }
      }
      function validateAsync() {
        const ruleErrs = gen.let("ruleErrs", null);
        gen.try(() => assignValid((0, codegen_1._)`await `), (e2) => gen.assign(valid, false).if((0, codegen_1._)`${e2} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e2}.errors`), () => gen.throw(e2)));
        return ruleErrs;
      }
      function validateSync() {
        const validateErrs = (0, codegen_1._)`${validateRef}.errors`;
        gen.assign(validateErrs, null);
        assignValid(codegen_1.nil);
        return validateErrs;
      }
      function assignValid(_await = def.async ? (0, codegen_1._)`await ` : codegen_1.nil) {
        const passCxt = it.opts.passContext ? names_1.default.this : names_1.default.self;
        const passSchema = !("compile" in def && !$data || def.schema === false);
        gen.assign(valid, (0, codegen_1._)`${_await}${(0, code_1.callValidateCode)(cxt, validateRef, passCxt, passSchema)}`, def.modifying);
      }
      function reportErrs(errors) {
        var _a4;
        gen.if((0, codegen_1.not)((_a4 = def.valid) !== null && _a4 !== void 0 ? _a4 : valid), errors);
      }
    }
    exports.funcKeywordCode = funcKeywordCode;
    function modifyData(cxt) {
      const { gen, data, it } = cxt;
      gen.if(it.parentData, () => gen.assign(data, (0, codegen_1._)`${it.parentData}[${it.parentDataProperty}]`));
    }
    function addErrs(cxt, errs) {
      const { gen } = cxt;
      gen.if((0, codegen_1._)`Array.isArray(${errs})`, () => {
        gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`).assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
        (0, errors_1.extendErrors)(cxt);
      }, () => cxt.error());
    }
    function checkAsyncKeyword({ schemaEnv }, def) {
      if (def.async && !schemaEnv.$async)
        throw new Error("async keyword in sync schema");
    }
    function useKeyword(gen, keyword, result) {
      if (result === void 0)
        throw new Error(`keyword "${keyword}" failed to compile`);
      return gen.scopeValue("keyword", typeof result == "function" ? { ref: result } : { ref: result, code: (0, codegen_1.stringify)(result) });
    }
    function validSchemaType(schema, schemaType, allowUndefined = false) {
      return !schemaType.length || schemaType.some((st) => st === "array" ? Array.isArray(schema) : st === "object" ? schema && typeof schema == "object" && !Array.isArray(schema) : typeof schema == st || allowUndefined && typeof schema == "undefined");
    }
    exports.validSchemaType = validSchemaType;
    function validateKeywordUsage({ schema, opts, self: self2, errSchemaPath }, def, keyword) {
      if (Array.isArray(def.keyword) ? !def.keyword.includes(keyword) : def.keyword !== keyword) {
        throw new Error("ajv implementation error");
      }
      const deps = def.dependencies;
      if (deps === null || deps === void 0 ? void 0 : deps.some((kwd) => !Object.prototype.hasOwnProperty.call(schema, kwd))) {
        throw new Error(`parent schema must have dependencies of ${keyword}: ${deps.join(",")}`);
      }
      if (def.validateSchema) {
        const valid = def.validateSchema(schema[keyword]);
        if (!valid) {
          const msg = `keyword "${keyword}" value is invalid at path "${errSchemaPath}": ` + self2.errorsText(def.validateSchema.errors);
          if (opts.validateSchema === "log")
            self2.logger.error(msg);
          else
            throw new Error(msg);
        }
      }
    }
    exports.validateKeywordUsage = validateKeywordUsage;
  }
});

// node_modules/ajv/dist/compile/validate/subschema.js
var require_subschema = __commonJS({
  "node_modules/ajv/dist/compile/validate/subschema.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.extendSubschemaMode = exports.extendSubschemaData = exports.getSubschema = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    function getSubschema(it, { keyword, schemaProp, schema, schemaPath, errSchemaPath, topSchemaRef }) {
      if (keyword !== void 0 && schema !== void 0) {
        throw new Error('both "keyword" and "schema" passed, only one allowed');
      }
      if (keyword !== void 0) {
        const sch = it.schema[keyword];
        return schemaProp === void 0 ? {
          schema: sch,
          schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}`
        } : {
          schema: sch[schemaProp],
          schemaPath: (0, codegen_1._)`${it.schemaPath}${(0, codegen_1.getProperty)(keyword)}${(0, codegen_1.getProperty)(schemaProp)}`,
          errSchemaPath: `${it.errSchemaPath}/${keyword}/${(0, util_1.escapeFragment)(schemaProp)}`
        };
      }
      if (schema !== void 0) {
        if (schemaPath === void 0 || errSchemaPath === void 0 || topSchemaRef === void 0) {
          throw new Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
        }
        return {
          schema,
          schemaPath,
          topSchemaRef,
          errSchemaPath
        };
      }
      throw new Error('either "keyword" or "schema" must be passed');
    }
    exports.getSubschema = getSubschema;
    function extendSubschemaData(subschema, it, { dataProp, dataPropType: dpType, data, dataTypes, propertyName }) {
      if (data !== void 0 && dataProp !== void 0) {
        throw new Error('both "data" and "dataProp" passed, only one allowed');
      }
      const { gen } = it;
      if (dataProp !== void 0) {
        const { errorPath, dataPathArr, opts } = it;
        const nextData = gen.let("data", (0, codegen_1._)`${it.data}${(0, codegen_1.getProperty)(dataProp)}`, true);
        dataContextProps(nextData);
        subschema.errorPath = (0, codegen_1.str)`${errorPath}${(0, util_1.getErrorPath)(dataProp, dpType, opts.jsPropertySyntax)}`;
        subschema.parentDataProperty = (0, codegen_1._)`${dataProp}`;
        subschema.dataPathArr = [...dataPathArr, subschema.parentDataProperty];
      }
      if (data !== void 0) {
        const nextData = data instanceof codegen_1.Name ? data : gen.let("data", data, true);
        dataContextProps(nextData);
        if (propertyName !== void 0)
          subschema.propertyName = propertyName;
      }
      if (dataTypes)
        subschema.dataTypes = dataTypes;
      function dataContextProps(_nextData) {
        subschema.data = _nextData;
        subschema.dataLevel = it.dataLevel + 1;
        subschema.dataTypes = [];
        it.definedProperties = /* @__PURE__ */ new Set();
        subschema.parentData = it.data;
        subschema.dataNames = [...it.dataNames, _nextData];
      }
    }
    exports.extendSubschemaData = extendSubschemaData;
    function extendSubschemaMode(subschema, { jtdDiscriminator, jtdMetadata, compositeRule, createErrors, allErrors }) {
      if (compositeRule !== void 0)
        subschema.compositeRule = compositeRule;
      if (createErrors !== void 0)
        subschema.createErrors = createErrors;
      if (allErrors !== void 0)
        subschema.allErrors = allErrors;
      subschema.jtdDiscriminator = jtdDiscriminator;
      subschema.jtdMetadata = jtdMetadata;
    }
    exports.extendSubschemaMode = extendSubschemaMode;
  }
});

// node_modules/fast-deep-equal/index.js
var require_fast_deep_equal = __commonJS({
  "node_modules/fast-deep-equal/index.js"(exports, module2) {
    "use strict";
    module2.exports = function equal(a2, b10) {
      if (a2 === b10) return true;
      if (a2 && b10 && typeof a2 == "object" && typeof b10 == "object") {
        if (a2.constructor !== b10.constructor) return false;
        var length, i2, keys;
        if (Array.isArray(a2)) {
          length = a2.length;
          if (length != b10.length) return false;
          for (i2 = length; i2-- !== 0; )
            if (!equal(a2[i2], b10[i2])) return false;
          return true;
        }
        if (a2.constructor === RegExp) return a2.source === b10.source && a2.flags === b10.flags;
        if (a2.valueOf !== Object.prototype.valueOf) return a2.valueOf() === b10.valueOf();
        if (a2.toString !== Object.prototype.toString) return a2.toString() === b10.toString();
        keys = Object.keys(a2);
        length = keys.length;
        if (length !== Object.keys(b10).length) return false;
        for (i2 = length; i2-- !== 0; )
          if (!Object.prototype.hasOwnProperty.call(b10, keys[i2])) return false;
        for (i2 = length; i2-- !== 0; ) {
          var key = keys[i2];
          if (!equal(a2[key], b10[key])) return false;
        }
        return true;
      }
      return a2 !== a2 && b10 !== b10;
    };
  }
});

// node_modules/json-schema-traverse/index.js
var require_json_schema_traverse = __commonJS({
  "node_modules/json-schema-traverse/index.js"(exports, module2) {
    "use strict";
    var traverse = module2.exports = function(schema, opts, cb) {
      if (typeof opts == "function") {
        cb = opts;
        opts = {};
      }
      cb = opts.cb || cb;
      var pre = typeof cb == "function" ? cb : cb.pre || function() {
      };
      var post = cb.post || function() {
      };
      _traverse(opts, pre, post, schema, "", schema);
    };
    traverse.keywords = {
      additionalItems: true,
      items: true,
      contains: true,
      additionalProperties: true,
      propertyNames: true,
      not: true,
      if: true,
      then: true,
      else: true
    };
    traverse.arrayKeywords = {
      items: true,
      allOf: true,
      anyOf: true,
      oneOf: true
    };
    traverse.propsKeywords = {
      $defs: true,
      definitions: true,
      properties: true,
      patternProperties: true,
      dependencies: true
    };
    traverse.skipKeywords = {
      default: true,
      enum: true,
      const: true,
      required: true,
      maximum: true,
      minimum: true,
      exclusiveMaximum: true,
      exclusiveMinimum: true,
      multipleOf: true,
      maxLength: true,
      minLength: true,
      pattern: true,
      format: true,
      maxItems: true,
      minItems: true,
      uniqueItems: true,
      maxProperties: true,
      minProperties: true
    };
    function _traverse(opts, pre, post, schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex) {
      if (schema && typeof schema == "object" && !Array.isArray(schema)) {
        pre(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
        for (var key in schema) {
          var sch = schema[key];
          if (Array.isArray(sch)) {
            if (key in traverse.arrayKeywords) {
              for (var i2 = 0; i2 < sch.length; i2++)
                _traverse(opts, pre, post, sch[i2], jsonPtr + "/" + key + "/" + i2, rootSchema, jsonPtr, key, schema, i2);
            }
          } else if (key in traverse.propsKeywords) {
            if (sch && typeof sch == "object") {
              for (var prop in sch)
                _traverse(opts, pre, post, sch[prop], jsonPtr + "/" + key + "/" + escapeJsonPtr(prop), rootSchema, jsonPtr, key, schema, prop);
            }
          } else if (key in traverse.keywords || opts.allKeys && !(key in traverse.skipKeywords)) {
            _traverse(opts, pre, post, sch, jsonPtr + "/" + key, rootSchema, jsonPtr, key, schema);
          }
        }
        post(schema, jsonPtr, rootSchema, parentJsonPtr, parentKeyword, parentSchema, keyIndex);
      }
    }
    function escapeJsonPtr(str) {
      return str.replace(/~/g, "~0").replace(/\//g, "~1");
    }
  }
});

// node_modules/ajv/dist/compile/resolve.js
var require_resolve = __commonJS({
  "node_modules/ajv/dist/compile/resolve.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getSchemaRefs = exports.resolveUrl = exports.normalizeId = exports._getFullPath = exports.getFullPath = exports.inlineRef = void 0;
    var util_1 = require_util();
    var equal = require_fast_deep_equal();
    var traverse = require_json_schema_traverse();
    var SIMPLE_INLINED = /* @__PURE__ */ new Set([
      "type",
      "format",
      "pattern",
      "maxLength",
      "minLength",
      "maxProperties",
      "minProperties",
      "maxItems",
      "minItems",
      "maximum",
      "minimum",
      "uniqueItems",
      "multipleOf",
      "required",
      "enum",
      "const"
    ]);
    function inlineRef(schema, limit = true) {
      if (typeof schema == "boolean")
        return true;
      if (limit === true)
        return !hasRef(schema);
      if (!limit)
        return false;
      return countKeys(schema) <= limit;
    }
    exports.inlineRef = inlineRef;
    var REF_KEYWORDS = /* @__PURE__ */ new Set([
      "$ref",
      "$recursiveRef",
      "$recursiveAnchor",
      "$dynamicRef",
      "$dynamicAnchor"
    ]);
    function hasRef(schema) {
      for (const key in schema) {
        if (REF_KEYWORDS.has(key))
          return true;
        const sch = schema[key];
        if (Array.isArray(sch) && sch.some(hasRef))
          return true;
        if (typeof sch == "object" && hasRef(sch))
          return true;
      }
      return false;
    }
    function countKeys(schema) {
      let count = 0;
      for (const key in schema) {
        if (key === "$ref")
          return Infinity;
        count++;
        if (SIMPLE_INLINED.has(key))
          continue;
        if (typeof schema[key] == "object") {
          (0, util_1.eachItem)(schema[key], (sch) => count += countKeys(sch));
        }
        if (count === Infinity)
          return Infinity;
      }
      return count;
    }
    function getFullPath(resolver, id = "", normalize3) {
      if (normalize3 !== false)
        id = normalizeId(id);
      const p = resolver.parse(id);
      return _getFullPath(resolver, p);
    }
    exports.getFullPath = getFullPath;
    function _getFullPath(resolver, p) {
      const serialized = resolver.serialize(p);
      return serialized.split("#")[0] + "#";
    }
    exports._getFullPath = _getFullPath;
    var TRAILING_SLASH_HASH = /#\/?$/;
    function normalizeId(id) {
      return id ? id.replace(TRAILING_SLASH_HASH, "") : "";
    }
    exports.normalizeId = normalizeId;
    function resolveUrl(resolver, baseId, id) {
      id = normalizeId(id);
      return resolver.resolve(baseId, id);
    }
    exports.resolveUrl = resolveUrl;
    var ANCHOR = /^[a-z_][-a-z0-9._]*$/i;
    function getSchemaRefs(schema, baseId) {
      if (typeof schema == "boolean")
        return {};
      const { schemaId, uriResolver } = this.opts;
      const schId = normalizeId(schema[schemaId] || baseId);
      const baseIds = { "": schId };
      const pathPrefix = getFullPath(uriResolver, schId, false);
      const localRefs = {};
      const schemaRefs = /* @__PURE__ */ new Set();
      traverse(schema, { allKeys: true }, (sch, jsonPtr, _10, parentJsonPtr) => {
        if (parentJsonPtr === void 0)
          return;
        const fullPath = pathPrefix + jsonPtr;
        let innerBaseId = baseIds[parentJsonPtr];
        if (typeof sch[schemaId] == "string")
          innerBaseId = addRef.call(this, sch[schemaId]);
        addAnchor.call(this, sch.$anchor);
        addAnchor.call(this, sch.$dynamicAnchor);
        baseIds[jsonPtr] = innerBaseId;
        function addRef(ref) {
          const _resolve = this.opts.uriResolver.resolve;
          ref = normalizeId(innerBaseId ? _resolve(innerBaseId, ref) : ref);
          if (schemaRefs.has(ref))
            throw ambiguos(ref);
          schemaRefs.add(ref);
          let schOrRef = this.refs[ref];
          if (typeof schOrRef == "string")
            schOrRef = this.refs[schOrRef];
          if (typeof schOrRef == "object") {
            checkAmbiguosRef(sch, schOrRef.schema, ref);
          } else if (ref !== normalizeId(fullPath)) {
            if (ref[0] === "#") {
              checkAmbiguosRef(sch, localRefs[ref], ref);
              localRefs[ref] = sch;
            } else {
              this.refs[ref] = fullPath;
            }
          }
          return ref;
        }
        function addAnchor(anchor) {
          if (typeof anchor == "string") {
            if (!ANCHOR.test(anchor))
              throw new Error(`invalid anchor "${anchor}"`);
            addRef.call(this, `#${anchor}`);
          }
        }
      });
      return localRefs;
      function checkAmbiguosRef(sch1, sch2, ref) {
        if (sch2 !== void 0 && !equal(sch1, sch2))
          throw ambiguos(ref);
      }
      function ambiguos(ref) {
        return new Error(`reference "${ref}" resolves to more than one schema`);
      }
    }
    exports.getSchemaRefs = getSchemaRefs;
  }
});

// node_modules/ajv/dist/compile/validate/index.js
var require_validate = __commonJS({
  "node_modules/ajv/dist/compile/validate/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.getData = exports.KeywordCxt = exports.validateFunctionCode = void 0;
    var boolSchema_1 = require_boolSchema();
    var dataType_1 = require_dataType();
    var applicability_1 = require_applicability();
    var dataType_2 = require_dataType();
    var defaults_1 = require_defaults();
    var keyword_1 = require_keyword();
    var subschema_1 = require_subschema();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var resolve_1 = require_resolve();
    var util_1 = require_util();
    var errors_1 = require_errors();
    function validateFunctionCode(it) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          topSchemaObjCode(it);
          return;
        }
      }
      validateFunction(it, () => (0, boolSchema_1.topBoolOrEmptySchema)(it));
    }
    exports.validateFunctionCode = validateFunctionCode;
    function validateFunction({ gen, validateName, schema, schemaEnv, opts }, body) {
      if (opts.code.es5) {
        gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${names_1.default.valCxt}`, schemaEnv.$async, () => {
          gen.code((0, codegen_1._)`"use strict"; ${funcSourceUrl(schema, opts)}`);
          destructureValCxtES5(gen, opts);
          gen.code(body);
        });
      } else {
        gen.func(validateName, (0, codegen_1._)`${names_1.default.data}, ${destructureValCxt(opts)}`, schemaEnv.$async, () => gen.code(funcSourceUrl(schema, opts)).code(body));
      }
    }
    function destructureValCxt(opts) {
      return (0, codegen_1._)`{${names_1.default.instancePath}="", ${names_1.default.parentData}, ${names_1.default.parentDataProperty}, ${names_1.default.rootData}=${names_1.default.data}${opts.dynamicRef ? (0, codegen_1._)`, ${names_1.default.dynamicAnchors}={}` : codegen_1.nil}}={}`;
    }
    function destructureValCxtES5(gen, opts) {
      gen.if(names_1.default.valCxt, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.instancePath}`);
        gen.var(names_1.default.parentData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentData}`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.parentDataProperty}`);
        gen.var(names_1.default.rootData, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.rootData}`);
        if (opts.dynamicRef)
          gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`${names_1.default.valCxt}.${names_1.default.dynamicAnchors}`);
      }, () => {
        gen.var(names_1.default.instancePath, (0, codegen_1._)`""`);
        gen.var(names_1.default.parentData, (0, codegen_1._)`undefined`);
        gen.var(names_1.default.parentDataProperty, (0, codegen_1._)`undefined`);
        gen.var(names_1.default.rootData, names_1.default.data);
        if (opts.dynamicRef)
          gen.var(names_1.default.dynamicAnchors, (0, codegen_1._)`{}`);
      });
    }
    function topSchemaObjCode(it) {
      const { schema, opts, gen } = it;
      validateFunction(it, () => {
        if (opts.$comment && schema.$comment)
          commentKeyword(it);
        checkNoDefault(it);
        gen.let(names_1.default.vErrors, null);
        gen.let(names_1.default.errors, 0);
        if (opts.unevaluated)
          resetEvaluated(it);
        typeAndKeywords(it);
        returnResults(it);
      });
      return;
    }
    function resetEvaluated(it) {
      const { gen, validateName } = it;
      it.evaluated = gen.const("evaluated", (0, codegen_1._)`${validateName}.evaluated`);
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicProps`, () => gen.assign((0, codegen_1._)`${it.evaluated}.props`, (0, codegen_1._)`undefined`));
      gen.if((0, codegen_1._)`${it.evaluated}.dynamicItems`, () => gen.assign((0, codegen_1._)`${it.evaluated}.items`, (0, codegen_1._)`undefined`));
    }
    function funcSourceUrl(schema, opts) {
      const schId = typeof schema == "object" && schema[opts.schemaId];
      return schId && (opts.code.source || opts.code.process) ? (0, codegen_1._)`/*# sourceURL=${schId} */` : codegen_1.nil;
    }
    function subschemaCode(it, valid) {
      if (isSchemaObj(it)) {
        checkKeywords(it);
        if (schemaCxtHasRules(it)) {
          subSchemaObjCode(it, valid);
          return;
        }
      }
      (0, boolSchema_1.boolOrEmptySchema)(it, valid);
    }
    function schemaCxtHasRules({ schema, self: self2 }) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (self2.RULES.all[key])
          return true;
      return false;
    }
    function isSchemaObj(it) {
      return typeof it.schema != "boolean";
    }
    function subSchemaObjCode(it, valid) {
      const { schema, gen, opts } = it;
      if (opts.$comment && schema.$comment)
        commentKeyword(it);
      updateContext(it);
      checkAsyncSchema(it);
      const errsCount = gen.const("_errs", names_1.default.errors);
      typeAndKeywords(it, errsCount);
      gen.var(valid, (0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
    }
    function checkKeywords(it) {
      (0, util_1.checkUnknownRules)(it);
      checkRefsAndKeywords(it);
    }
    function typeAndKeywords(it, errsCount) {
      if (it.opts.jtd)
        return schemaKeywords(it, [], false, errsCount);
      const types = (0, dataType_1.getSchemaTypes)(it.schema);
      const checkedTypes = (0, dataType_1.coerceAndCheckDataType)(it, types);
      schemaKeywords(it, types, !checkedTypes, errsCount);
    }
    function checkRefsAndKeywords(it) {
      const { schema, errSchemaPath, opts, self: self2 } = it;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self2.RULES)) {
        self2.logger.warn(`$ref: keywords ignored in schema at path "${errSchemaPath}"`);
      }
    }
    function checkNoDefault(it) {
      const { schema, opts } = it;
      if (schema.default !== void 0 && opts.useDefaults && opts.strictSchema) {
        (0, util_1.checkStrictMode)(it, "default is ignored in the schema root");
      }
    }
    function updateContext(it) {
      const schId = it.schema[it.opts.schemaId];
      if (schId)
        it.baseId = (0, resolve_1.resolveUrl)(it.opts.uriResolver, it.baseId, schId);
    }
    function checkAsyncSchema(it) {
      if (it.schema.$async && !it.schemaEnv.$async)
        throw new Error("async schema in sync schema");
    }
    function commentKeyword({ gen, schemaEnv, schema, errSchemaPath, opts }) {
      const msg = schema.$comment;
      if (opts.$comment === true) {
        gen.code((0, codegen_1._)`${names_1.default.self}.logger.log(${msg})`);
      } else if (typeof opts.$comment == "function") {
        const schemaPath = (0, codegen_1.str)`${errSchemaPath}/$comment`;
        const rootName = gen.scopeValue("root", { ref: schemaEnv.root });
        gen.code((0, codegen_1._)`${names_1.default.self}.opts.$comment(${msg}, ${schemaPath}, ${rootName}.schema)`);
      }
    }
    function returnResults(it) {
      const { gen, schemaEnv, validateName, ValidationError, opts } = it;
      if (schemaEnv.$async) {
        gen.if((0, codegen_1._)`${names_1.default.errors} === 0`, () => gen.return(names_1.default.data), () => gen.throw((0, codegen_1._)`new ${ValidationError}(${names_1.default.vErrors})`));
      } else {
        gen.assign((0, codegen_1._)`${validateName}.errors`, names_1.default.vErrors);
        if (opts.unevaluated)
          assignEvaluated(it);
        gen.return((0, codegen_1._)`${names_1.default.errors} === 0`);
      }
    }
    function assignEvaluated({ gen, evaluated, props, items }) {
      if (props instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.props`, props);
      if (items instanceof codegen_1.Name)
        gen.assign((0, codegen_1._)`${evaluated}.items`, items);
    }
    function schemaKeywords(it, types, typeErrors, errsCount) {
      const { gen, schema, data, allErrors, opts, self: self2 } = it;
      const { RULES } = self2;
      if (schema.$ref && (opts.ignoreKeywordsWithRef || !(0, util_1.schemaHasRulesButRef)(schema, RULES))) {
        gen.block(() => keywordCode(it, "$ref", RULES.all.$ref.definition));
        return;
      }
      if (!opts.jtd)
        checkStrictTypes(it, types);
      gen.block(() => {
        for (const group of RULES.rules)
          groupKeywords(group);
        groupKeywords(RULES.post);
      });
      function groupKeywords(group) {
        if (!(0, applicability_1.shouldUseGroup)(schema, group))
          return;
        if (group.type) {
          gen.if((0, dataType_2.checkDataType)(group.type, data, opts.strictNumbers));
          iterateKeywords(it, group);
          if (types.length === 1 && types[0] === group.type && typeErrors) {
            gen.else();
            (0, dataType_2.reportTypeError)(it);
          }
          gen.endIf();
        } else {
          iterateKeywords(it, group);
        }
        if (!allErrors)
          gen.if((0, codegen_1._)`${names_1.default.errors} === ${errsCount || 0}`);
      }
    }
    function iterateKeywords(it, group) {
      const { gen, schema, opts: { useDefaults } } = it;
      if (useDefaults)
        (0, defaults_1.assignDefaults)(it, group.type);
      gen.block(() => {
        for (const rule of group.rules) {
          if ((0, applicability_1.shouldUseRule)(schema, rule)) {
            keywordCode(it, rule.keyword, rule.definition, group.type);
          }
        }
      });
    }
    function checkStrictTypes(it, types) {
      if (it.schemaEnv.meta || !it.opts.strictTypes)
        return;
      checkContextTypes(it, types);
      if (!it.opts.allowUnionTypes)
        checkMultipleTypes(it, types);
      checkKeywordTypes(it, it.dataTypes);
    }
    function checkContextTypes(it, types) {
      if (!types.length)
        return;
      if (!it.dataTypes.length) {
        it.dataTypes = types;
        return;
      }
      types.forEach((t2) => {
        if (!includesType(it.dataTypes, t2)) {
          strictTypesError(it, `type "${t2}" not allowed by context "${it.dataTypes.join(",")}"`);
        }
      });
      narrowSchemaTypes(it, types);
    }
    function checkMultipleTypes(it, ts) {
      if (ts.length > 1 && !(ts.length === 2 && ts.includes("null"))) {
        strictTypesError(it, "use allowUnionTypes to allow union type keyword");
      }
    }
    function checkKeywordTypes(it, ts) {
      const rules = it.self.RULES.all;
      for (const keyword in rules) {
        const rule = rules[keyword];
        if (typeof rule == "object" && (0, applicability_1.shouldUseRule)(it.schema, rule)) {
          const { type } = rule.definition;
          if (type.length && !type.some((t2) => hasApplicableType(ts, t2))) {
            strictTypesError(it, `missing type "${type.join(",")}" for keyword "${keyword}"`);
          }
        }
      }
    }
    function hasApplicableType(schTs, kwdT) {
      return schTs.includes(kwdT) || kwdT === "number" && schTs.includes("integer");
    }
    function includesType(ts, t2) {
      return ts.includes(t2) || t2 === "integer" && ts.includes("number");
    }
    function narrowSchemaTypes(it, withTypes) {
      const ts = [];
      for (const t2 of it.dataTypes) {
        if (includesType(withTypes, t2))
          ts.push(t2);
        else if (withTypes.includes("integer") && t2 === "number")
          ts.push("integer");
      }
      it.dataTypes = ts;
    }
    function strictTypesError(it, msg) {
      const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
      msg += ` at "${schemaPath}" (strictTypes)`;
      (0, util_1.checkStrictMode)(it, msg, it.opts.strictTypes);
    }
    var KeywordCxt = class {
      constructor(it, def, keyword) {
        (0, keyword_1.validateKeywordUsage)(it, def, keyword);
        this.gen = it.gen;
        this.allErrors = it.allErrors;
        this.keyword = keyword;
        this.data = it.data;
        this.schema = it.schema[keyword];
        this.$data = def.$data && it.opts.$data && this.schema && this.schema.$data;
        this.schemaValue = (0, util_1.schemaRefOrVal)(it, this.schema, keyword, this.$data);
        this.schemaType = def.schemaType;
        this.parentSchema = it.schema;
        this.params = {};
        this.it = it;
        this.def = def;
        if (this.$data) {
          this.schemaCode = it.gen.const("vSchema", getData(this.$data, it));
        } else {
          this.schemaCode = this.schemaValue;
          if (!(0, keyword_1.validSchemaType)(this.schema, def.schemaType, def.allowUndefined)) {
            throw new Error(`${keyword} value must be ${JSON.stringify(def.schemaType)}`);
          }
        }
        if ("code" in def ? def.trackErrors : def.errors !== false) {
          this.errsCount = it.gen.const("_errs", names_1.default.errors);
        }
      }
      result(condition, successAction, failAction) {
        this.failResult((0, codegen_1.not)(condition), successAction, failAction);
      }
      failResult(condition, successAction, failAction) {
        this.gen.if(condition);
        if (failAction)
          failAction();
        else
          this.error();
        if (successAction) {
          this.gen.else();
          successAction();
          if (this.allErrors)
            this.gen.endIf();
        } else {
          if (this.allErrors)
            this.gen.endIf();
          else
            this.gen.else();
        }
      }
      pass(condition, failAction) {
        this.failResult((0, codegen_1.not)(condition), void 0, failAction);
      }
      fail(condition) {
        if (condition === void 0) {
          this.error();
          if (!this.allErrors)
            this.gen.if(false);
          return;
        }
        this.gen.if(condition);
        this.error();
        if (this.allErrors)
          this.gen.endIf();
        else
          this.gen.else();
      }
      fail$data(condition) {
        if (!this.$data)
          return this.fail(condition);
        const { schemaCode } = this;
        this.fail((0, codegen_1._)`${schemaCode} !== undefined && (${(0, codegen_1.or)(this.invalid$data(), condition)})`);
      }
      error(append, errorParams, errorPaths) {
        if (errorParams) {
          this.setParams(errorParams);
          this._error(append, errorPaths);
          this.setParams({});
          return;
        }
        this._error(append, errorPaths);
      }
      _error(append, errorPaths) {
        ;
        (append ? errors_1.reportExtraError : errors_1.reportError)(this, this.def.error, errorPaths);
      }
      $dataError() {
        (0, errors_1.reportError)(this, this.def.$dataError || errors_1.keyword$DataError);
      }
      reset() {
        if (this.errsCount === void 0)
          throw new Error('add "trackErrors" to keyword definition');
        (0, errors_1.resetErrorsCount)(this.gen, this.errsCount);
      }
      ok(cond) {
        if (!this.allErrors)
          this.gen.if(cond);
      }
      setParams(obj, assign) {
        if (assign)
          Object.assign(this.params, obj);
        else
          this.params = obj;
      }
      block$data(valid, codeBlock, $dataValid = codegen_1.nil) {
        this.gen.block(() => {
          this.check$data(valid, $dataValid);
          codeBlock();
        });
      }
      check$data(valid = codegen_1.nil, $dataValid = codegen_1.nil) {
        if (!this.$data)
          return;
        const { gen, schemaCode, schemaType, def } = this;
        gen.if((0, codegen_1.or)((0, codegen_1._)`${schemaCode} === undefined`, $dataValid));
        if (valid !== codegen_1.nil)
          gen.assign(valid, true);
        if (schemaType.length || def.validateSchema) {
          gen.elseIf(this.invalid$data());
          this.$dataError();
          if (valid !== codegen_1.nil)
            gen.assign(valid, false);
        }
        gen.else();
      }
      invalid$data() {
        const { gen, schemaCode, schemaType, def, it } = this;
        return (0, codegen_1.or)(wrong$DataType(), invalid$DataSchema());
        function wrong$DataType() {
          if (schemaType.length) {
            if (!(schemaCode instanceof codegen_1.Name))
              throw new Error("ajv implementation error");
            const st = Array.isArray(schemaType) ? schemaType : [schemaType];
            return (0, codegen_1._)`${(0, dataType_2.checkDataTypes)(st, schemaCode, it.opts.strictNumbers, dataType_2.DataType.Wrong)}`;
          }
          return codegen_1.nil;
        }
        function invalid$DataSchema() {
          if (def.validateSchema) {
            const validateSchemaRef = gen.scopeValue("validate$data", { ref: def.validateSchema });
            return (0, codegen_1._)`!${validateSchemaRef}(${schemaCode})`;
          }
          return codegen_1.nil;
        }
      }
      subschema(appl, valid) {
        const subschema = (0, subschema_1.getSubschema)(this.it, appl);
        (0, subschema_1.extendSubschemaData)(subschema, this.it, appl);
        (0, subschema_1.extendSubschemaMode)(subschema, appl);
        const nextContext = { ...this.it, ...subschema, items: void 0, props: void 0 };
        subschemaCode(nextContext, valid);
        return nextContext;
      }
      mergeEvaluated(schemaCxt, toName) {
        const { it, gen } = this;
        if (!it.opts.unevaluated)
          return;
        if (it.props !== true && schemaCxt.props !== void 0) {
          it.props = util_1.mergeEvaluated.props(gen, schemaCxt.props, it.props, toName);
        }
        if (it.items !== true && schemaCxt.items !== void 0) {
          it.items = util_1.mergeEvaluated.items(gen, schemaCxt.items, it.items, toName);
        }
      }
      mergeValidEvaluated(schemaCxt, valid) {
        const { it, gen } = this;
        if (it.opts.unevaluated && (it.props !== true || it.items !== true)) {
          gen.if(valid, () => this.mergeEvaluated(schemaCxt, codegen_1.Name));
          return true;
        }
      }
    };
    exports.KeywordCxt = KeywordCxt;
    function keywordCode(it, keyword, def, ruleType) {
      const cxt = new KeywordCxt(it, def, keyword);
      if ("code" in def) {
        def.code(cxt, ruleType);
      } else if (cxt.$data && def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
      } else if ("macro" in def) {
        (0, keyword_1.macroKeywordCode)(cxt, def);
      } else if (def.compile || def.validate) {
        (0, keyword_1.funcKeywordCode)(cxt, def);
      }
    }
    var JSON_POINTER = /^\/(?:[^~]|~0|~1)*$/;
    var RELATIVE_JSON_POINTER = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
    function getData($data, { dataLevel, dataNames, dataPathArr }) {
      let jsonPointer;
      let data;
      if ($data === "")
        return names_1.default.rootData;
      if ($data[0] === "/") {
        if (!JSON_POINTER.test($data))
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        jsonPointer = $data;
        data = names_1.default.rootData;
      } else {
        const matches = RELATIVE_JSON_POINTER.exec($data);
        if (!matches)
          throw new Error(`Invalid JSON-pointer: ${$data}`);
        const up = +matches[1];
        jsonPointer = matches[2];
        if (jsonPointer === "#") {
          if (up >= dataLevel)
            throw new Error(errorMsg("property/index", up));
          return dataPathArr[dataLevel - up];
        }
        if (up > dataLevel)
          throw new Error(errorMsg("data", up));
        data = dataNames[dataLevel - up];
        if (!jsonPointer)
          return data;
      }
      let expr = data;
      const segments = jsonPointer.split("/");
      for (const segment of segments) {
        if (segment) {
          data = (0, codegen_1._)`${data}${(0, codegen_1.getProperty)((0, util_1.unescapeJsonPointer)(segment))}`;
          expr = (0, codegen_1._)`${expr} && ${data}`;
        }
      }
      return expr;
      function errorMsg(pointerType, up) {
        return `Cannot access ${pointerType} ${up} levels up, current level is ${dataLevel}`;
      }
    }
    exports.getData = getData;
  }
});

// node_modules/ajv/dist/runtime/validation_error.js
var require_validation_error = __commonJS({
  "node_modules/ajv/dist/runtime/validation_error.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var ValidationError = class extends Error {
      constructor(errors) {
        super("validation failed");
        this.errors = errors;
        this.ajv = this.validation = true;
      }
    };
    exports.default = ValidationError;
  }
});

// node_modules/ajv/dist/compile/ref_error.js
var require_ref_error = __commonJS({
  "node_modules/ajv/dist/compile/ref_error.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var resolve_1 = require_resolve();
    var MissingRefError = class extends Error {
      constructor(resolver, baseId, ref, msg) {
        super(msg || `can't resolve reference ${ref} from id ${baseId}`);
        this.missingRef = (0, resolve_1.resolveUrl)(resolver, baseId, ref);
        this.missingSchema = (0, resolve_1.normalizeId)((0, resolve_1.getFullPath)(resolver, this.missingRef));
      }
    };
    exports.default = MissingRefError;
  }
});

// node_modules/ajv/dist/compile/index.js
var require_compile = __commonJS({
  "node_modules/ajv/dist/compile/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.resolveSchema = exports.getCompilingSchema = exports.resolveRef = exports.compileSchema = exports.SchemaEnv = void 0;
    var codegen_1 = require_codegen();
    var validation_error_1 = require_validation_error();
    var names_1 = require_names();
    var resolve_1 = require_resolve();
    var util_1 = require_util();
    var validate_1 = require_validate();
    var SchemaEnv = class {
      constructor(env) {
        var _a3;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env.schema == "object")
          schema = env.schema;
        this.schema = env.schema;
        this.schemaId = env.schemaId;
        this.root = env.root || this;
        this.baseId = (_a3 = env.baseId) !== null && _a3 !== void 0 ? _a3 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env.schemaId || "$id"]);
        this.schemaPath = env.schemaPath;
        this.localRefs = env.localRefs;
        this.meta = env.meta;
        this.$async = schema === null || schema === void 0 ? void 0 : schema.$async;
        this.refs = {};
      }
    };
    exports.SchemaEnv = SchemaEnv;
    function compileSchema(sch) {
      const _sch = getCompilingSchema.call(this, sch);
      if (_sch)
        return _sch;
      const rootId = (0, resolve_1.getFullPath)(this.opts.uriResolver, sch.root.baseId);
      const { es5, lines } = this.opts.code;
      const { ownProperties } = this.opts;
      const gen = new codegen_1.CodeGen(this.scope, { es5, lines, ownProperties });
      let _ValidationError;
      if (sch.$async) {
        _ValidationError = gen.scopeValue("Error", {
          ref: validation_error_1.default,
          code: (0, codegen_1._)`require("ajv/dist/runtime/validation_error").default`
        });
      }
      const validateName = gen.scopeName("validate");
      sch.validateName = validateName;
      const schemaCxt = {
        gen,
        allErrors: this.opts.allErrors,
        data: names_1.default.data,
        parentData: names_1.default.parentData,
        parentDataProperty: names_1.default.parentDataProperty,
        dataNames: [names_1.default.data],
        dataPathArr: [codegen_1.nil],
        // TODO can its length be used as dataLevel if nil is removed?
        dataLevel: 0,
        dataTypes: [],
        definedProperties: /* @__PURE__ */ new Set(),
        topSchemaRef: gen.scopeValue("schema", this.opts.code.source === true ? { ref: sch.schema, code: (0, codegen_1.stringify)(sch.schema) } : { ref: sch.schema }),
        validateName,
        ValidationError: _ValidationError,
        schema: sch.schema,
        schemaEnv: sch,
        rootId,
        baseId: sch.baseId || rootId,
        schemaPath: codegen_1.nil,
        errSchemaPath: sch.schemaPath || (this.opts.jtd ? "" : "#"),
        errorPath: (0, codegen_1._)`""`,
        opts: this.opts,
        self: this
      };
      let sourceCode;
      try {
        this._compilations.add(sch);
        (0, validate_1.validateFunctionCode)(schemaCxt);
        gen.optimize(this.opts.code.optimize);
        const validateCode = gen.toString();
        sourceCode = `${gen.scopeRefs(names_1.default.scope)}return ${validateCode}`;
        if (this.opts.code.process)
          sourceCode = this.opts.code.process(sourceCode, sch);
        const makeValidate = new Function(`${names_1.default.self}`, `${names_1.default.scope}`, sourceCode);
        const validate = makeValidate(this, this.scope.get());
        this.scope.value(validateName, { ref: validate });
        validate.errors = null;
        validate.schema = sch.schema;
        validate.schemaEnv = sch;
        if (sch.$async)
          validate.$async = true;
        if (this.opts.code.source === true) {
          validate.source = { validateName, validateCode, scopeValues: gen._values };
        }
        if (this.opts.unevaluated) {
          const { props, items } = schemaCxt;
          validate.evaluated = {
            props: props instanceof codegen_1.Name ? void 0 : props,
            items: items instanceof codegen_1.Name ? void 0 : items,
            dynamicProps: props instanceof codegen_1.Name,
            dynamicItems: items instanceof codegen_1.Name
          };
          if (validate.source)
            validate.source.evaluated = (0, codegen_1.stringify)(validate.evaluated);
        }
        sch.validate = validate;
        return sch;
      } catch (e2) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e2;
      } finally {
        this._compilations.delete(sch);
      }
    }
    exports.compileSchema = compileSchema;
    function resolveRef(root, baseId, ref) {
      var _a3;
      ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
      const schOrFunc = root.refs[ref];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve8.call(this, root, ref);
      if (_sch === void 0) {
        const schema = (_a3 = root.localRefs) === null || _a3 === void 0 ? void 0 : _a3[ref];
        const { schemaId } = this.opts;
        if (schema)
          _sch = new SchemaEnv({ schema, schemaId, root, baseId });
      }
      if (_sch === void 0)
        return;
      return root.refs[ref] = inlineOrCompile.call(this, _sch);
    }
    exports.resolveRef = resolveRef;
    function inlineOrCompile(sch) {
      if ((0, resolve_1.inlineRef)(sch.schema, this.opts.inlineRefs))
        return sch.schema;
      return sch.validate ? sch : compileSchema.call(this, sch);
    }
    function getCompilingSchema(schEnv) {
      for (const sch of this._compilations) {
        if (sameSchemaEnv(sch, schEnv))
          return sch;
      }
    }
    exports.getCompilingSchema = getCompilingSchema;
    function sameSchemaEnv(s12, s22) {
      return s12.schema === s22.schema && s12.root === s22.root && s12.baseId === s22.baseId;
    }
    function resolve8(root, ref) {
      let sch;
      while (typeof (sch = this.refs[ref]) == "string")
        ref = sch;
      return sch || this.schemas[ref] || resolveSchema.call(this, root, ref);
    }
    function resolveSchema(root, ref) {
      const p = this.opts.uriResolver.parse(ref);
      const refPath = (0, resolve_1._getFullPath)(this.opts.uriResolver, p);
      let baseId = (0, resolve_1.getFullPath)(this.opts.uriResolver, root.baseId, void 0);
      if (Object.keys(root.schema).length > 0 && refPath === baseId) {
        return getJsonPointer.call(this, p, root);
      }
      const id = (0, resolve_1.normalizeId)(refPath);
      const schOrRef = this.refs[id] || this.schemas[id];
      if (typeof schOrRef == "string") {
        const sch = resolveSchema.call(this, root, schOrRef);
        if (typeof (sch === null || sch === void 0 ? void 0 : sch.schema) !== "object")
          return;
        return getJsonPointer.call(this, p, sch);
      }
      if (typeof (schOrRef === null || schOrRef === void 0 ? void 0 : schOrRef.schema) !== "object")
        return;
      if (!schOrRef.validate)
        compileSchema.call(this, schOrRef);
      if (id === (0, resolve_1.normalizeId)(ref)) {
        const { schema } = schOrRef;
        const { schemaId } = this.opts;
        const schId = schema[schemaId];
        if (schId)
          baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        return new SchemaEnv({ schema, schemaId, root, baseId });
      }
      return getJsonPointer.call(this, p, schOrRef);
    }
    exports.resolveSchema = resolveSchema;
    var PREVENT_SCOPE_CHANGE = /* @__PURE__ */ new Set([
      "properties",
      "patternProperties",
      "enum",
      "dependencies",
      "definitions"
    ]);
    function getJsonPointer(parsedRef, { baseId, schema, root }) {
      var _a3;
      if (((_a3 = parsedRef.fragment) === null || _a3 === void 0 ? void 0 : _a3[0]) !== "/")
        return;
      for (const part of parsedRef.fragment.slice(1).split("/")) {
        if (typeof schema === "boolean")
          return;
        const partSchema = schema[(0, util_1.unescapeFragment)(part)];
        if (partSchema === void 0)
          return;
        schema = partSchema;
        const schId = typeof schema === "object" && schema[this.opts.schemaId];
        if (!PREVENT_SCOPE_CHANGE.has(part) && schId) {
          baseId = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schId);
        }
      }
      let env;
      if (typeof schema != "boolean" && schema.$ref && !(0, util_1.schemaHasRulesButRef)(schema, this.RULES)) {
        const $ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, schema.$ref);
        env = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env = env || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env.schema !== env.root.schema)
        return env;
      return void 0;
    }
  }
});

// node_modules/ajv/dist/refs/data.json
var require_data = __commonJS({
  "node_modules/ajv/dist/refs/data.json"(exports, module2) {
    module2.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: false
    };
  }
});

// node_modules/fast-uri/lib/utils.js
var require_utils = __commonJS({
  "node_modules/fast-uri/lib/utils.js"(exports, module2) {
    "use strict";
    var isUUID = RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu);
    var isIPv4 = 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 stringArrayToHexStripped(input) {
      let acc = "";
      let code = 0;
      let i2 = 0;
      for (i2 = 0; i2 < input.length; i2++) {
        code = input[i2].charCodeAt(0);
        if (code === 48) {
          continue;
        }
        if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
          return "";
        }
        acc += input[i2];
        break;
      }
      for (i2 += 1; i2 < input.length; i2++) {
        code = input[i2].charCodeAt(0);
        if (!(code >= 48 && code <= 57 || code >= 65 && code <= 70 || code >= 97 && code <= 102)) {
          return "";
        }
        acc += input[i2];
      }
      return acc;
    }
    var nonSimpleDomain = RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);
    function consumeIsZone(buffer) {
      buffer.length = 0;
      return true;
    }
    function consumeHextets(buffer, address, output) {
      if (buffer.length) {
        const hex3 = stringArrayToHexStripped(buffer);
        if (hex3 !== "") {
          address.push(hex3);
        } else {
          output.error = true;
          return false;
        }
        buffer.length = 0;
      }
      return true;
    }
    function getIPV6(input) {
      let tokenCount = 0;
      const output = { error: false, address: "", zone: "" };
      const address = [];
      const buffer = [];
      let endipv6Encountered = false;
      let endIpv6 = false;
      let consume = consumeHextets;
      for (let i2 = 0; i2 < input.length; i2++) {
        const cursor = input[i2];
        if (cursor === "[" || cursor === "]") {
          continue;
        }
        if (cursor === ":") {
          if (endipv6Encountered === true) {
            endIpv6 = true;
          }
          if (!consume(buffer, address, output)) {
            break;
          }
          if (++tokenCount > 7) {
            output.error = true;
            break;
          }
          if (i2 > 0 && input[i2 - 1] === ":") {
            endipv6Encountered = true;
          }
          address.push(":");
          continue;
        } else if (cursor === "%") {
          if (!consume(buffer, address, output)) {
            break;
          }
          consume = consumeIsZone;
        } else {
          buffer.push(cursor);
          continue;
        }
      }
      if (buffer.length) {
        if (consume === consumeIsZone) {
          output.zone = buffer.join("");
        } else if (endIpv6) {
          address.push(buffer.join(""));
        } else {
          address.push(stringArrayToHexStripped(buffer));
        }
      }
      output.address = address.join("");
      return output;
    }
    function normalizeIPv6(host) {
      if (findToken(host, ":") < 2) {
        return { host, isIPV6: false };
      }
      const ipv63 = getIPV6(host);
      if (!ipv63.error) {
        let newHost = ipv63.address;
        let escapedHost = ipv63.address;
        if (ipv63.zone) {
          newHost += "%" + ipv63.zone;
          escapedHost += "%25" + ipv63.zone;
        }
        return { host: newHost, isIPV6: true, escapedHost };
      } else {
        return { host, isIPV6: false };
      }
    }
    function findToken(str, token) {
      let ind = 0;
      for (let i2 = 0; i2 < str.length; i2++) {
        if (str[i2] === token) ind++;
      }
      return ind;
    }
    function removeDotSegments(path24) {
      let input = path24;
      const output = [];
      let nextSlash = -1;
      let len = 0;
      while (len = input.length) {
        if (len === 1) {
          if (input === ".") {
            break;
          } else if (input === "/") {
            output.push("/");
            break;
          } else {
            output.push(input);
            break;
          }
        } else if (len === 2) {
          if (input[0] === ".") {
            if (input[1] === ".") {
              break;
            } else if (input[1] === "/") {
              input = input.slice(2);
              continue;
            }
          } else if (input[0] === "/") {
            if (input[1] === "." || input[1] === "/") {
              output.push("/");
              break;
            }
          }
        } else if (len === 3) {
          if (input === "/..") {
            if (output.length !== 0) {
              output.pop();
            }
            output.push("/");
            break;
          }
        }
        if (input[0] === ".") {
          if (input[1] === ".") {
            if (input[2] === "/") {
              input = input.slice(3);
              continue;
            }
          } else if (input[1] === "/") {
            input = input.slice(2);
            continue;
          }
        } else if (input[0] === "/") {
          if (input[1] === ".") {
            if (input[2] === "/") {
              input = input.slice(2);
              continue;
            } else if (input[2] === ".") {
              if (input[3] === "/") {
                input = input.slice(3);
                if (output.length !== 0) {
                  output.pop();
                }
                continue;
              }
            }
          }
        }
        if ((nextSlash = input.indexOf("/", 1)) === -1) {
          output.push(input);
          break;
        } else {
          output.push(input.slice(0, nextSlash));
          input = input.slice(nextSlash);
        }
      }
      return output.join("");
    }
    function normalizeComponentEncoding(component, esc2) {
      const func = esc2 !== true ? escape : unescape;
      if (component.scheme !== void 0) {
        component.scheme = func(component.scheme);
      }
      if (component.userinfo !== void 0) {
        component.userinfo = func(component.userinfo);
      }
      if (component.host !== void 0) {
        component.host = func(component.host);
      }
      if (component.path !== void 0) {
        component.path = func(component.path);
      }
      if (component.query !== void 0) {
        component.query = func(component.query);
      }
      if (component.fragment !== void 0) {
        component.fragment = func(component.fragment);
      }
      return component;
    }
    function recomposeAuthority(component) {
      const uriTokens = [];
      if (component.userinfo !== void 0) {
        uriTokens.push(component.userinfo);
        uriTokens.push("@");
      }
      if (component.host !== void 0) {
        let host = unescape(component.host);
        if (!isIPv4(host)) {
          const ipV6res = normalizeIPv6(host);
          if (ipV6res.isIPV6 === true) {
            host = `[${ipV6res.escapedHost}]`;
          } else {
            host = component.host;
          }
        }
        uriTokens.push(host);
      }
      if (typeof component.port === "number" || typeof component.port === "string") {
        uriTokens.push(":");
        uriTokens.push(String(component.port));
      }
      return uriTokens.length ? uriTokens.join("") : void 0;
    }
    module2.exports = {
      nonSimpleDomain,
      recomposeAuthority,
      normalizeComponentEncoding,
      removeDotSegments,
      isIPv4,
      isUUID,
      normalizeIPv6,
      stringArrayToHexStripped
    };
  }
});

// node_modules/fast-uri/lib/schemes.js
var require_schemes = __commonJS({
  "node_modules/fast-uri/lib/schemes.js"(exports, module2) {
    "use strict";
    var { isUUID } = require_utils();
    var URN_REG = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
    var supportedSchemeNames = (
      /** @type {const} */
      [
        "http",
        "https",
        "ws",
        "wss",
        "urn",
        "urn:uuid"
      ]
    );
    function isValidSchemeName(name) {
      return supportedSchemeNames.indexOf(
        /** @type {*} */
        name
      ) !== -1;
    }
    function wsIsSecure(wsComponent) {
      if (wsComponent.secure === true) {
        return true;
      } else if (wsComponent.secure === false) {
        return false;
      } else if (wsComponent.scheme) {
        return wsComponent.scheme.length === 3 && (wsComponent.scheme[0] === "w" || wsComponent.scheme[0] === "W") && (wsComponent.scheme[1] === "s" || wsComponent.scheme[1] === "S") && (wsComponent.scheme[2] === "s" || wsComponent.scheme[2] === "S");
      } else {
        return false;
      }
    }
    function httpParse(component) {
      if (!component.host) {
        component.error = component.error || "HTTP URIs must have a host.";
      }
      return component;
    }
    function httpSerialize(component) {
      const secure = String(component.scheme).toLowerCase() === "https";
      if (component.port === (secure ? 443 : 80) || component.port === "") {
        component.port = void 0;
      }
      if (!component.path) {
        component.path = "/";
      }
      return component;
    }
    function wsParse(wsComponent) {
      wsComponent.secure = wsIsSecure(wsComponent);
      wsComponent.resourceName = (wsComponent.path || "/") + (wsComponent.query ? "?" + wsComponent.query : "");
      wsComponent.path = void 0;
      wsComponent.query = void 0;
      return wsComponent;
    }
    function wsSerialize(wsComponent) {
      if (wsComponent.port === (wsIsSecure(wsComponent) ? 443 : 80) || wsComponent.port === "") {
        wsComponent.port = void 0;
      }
      if (typeof wsComponent.secure === "boolean") {
        wsComponent.scheme = wsComponent.secure ? "wss" : "ws";
        wsComponent.secure = void 0;
      }
      if (wsComponent.resourceName) {
        const [path24, query] = wsComponent.resourceName.split("?");
        wsComponent.path = path24 && path24 !== "/" ? path24 : void 0;
        wsComponent.query = query;
        wsComponent.resourceName = void 0;
      }
      wsComponent.fragment = void 0;
      return wsComponent;
    }
    function urnParse(urnComponent, options) {
      if (!urnComponent.path) {
        urnComponent.error = "URN can not be parsed";
        return urnComponent;
      }
      const matches = urnComponent.path.match(URN_REG);
      if (matches) {
        const scheme = options.scheme || urnComponent.scheme || "urn";
        urnComponent.nid = matches[1].toLowerCase();
        urnComponent.nss = matches[2];
        const urnScheme = `${scheme}:${options.nid || urnComponent.nid}`;
        const schemeHandler = getSchemeHandler(urnScheme);
        urnComponent.path = void 0;
        if (schemeHandler) {
          urnComponent = schemeHandler.parse(urnComponent, options);
        }
      } else {
        urnComponent.error = urnComponent.error || "URN can not be parsed.";
      }
      return urnComponent;
    }
    function urnSerialize(urnComponent, options) {
      if (urnComponent.nid === void 0) {
        throw new Error("URN without nid cannot be serialized");
      }
      const scheme = options.scheme || urnComponent.scheme || "urn";
      const nid = urnComponent.nid.toLowerCase();
      const urnScheme = `${scheme}:${options.nid || nid}`;
      const schemeHandler = getSchemeHandler(urnScheme);
      if (schemeHandler) {
        urnComponent = schemeHandler.serialize(urnComponent, options);
      }
      const uriComponent = urnComponent;
      const nss = urnComponent.nss;
      uriComponent.path = `${nid || options.nid}:${nss}`;
      options.skipEscape = true;
      return uriComponent;
    }
    function urnuuidParse(urnComponent, options) {
      const uuidComponent = urnComponent;
      uuidComponent.uuid = uuidComponent.nss;
      uuidComponent.nss = void 0;
      if (!options.tolerant && (!uuidComponent.uuid || !isUUID(uuidComponent.uuid))) {
        uuidComponent.error = uuidComponent.error || "UUID is not valid.";
      }
      return uuidComponent;
    }
    function urnuuidSerialize(uuidComponent) {
      const urnComponent = uuidComponent;
      urnComponent.nss = (uuidComponent.uuid || "").toLowerCase();
      return urnComponent;
    }
    var http2 = (
      /** @type {SchemeHandler} */
      {
        scheme: "http",
        domainHost: true,
        parse: httpParse,
        serialize: httpSerialize
      }
    );
    var https2 = (
      /** @type {SchemeHandler} */
      {
        scheme: "https",
        domainHost: http2.domainHost,
        parse: httpParse,
        serialize: httpSerialize
      }
    );
    var ws = (
      /** @type {SchemeHandler} */
      {
        scheme: "ws",
        domainHost: true,
        parse: wsParse,
        serialize: wsSerialize
      }
    );
    var wss = (
      /** @type {SchemeHandler} */
      {
        scheme: "wss",
        domainHost: ws.domainHost,
        parse: ws.parse,
        serialize: ws.serialize
      }
    );
    var urn = (
      /** @type {SchemeHandler} */
      {
        scheme: "urn",
        parse: urnParse,
        serialize: urnSerialize,
        skipNormalize: true
      }
    );
    var urnuuid = (
      /** @type {SchemeHandler} */
      {
        scheme: "urn:uuid",
        parse: urnuuidParse,
        serialize: urnuuidSerialize,
        skipNormalize: true
      }
    );
    var SCHEMES = (
      /** @type {Record<SchemeName, SchemeHandler>} */
      {
        http: http2,
        https: https2,
        ws,
        wss,
        urn,
        "urn:uuid": urnuuid
      }
    );
    Object.setPrototypeOf(SCHEMES, null);
    function getSchemeHandler(scheme) {
      return scheme && (SCHEMES[
        /** @type {SchemeName} */
        scheme
      ] || SCHEMES[
        /** @type {SchemeName} */
        scheme.toLowerCase()
      ]) || void 0;
    }
    module2.exports = {
      wsIsSecure,
      SCHEMES,
      isValidSchemeName,
      getSchemeHandler
    };
  }
});

// node_modules/fast-uri/index.js
var require_fast_uri = __commonJS({
  "node_modules/fast-uri/index.js"(exports, module2) {
    "use strict";
    var { normalizeIPv6, removeDotSegments, recomposeAuthority, normalizeComponentEncoding, isIPv4, nonSimpleDomain } = require_utils();
    var { SCHEMES, getSchemeHandler } = require_schemes();
    function normalize3(uri, options) {
      if (typeof uri === "string") {
        uri = /** @type {T} */
        serialize(parse4(uri, options), options);
      } else if (typeof uri === "object") {
        uri = /** @type {T} */
        parse4(serialize(uri, options), options);
      }
      return uri;
    }
    function resolve8(baseURI, relativeURI, options) {
      const schemelessOptions = options ? Object.assign({ scheme: "null" }, options) : { scheme: "null" };
      const resolved = resolveComponent(parse4(baseURI, schemelessOptions), parse4(relativeURI, schemelessOptions), schemelessOptions, true);
      schemelessOptions.skipEscape = true;
      return serialize(resolved, schemelessOptions);
    }
    function resolveComponent(base, relative4, options, skipNormalization) {
      const target = {};
      if (!skipNormalization) {
        base = parse4(serialize(base, options), options);
        relative4 = parse4(serialize(relative4, options), options);
      }
      options = options || {};
      if (!options.tolerant && relative4.scheme) {
        target.scheme = relative4.scheme;
        target.userinfo = relative4.userinfo;
        target.host = relative4.host;
        target.port = relative4.port;
        target.path = removeDotSegments(relative4.path || "");
        target.query = relative4.query;
      } else {
        if (relative4.userinfo !== void 0 || relative4.host !== void 0 || relative4.port !== void 0) {
          target.userinfo = relative4.userinfo;
          target.host = relative4.host;
          target.port = relative4.port;
          target.path = removeDotSegments(relative4.path || "");
          target.query = relative4.query;
        } else {
          if (!relative4.path) {
            target.path = base.path;
            if (relative4.query !== void 0) {
              target.query = relative4.query;
            } else {
              target.query = base.query;
            }
          } else {
            if (relative4.path[0] === "/") {
              target.path = removeDotSegments(relative4.path);
            } else {
              if ((base.userinfo !== void 0 || base.host !== void 0 || base.port !== void 0) && !base.path) {
                target.path = "/" + relative4.path;
              } else if (!base.path) {
                target.path = relative4.path;
              } else {
                target.path = base.path.slice(0, base.path.lastIndexOf("/") + 1) + relative4.path;
              }
              target.path = removeDotSegments(target.path);
            }
            target.query = relative4.query;
          }
          target.userinfo = base.userinfo;
          target.host = base.host;
          target.port = base.port;
        }
        target.scheme = base.scheme;
      }
      target.fragment = relative4.fragment;
      return target;
    }
    function equal(uriA, uriB, options) {
      if (typeof uriA === "string") {
        uriA = unescape(uriA);
        uriA = serialize(normalizeComponentEncoding(parse4(uriA, options), true), { ...options, skipEscape: true });
      } else if (typeof uriA === "object") {
        uriA = serialize(normalizeComponentEncoding(uriA, true), { ...options, skipEscape: true });
      }
      if (typeof uriB === "string") {
        uriB = unescape(uriB);
        uriB = serialize(normalizeComponentEncoding(parse4(uriB, options), true), { ...options, skipEscape: true });
      } else if (typeof uriB === "object") {
        uriB = serialize(normalizeComponentEncoding(uriB, true), { ...options, skipEscape: true });
      }
      return uriA.toLowerCase() === uriB.toLowerCase();
    }
    function serialize(cmpts, opts) {
      const component = {
        host: cmpts.host,
        scheme: cmpts.scheme,
        userinfo: cmpts.userinfo,
        port: cmpts.port,
        path: cmpts.path,
        query: cmpts.query,
        nid: cmpts.nid,
        nss: cmpts.nss,
        uuid: cmpts.uuid,
        fragment: cmpts.fragment,
        reference: cmpts.reference,
        resourceName: cmpts.resourceName,
        secure: cmpts.secure,
        error: ""
      };
      const options = Object.assign({}, opts);
      const uriTokens = [];
      const schemeHandler = getSchemeHandler(options.scheme || component.scheme);
      if (schemeHandler && schemeHandler.serialize) schemeHandler.serialize(component, options);
      if (component.path !== void 0) {
        if (!options.skipEscape) {
          component.path = escape(component.path);
          if (component.scheme !== void 0) {
            component.path = component.path.split("%3A").join(":");
          }
        } else {
          component.path = unescape(component.path);
        }
      }
      if (options.reference !== "suffix" && component.scheme) {
        uriTokens.push(component.scheme, ":");
      }
      const authority = recomposeAuthority(component);
      if (authority !== void 0) {
        if (options.reference !== "suffix") {
          uriTokens.push("//");
        }
        uriTokens.push(authority);
        if (component.path && component.path[0] !== "/") {
          uriTokens.push("/");
        }
      }
      if (component.path !== void 0) {
        let s4 = component.path;
        if (!options.absolutePath && (!schemeHandler || !schemeHandler.absolutePath)) {
          s4 = removeDotSegments(s4);
        }
        if (authority === void 0 && s4[0] === "/" && s4[1] === "/") {
          s4 = "/%2F" + s4.slice(2);
        }
        uriTokens.push(s4);
      }
      if (component.query !== void 0) {
        uriTokens.push("?", component.query);
      }
      if (component.fragment !== void 0) {
        uriTokens.push("#", component.fragment);
      }
      return uriTokens.join("");
    }
    var URI_PARSE = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
    function parse4(uri, opts) {
      const options = Object.assign({}, opts);
      const parsed = {
        scheme: void 0,
        userinfo: void 0,
        host: "",
        port: void 0,
        path: "",
        query: void 0,
        fragment: void 0
      };
      let isIP = false;
      if (options.reference === "suffix") {
        if (options.scheme) {
          uri = options.scheme + ":" + uri;
        } else {
          uri = "//" + uri;
        }
      }
      const matches = uri.match(URI_PARSE);
      if (matches) {
        parsed.scheme = matches[1];
        parsed.userinfo = matches[3];
        parsed.host = matches[4];
        parsed.port = parseInt(matches[5], 10);
        parsed.path = matches[6] || "";
        parsed.query = matches[7];
        parsed.fragment = matches[8];
        if (isNaN(parsed.port)) {
          parsed.port = matches[5];
        }
        if (parsed.host) {
          const ipv4result = isIPv4(parsed.host);
          if (ipv4result === false) {
            const ipv6result = normalizeIPv6(parsed.host);
            parsed.host = ipv6result.host.toLowerCase();
            isIP = ipv6result.isIPV6;
          } else {
            isIP = true;
          }
        }
        if (parsed.scheme === void 0 && parsed.userinfo === void 0 && parsed.host === void 0 && parsed.port === void 0 && parsed.query === void 0 && !parsed.path) {
          parsed.reference = "same-document";
        } else if (parsed.scheme === void 0) {
          parsed.reference = "relative";
        } else if (parsed.fragment === void 0) {
          parsed.reference = "absolute";
        } else {
          parsed.reference = "uri";
        }
        if (options.reference && options.reference !== "suffix" && options.reference !== parsed.reference) {
          parsed.error = parsed.error || "URI is not a " + options.reference + " reference.";
        }
        const schemeHandler = getSchemeHandler(options.scheme || parsed.scheme);
        if (!options.unicodeSupport && (!schemeHandler || !schemeHandler.unicodeSupport)) {
          if (parsed.host && (options.domainHost || schemeHandler && schemeHandler.domainHost) && isIP === false && nonSimpleDomain(parsed.host)) {
            try {
              parsed.host = URL.domainToASCII(parsed.host.toLowerCase());
            } catch (e2) {
              parsed.error = parsed.error || "Host's domain name can not be converted to ASCII: " + e2;
            }
          }
        }
        if (!schemeHandler || schemeHandler && !schemeHandler.skipNormalize) {
          if (uri.indexOf("%") !== -1) {
            if (parsed.scheme !== void 0) {
              parsed.scheme = unescape(parsed.scheme);
            }
            if (parsed.host !== void 0) {
              parsed.host = unescape(parsed.host);
            }
          }
          if (parsed.path) {
            parsed.path = escape(unescape(parsed.path));
          }
          if (parsed.fragment) {
            parsed.fragment = encodeURI(decodeURIComponent(parsed.fragment));
          }
        }
        if (schemeHandler && schemeHandler.parse) {
          schemeHandler.parse(parsed, options);
        }
      } else {
        parsed.error = parsed.error || "URI can not be parsed.";
      }
      return parsed;
    }
    var fastUri = {
      SCHEMES,
      normalize: normalize3,
      resolve: resolve8,
      resolveComponent,
      equal,
      serialize,
      parse: parse4
    };
    module2.exports = fastUri;
    module2.exports.default = fastUri;
    module2.exports.fastUri = fastUri;
  }
});

// node_modules/ajv/dist/runtime/uri.js
var require_uri = __commonJS({
  "node_modules/ajv/dist/runtime/uri.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var uri = require_fast_uri();
    uri.code = 'require("ajv/dist/runtime/uri").default';
    exports.default = uri;
  }
});

// node_modules/ajv/dist/core.js
var require_core = __commonJS({
  "node_modules/ajv/dist/core.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = void 0;
    var validate_1 = require_validate();
    Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = require_codegen();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    var validation_error_1 = require_validation_error();
    var ref_error_1 = require_ref_error();
    var rules_1 = require_rules();
    var compile_1 = require_compile();
    var codegen_2 = require_codegen();
    var resolve_1 = require_resolve();
    var dataType_1 = require_dataType();
    var util_1 = require_util();
    var $dataRefSchema = require_data();
    var uri_1 = require_uri();
    var defaultRegExp = (str, flags) => new RegExp(str, flags);
    defaultRegExp.code = "new RegExp";
    var META_IGNORE_OPTIONS = ["removeAdditional", "useDefaults", "coerceTypes"];
    var EXT_SCOPE_NAMES = /* @__PURE__ */ new Set([
      "validate",
      "serialize",
      "parse",
      "wrapper",
      "root",
      "schema",
      "keyword",
      "pattern",
      "formats",
      "validate$data",
      "func",
      "obj",
      "Error"
    ]);
    var removedOptions = {
      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."
    };
    var deprecatedOptions = {
      ignoreKeywordsWithRef: "",
      jsPropertySyntax: "",
      unicode: '"minLength"/"maxLength" account for unicode characters by default.'
    };
    var MAX_EXPRESSION = 200;
    function requiredOptions(o2) {
      var _a3, _b2, _c, _d2, _e, _f, _g, _h, _j2, _k, _l, _m, _o, _p2, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z2, _02;
      const s4 = o2.strict;
      const _optz = (_a3 = o2.code) === null || _a3 === void 0 ? void 0 : _a3.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c = (_b2 = o2.code) === null || _b2 === void 0 ? void 0 : _b2.regExp) !== null && _c !== void 0 ? _c : defaultRegExp;
      const uriResolver = (_d2 = o2.uriResolver) !== null && _d2 !== void 0 ? _d2 : uri_1.default;
      return {
        strictSchema: (_f = (_e = o2.strictSchema) !== null && _e !== void 0 ? _e : s4) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o2.strictNumbers) !== null && _g !== void 0 ? _g : s4) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j2 = o2.strictTypes) !== null && _j2 !== void 0 ? _j2 : s4) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o2.strictTuples) !== null && _l !== void 0 ? _l : s4) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p2 = (_o = o2.strictRequired) !== null && _o !== void 0 ? _o : s4) !== null && _p2 !== void 0 ? _p2 : false,
        code: o2.code ? { ...o2.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o2.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o2.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o2.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o2.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o2.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o2.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o2.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o2.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o2.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z2 = o2.unicodeRegExp) !== null && _z2 !== void 0 ? _z2 : true,
        int32range: (_02 = o2.int32range) !== null && _02 !== void 0 ? _02 : true,
        uriResolver
      };
    }
    var Ajv2 = class {
      constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = {};
        this._compilations = /* @__PURE__ */ new Set();
        this._loading = {};
        this._cache = /* @__PURE__ */ new Map();
        opts = this.opts = { ...opts, ...requiredOptions(opts) };
        const { es5, lines } = this.opts.code;
        this.scope = new codegen_2.ValueScope({ scope: {}, prefixes: EXT_SCOPE_NAMES, es5, lines });
        this.logger = getLogger(opts.logger);
        const formatOpt = opts.validateFormats;
        opts.validateFormats = false;
        this.RULES = (0, rules_1.getRules)();
        checkOptions.call(this, removedOptions, opts, "NOT SUPPORTED");
        checkOptions.call(this, deprecatedOptions, opts, "DEPRECATED", "warn");
        this._metaOpts = getMetaSchemaOptions.call(this);
        if (opts.formats)
          addInitialFormats.call(this);
        this._addVocabularies();
        this._addDefaultMetaSchema();
        if (opts.keywords)
          addInitialKeywords.call(this, opts.keywords);
        if (typeof opts.meta == "object")
          this.addMetaSchema(opts.meta);
        addInitialSchemas.call(this);
        opts.validateFormats = formatOpt;
      }
      _addVocabularies() {
        this.addKeyword("$async");
      }
      _addDefaultMetaSchema() {
        const { $data, meta: meta3, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
          _dataRefSchema = { ...$dataRefSchema };
          _dataRefSchema.id = _dataRefSchema.$id;
          delete _dataRefSchema.$id;
        }
        if (meta3 && $data)
          this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
      }
      defaultMeta() {
        const { meta: meta3, schemaId } = this.opts;
        return this.opts.defaultMeta = typeof meta3 == "object" ? meta3[schemaId] || meta3 : void 0;
      }
      validate(schemaKeyRef, data) {
        let v2;
        if (typeof schemaKeyRef == "string") {
          v2 = this.getSchema(schemaKeyRef);
          if (!v2)
            throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        } else {
          v2 = this.compile(schemaKeyRef);
        }
        const valid = v2(data);
        if (!("$async" in v2))
          this.errors = v2.errors;
        return valid;
      }
      compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return sch.validate || this._compileSchemaEnv(sch);
      }
      compileAsync(schema, meta3) {
        if (typeof this.opts.loadSchema != "function") {
          throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta3);
        async function runCompileAsync(_schema, _meta) {
          await loadMetaSchema.call(this, _schema.$schema);
          const sch = this._addSchema(_schema, _meta);
          return sch.validate || _compileAsync.call(this, sch);
        }
        async function loadMetaSchema($ref) {
          if ($ref && !this.getSchema($ref)) {
            await runCompileAsync.call(this, { $ref }, true);
          }
        }
        async function _compileAsync(sch) {
          try {
            return this._compileSchemaEnv(sch);
          } catch (e2) {
            if (!(e2 instanceof ref_error_1.default))
              throw e2;
            checkLoaded.call(this, e2);
            await loadMissingSchema.call(this, e2.missingSchema);
            return _compileAsync.call(this, sch);
          }
        }
        function checkLoaded({ missingSchema: ref, missingRef }) {
          if (this.refs[ref]) {
            throw new Error(`AnySchema ${ref} is loaded but ${missingRef} cannot be resolved`);
          }
        }
        async function loadMissingSchema(ref) {
          const _schema = await _loadSchema.call(this, ref);
          if (!this.refs[ref])
            await loadMetaSchema.call(this, _schema.$schema);
          if (!this.refs[ref])
            this.addSchema(_schema, ref, meta3);
        }
        async function _loadSchema(ref) {
          const p = this._loading[ref];
          if (p)
            return p;
          try {
            return await (this._loading[ref] = loadSchema(ref));
          } finally {
            delete this._loading[ref];
          }
        }
      }
      // Adds schema to the instance
      addSchema(schema, key, _meta, _validateSchema = this.opts.validateSchema) {
        if (Array.isArray(schema)) {
          for (const sch of schema)
            this.addSchema(sch, void 0, _meta, _validateSchema);
          return this;
        }
        let id;
        if (typeof schema === "object") {
          const { schemaId } = this.opts;
          id = schema[schemaId];
          if (id !== void 0 && typeof id != "string") {
            throw new Error(`schema ${schemaId} must be string`);
          }
        }
        key = (0, resolve_1.normalizeId)(key || id);
        this._checkUnique(key);
        this.schemas[key] = this._addSchema(schema, _meta, key, _validateSchema, true);
        return this;
      }
      // Add schema that will be used to validate other schemas
      // options in META_IGNORE_OPTIONS are alway set to false
      addMetaSchema(schema, key, _validateSchema = this.opts.validateSchema) {
        this.addSchema(schema, key, true, _validateSchema);
        return this;
      }
      //  Validate schema against its meta-schema
      validateSchema(schema, throwOrLogError) {
        if (typeof schema == "boolean")
          return true;
        let $schema;
        $schema = schema.$schema;
        if ($schema !== void 0 && typeof $schema != "string") {
          throw new Error("$schema must be a string");
        }
        $schema = $schema || this.opts.defaultMeta || this.defaultMeta();
        if (!$schema) {
          this.logger.warn("meta-schema not available");
          this.errors = null;
          return true;
        }
        const valid = this.validate($schema, schema);
        if (!valid && throwOrLogError) {
          const message = "schema is invalid: " + this.errorsText();
          if (this.opts.validateSchema === "log")
            this.logger.error(message);
          else
            throw new Error(message);
        }
        return valid;
      }
      // Get compiled schema by `key` or `ref`.
      // (`key` that was passed to `addSchema` or full schema reference - `schema.$id` or resolved id)
      getSchema(keyRef) {
        let sch;
        while (typeof (sch = getSchEnv.call(this, keyRef)) == "string")
          keyRef = sch;
        if (sch === void 0) {
          const { schemaId } = this.opts;
          const root = new compile_1.SchemaEnv({ schema: {}, schemaId });
          sch = compile_1.resolveSchema.call(this, root, keyRef);
          if (!sch)
            return;
          this.refs[keyRef] = sch;
        }
        return sch.validate || this._compileSchemaEnv(sch);
      }
      // Remove cached schema(s).
      // If no parameter is passed all schemas but meta-schemas are removed.
      // If RegExp is passed all schemas with key/id matching pattern but meta-schemas are removed.
      // Even if schema is referenced by other schemas it still can be removed as other schemas have local references.
      removeSchema(schemaKeyRef) {
        if (schemaKeyRef instanceof RegExp) {
          this._removeAllSchemas(this.schemas, schemaKeyRef);
          this._removeAllSchemas(this.refs, schemaKeyRef);
          return this;
        }
        switch (typeof schemaKeyRef) {
          case "undefined":
            this._removeAllSchemas(this.schemas);
            this._removeAllSchemas(this.refs);
            this._cache.clear();
            return this;
          case "string": {
            const sch = getSchEnv.call(this, schemaKeyRef);
            if (typeof sch == "object")
              this._cache.delete(sch.schema);
            delete this.schemas[schemaKeyRef];
            delete this.refs[schemaKeyRef];
            return this;
          }
          case "object": {
            const cacheKey = schemaKeyRef;
            this._cache.delete(cacheKey);
            let id = schemaKeyRef[this.opts.schemaId];
            if (id) {
              id = (0, resolve_1.normalizeId)(id);
              delete this.schemas[id];
              delete this.refs[id];
            }
            return this;
          }
          default:
            throw new Error("ajv.removeSchema: invalid parameter");
        }
      }
      // add "vocabulary" - a collection of keywords
      addVocabulary(definitions) {
        for (const def of definitions)
          this.addKeyword(def);
        return this;
      }
      addKeyword(kwdOrDef, def) {
        let keyword;
        if (typeof kwdOrDef == "string") {
          keyword = kwdOrDef;
          if (typeof def == "object") {
            this.logger.warn("these parameters are deprecated, see docs for addKeyword");
            def.keyword = keyword;
          }
        } else if (typeof kwdOrDef == "object" && def === void 0) {
          def = kwdOrDef;
          keyword = def.keyword;
          if (Array.isArray(keyword) && !keyword.length) {
            throw new Error("addKeywords: keyword must be string or non-empty array");
          }
        } else {
          throw new Error("invalid addKeywords parameters");
        }
        checkKeyword.call(this, keyword, def);
        if (!def) {
          (0, util_1.eachItem)(keyword, (kwd) => addRule.call(this, kwd));
          return this;
        }
        keywordMetaschema.call(this, def);
        const definition = {
          ...def,
          type: (0, dataType_1.getJSONTypes)(def.type),
          schemaType: (0, dataType_1.getJSONTypes)(def.schemaType)
        };
        (0, util_1.eachItem)(keyword, definition.type.length === 0 ? (k10) => addRule.call(this, k10, definition) : (k10) => definition.type.forEach((t2) => addRule.call(this, k10, definition, t2)));
        return this;
      }
      getKeyword(keyword) {
        const rule = this.RULES.all[keyword];
        return typeof rule == "object" ? rule.definition : !!rule;
      }
      // Remove keyword
      removeKeyword(keyword) {
        const { RULES } = this;
        delete RULES.keywords[keyword];
        delete RULES.all[keyword];
        for (const group of RULES.rules) {
          const i2 = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i2 >= 0)
            group.rules.splice(i2, 1);
        }
        return this;
      }
      // Add format
      addFormat(name, format) {
        if (typeof format == "string")
          format = new RegExp(format);
        this.formats[name] = format;
        return this;
      }
      errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
        if (!errors || errors.length === 0)
          return "No errors";
        return errors.map((e2) => `${dataVar}${e2.instancePath} ${e2.message}`).reduce((text, msg) => text + separator + msg);
      }
      $dataMetaSchema(metaSchema, keywordsJsonPointers) {
        const rules = this.RULES.all;
        metaSchema = JSON.parse(JSON.stringify(metaSchema));
        for (const jsonPointer of keywordsJsonPointers) {
          const segments = jsonPointer.split("/").slice(1);
          let keywords = metaSchema;
          for (const seg of segments)
            keywords = keywords[seg];
          for (const key in rules) {
            const rule = rules[key];
            if (typeof rule != "object")
              continue;
            const { $data } = rule.definition;
            const schema = keywords[key];
            if ($data && schema)
              keywords[key] = schemaOrData(schema);
          }
        }
        return metaSchema;
      }
      _removeAllSchemas(schemas, regex) {
        for (const keyRef in schemas) {
          const sch = schemas[keyRef];
          if (!regex || regex.test(keyRef)) {
            if (typeof sch == "string") {
              delete schemas[keyRef];
            } else if (sch && !sch.meta) {
              this._cache.delete(sch.schema);
              delete schemas[keyRef];
            }
          }
        }
      }
      _addSchema(schema, meta3, baseId, validateSchema = this.opts.validateSchema, addSchema = this.opts.addUsedSchema) {
        let id;
        const { schemaId } = this.opts;
        if (typeof schema == "object") {
          id = schema[schemaId];
        } else {
          if (this.opts.jtd)
            throw new Error("schema must be object");
          else if (typeof schema != "boolean")
            throw new Error("schema must be object or boolean");
        }
        let sch = this._cache.get(schema);
        if (sch !== void 0)
          return sch;
        baseId = (0, resolve_1.normalizeId)(id || baseId);
        const localRefs = resolve_1.getSchemaRefs.call(this, schema, baseId);
        sch = new compile_1.SchemaEnv({ schema, schemaId, meta: meta3, baseId, localRefs });
        this._cache.set(sch.schema, sch);
        if (addSchema && !baseId.startsWith("#")) {
          if (baseId)
            this._checkUnique(baseId);
          this.refs[baseId] = sch;
        }
        if (validateSchema)
          this.validateSchema(schema, true);
        return sch;
      }
      _checkUnique(id) {
        if (this.schemas[id] || this.refs[id]) {
          throw new Error(`schema with key or id "${id}" already exists`);
        }
      }
      _compileSchemaEnv(sch) {
        if (sch.meta)
          this._compileMetaSchema(sch);
        else
          compile_1.compileSchema.call(this, sch);
        if (!sch.validate)
          throw new Error("ajv implementation error");
        return sch.validate;
      }
      _compileMetaSchema(sch) {
        const currentOpts = this.opts;
        this.opts = this._metaOpts;
        try {
          compile_1.compileSchema.call(this, sch);
        } finally {
          this.opts = currentOpts;
        }
      }
    };
    Ajv2.ValidationError = validation_error_1.default;
    Ajv2.MissingRefError = ref_error_1.default;
    exports.default = Ajv2;
    function checkOptions(checkOpts, options, msg, log = "error") {
      for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
          this.logger[log](`${msg}: option ${key}. ${checkOpts[opt]}`);
      }
    }
    function getSchEnv(keyRef) {
      keyRef = (0, resolve_1.normalizeId)(keyRef);
      return this.schemas[keyRef] || this.refs[keyRef];
    }
    function addInitialSchemas() {
      const optsSchemas = this.opts.schemas;
      if (!optsSchemas)
        return;
      if (Array.isArray(optsSchemas))
        this.addSchema(optsSchemas);
      else
        for (const key in optsSchemas)
          this.addSchema(optsSchemas[key], key);
    }
    function addInitialFormats() {
      for (const name in this.opts.formats) {
        const format = this.opts.formats[name];
        if (format)
          this.addFormat(name, format);
      }
    }
    function addInitialKeywords(defs) {
      if (Array.isArray(defs)) {
        this.addVocabulary(defs);
        return;
      }
      this.logger.warn("keywords option as map is deprecated, pass array");
      for (const keyword in defs) {
        const def = defs[keyword];
        if (!def.keyword)
          def.keyword = keyword;
        this.addKeyword(def);
      }
    }
    function getMetaSchemaOptions() {
      const metaOpts = { ...this.opts };
      for (const opt of META_IGNORE_OPTIONS)
        delete metaOpts[opt];
      return metaOpts;
    }
    var noLogs = { log() {
    }, warn() {
    }, error() {
    } };
    function getLogger(logger) {
      if (logger === false)
        return noLogs;
      if (logger === void 0)
        return console;
      if (logger.log && logger.warn && logger.error)
        return logger;
      throw new Error("logger must implement log, warn and error methods");
    }
    var KEYWORD_NAME = /^[a-z_$][a-z0-9_$:-]*$/i;
    function checkKeyword(keyword, def) {
      const { RULES } = this;
      (0, util_1.eachItem)(keyword, (kwd) => {
        if (RULES.keywords[kwd])
          throw new Error(`Keyword ${kwd} is already defined`);
        if (!KEYWORD_NAME.test(kwd))
          throw new Error(`Keyword ${kwd} has invalid name`);
      });
      if (!def)
        return;
      if (def.$data && !("code" in def || "validate" in def)) {
        throw new Error('$data keyword must have "code" or "validate" function');
      }
    }
    function addRule(keyword, definition, dataType) {
      var _a3;
      const post = definition === null || definition === void 0 ? void 0 : definition.post;
      if (dataType && post)
        throw new Error('keyword with "post" flag cannot have "type"');
      const { RULES } = this;
      let ruleGroup = post ? RULES.post : RULES.rules.find(({ type: t2 }) => t2 === dataType);
      if (!ruleGroup) {
        ruleGroup = { type: dataType, rules: [] };
        RULES.rules.push(ruleGroup);
      }
      RULES.keywords[keyword] = true;
      if (!definition)
        return;
      const rule = {
        keyword,
        definition: {
          ...definition,
          type: (0, dataType_1.getJSONTypes)(definition.type),
          schemaType: (0, dataType_1.getJSONTypes)(definition.schemaType)
        }
      };
      if (definition.before)
        addBeforeRule.call(this, ruleGroup, rule, definition.before);
      else
        ruleGroup.rules.push(rule);
      RULES.all[keyword] = rule;
      (_a3 = definition.implements) === null || _a3 === void 0 ? void 0 : _a3.forEach((kwd) => this.addKeyword(kwd));
    }
    function addBeforeRule(ruleGroup, rule, before) {
      const i2 = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i2 >= 0) {
        ruleGroup.rules.splice(i2, 0, rule);
      } else {
        ruleGroup.rules.push(rule);
        this.logger.warn(`rule ${before} is not defined`);
      }
    }
    function keywordMetaschema(def) {
      let { metaSchema } = def;
      if (metaSchema === void 0)
        return;
      if (def.$data && this.opts.$data)
        metaSchema = schemaOrData(metaSchema);
      def.validateSchema = this.compile(metaSchema, true);
    }
    var $dataRef = {
      $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"
    };
    function schemaOrData(schema) {
      return { anyOf: [schema, $dataRef] };
    }
  }
});

// node_modules/ajv/dist/vocabularies/core/id.js
var require_id = __commonJS({
  "node_modules/ajv/dist/vocabularies/core/id.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var def = {
      keyword: "id",
      code() {
        throw new Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref = __commonJS({
  "node_modules/ajv/dist/vocabularies/core/ref.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.callRef = exports.getValidate = void 0;
    var ref_error_1 = require_ref_error();
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var compile_1 = require_compile();
    var util_1 = require_util();
    var def = {
      keyword: "$ref",
      schemaType: "string",
      code(cxt) {
        const { gen, schema: $ref, it } = cxt;
        const { baseId, schemaEnv: env, validateName, opts, self: self2 } = it;
        const { root } = env;
        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
          return callRootRef();
        const schOrEnv = compile_1.resolveRef.call(self2, root, baseId, $ref);
        if (schOrEnv === void 0)
          throw new ref_error_1.default(it.opts.uriResolver, baseId, $ref);
        if (schOrEnv instanceof compile_1.SchemaEnv)
          return callValidate(schOrEnv);
        return inlineRefSchema(schOrEnv);
        function callRootRef() {
          if (env === root)
            return callRef(cxt, validateName, env, env.$async);
          const rootName = gen.scopeValue("root", { ref: root });
          return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
        }
        function callValidate(sch) {
          const v2 = getValidate(cxt, sch);
          callRef(cxt, v2, sch, sch.$async);
        }
        function inlineRefSchema(sch) {
          const schName = gen.scopeValue("schema", opts.code.source === true ? { ref: sch, code: (0, codegen_1.stringify)(sch) } : { ref: sch });
          const valid = gen.name("valid");
          const schCxt = cxt.subschema({
            schema: sch,
            dataTypes: [],
            schemaPath: codegen_1.nil,
            topSchemaRef: schName,
            errSchemaPath: $ref
          }, valid);
          cxt.mergeEvaluated(schCxt);
          cxt.ok(valid);
        }
      }
    };
    function getValidate(cxt, sch) {
      const { gen } = cxt;
      return sch.validate ? gen.scopeValue("validate", { ref: sch.validate }) : (0, codegen_1._)`${gen.scopeValue("wrapper", { ref: sch })}.validate`;
    }
    exports.getValidate = getValidate;
    function callRef(cxt, v2, sch, $async) {
      const { gen, it } = cxt;
      const { allErrors, schemaEnv: env, opts } = it;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env.$async)
          throw new Error("async schema referenced by sync schema");
        const valid = gen.let("valid");
        gen.try(() => {
          gen.code((0, codegen_1._)`await ${(0, code_1.callValidateCode)(cxt, v2, passCxt)}`);
          addEvaluatedFrom(v2);
          if (!allErrors)
            gen.assign(valid, true);
        }, (e2) => {
          gen.if((0, codegen_1._)`!(${e2} instanceof ${it.ValidationError})`, () => gen.throw(e2));
          addErrorsFrom(e2);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v2, passCxt), () => addEvaluatedFrom(v2), () => addErrorsFrom(v2));
      }
      function addErrorsFrom(source) {
        const errs = (0, codegen_1._)`${source}.errors`;
        gen.assign(names_1.default.vErrors, (0, codegen_1._)`${names_1.default.vErrors} === null ? ${errs} : ${names_1.default.vErrors}.concat(${errs})`);
        gen.assign(names_1.default.errors, (0, codegen_1._)`${names_1.default.vErrors}.length`);
      }
      function addEvaluatedFrom(source) {
        var _a3;
        if (!it.opts.unevaluated)
          return;
        const schEvaluated = (_a3 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a3 === void 0 ? void 0 : _a3.evaluated;
        if (it.props !== true) {
          if (schEvaluated && !schEvaluated.dynamicProps) {
            if (schEvaluated.props !== void 0) {
              it.props = util_1.mergeEvaluated.props(gen, schEvaluated.props, it.props);
            }
          } else {
            const props = gen.var("props", (0, codegen_1._)`${source}.evaluated.props`);
            it.props = util_1.mergeEvaluated.props(gen, props, it.props, codegen_1.Name);
          }
        }
        if (it.items !== true) {
          if (schEvaluated && !schEvaluated.dynamicItems) {
            if (schEvaluated.items !== void 0) {
              it.items = util_1.mergeEvaluated.items(gen, schEvaluated.items, it.items);
            }
          } else {
            const items = gen.var("items", (0, codegen_1._)`${source}.evaluated.items`);
            it.items = util_1.mergeEvaluated.items(gen, items, it.items, codegen_1.Name);
          }
        }
      }
    }
    exports.callRef = callRef;
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/core/index.js
var require_core2 = __commonJS({
  "node_modules/ajv/dist/vocabularies/core/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var id_1 = require_id();
    var ref_1 = require_ref();
    var core = [
      "$schema",
      "$id",
      "$defs",
      "$vocabulary",
      { keyword: "$comment" },
      "definitions",
      id_1.default,
      ref_1.default
    ];
    exports.default = core;
  }
});

// node_modules/ajv/dist/vocabularies/validation/limitNumber.js
var require_limitNumber = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/limitNumber.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var ops = codegen_1.operators;
    var KWDs = {
      maximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
      minimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
      exclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
      exclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
    };
    var error48 = {
      message: ({ keyword, schemaCode }) => (0, codegen_1.str)`must be ${KWDs[keyword].okStr} ${schemaCode}`,
      params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
    };
    var def = {
      keyword: Object.keys(KWDs),
      type: "number",
      schemaType: "number",
      $data: true,
      error: error48,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/multipleOf.js
var require_multipleOf = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error48 = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must be multiple of ${schemaCode}`,
      params: ({ schemaCode }) => (0, codegen_1._)`{multipleOf: ${schemaCode}}`
    };
    var def = {
      keyword: "multipleOf",
      type: "number",
      schemaType: "number",
      $data: true,
      error: error48,
      code(cxt) {
        const { gen, data, schemaCode, it } = cxt;
        const prec = it.opts.multipleOfPrecision;
        const res = gen.let("res");
        const invalid = prec ? (0, codegen_1._)`Math.abs(Math.round(${res}) - ${res}) > 1e-${prec}` : (0, codegen_1._)`${res} !== parseInt(${res})`;
        cxt.fail$data((0, codegen_1._)`(${schemaCode} === 0 || (${res} = ${data}/${schemaCode}, ${invalid}))`);
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/runtime/ucs2length.js
var require_ucs2length = __commonJS({
  "node_modules/ajv/dist/runtime/ucs2length.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    function ucs2length(str) {
      const len = str.length;
      let length = 0;
      let pos = 0;
      let value;
      while (pos < len) {
        length++;
        value = str.charCodeAt(pos++);
        if (value >= 55296 && value <= 56319 && pos < len) {
          value = str.charCodeAt(pos);
          if ((value & 64512) === 56320)
            pos++;
        }
      }
      return length;
    }
    exports.default = ucs2length;
    ucs2length.code = 'require("ajv/dist/runtime/ucs2length").default';
  }
});

// node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/limitLength.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var ucs2length_1 = require_ucs2length();
    var error48 = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxLength" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} characters`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    var def = {
      keyword: ["maxLength", "minLength"],
      type: "string",
      schemaType: "number",
      $data: true,
      error: error48,
      code(cxt) {
        const { keyword, data, schemaCode, it } = cxt;
        const op = keyword === "maxLength" ? codegen_1.operators.GT : codegen_1.operators.LT;
        const len = it.opts.unicode === false ? (0, codegen_1._)`${data}.length` : (0, codegen_1._)`${(0, util_1.useFunc)(cxt.gen, ucs2length_1.default)}(${data})`;
        cxt.fail$data((0, codegen_1._)`${len} ${op} ${schemaCode}`);
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/pattern.js
var require_pattern = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/pattern.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var util_1 = require_util();
    var codegen_1 = require_codegen();
    var error48 = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must match pattern "${schemaCode}"`,
      params: ({ schemaCode }) => (0, codegen_1._)`{pattern: ${schemaCode}}`
    };
    var def = {
      keyword: "pattern",
      type: "string",
      schemaType: "string",
      $data: true,
      error: error48,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const u = it.opts.unicodeRegExp ? "u" : "";
        if ($data) {
          const { regExp } = it.opts.code;
          const regExpCode = regExp.code === "new RegExp" ? (0, codegen_1._)`new RegExp` : (0, util_1.useFunc)(gen, regExp);
          const valid = gen.let("valid");
          gen.try(() => gen.assign(valid, (0, codegen_1._)`${regExpCode}(${schemaCode}, ${u}).test(${data})`), () => gen.assign(valid, false));
          cxt.fail$data((0, codegen_1._)`!${valid}`);
        } else {
          const regExp = (0, code_1.usePattern)(cxt, schema);
          cxt.fail$data((0, codegen_1._)`!${regExp}.test(${data})`);
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/limitProperties.js
var require_limitProperties = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error48 = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxProperties" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} properties`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    var def = {
      keyword: ["maxProperties", "minProperties"],
      type: "object",
      schemaType: "number",
      $data: true,
      error: error48,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxProperties" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`Object.keys(${data}).length ${op} ${schemaCode}`);
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/required.js
var require_required = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/required.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var error48 = {
      message: ({ params: { missingProperty } }) => (0, codegen_1.str)`must have required property '${missingProperty}'`,
      params: ({ params: { missingProperty } }) => (0, codegen_1._)`{missingProperty: ${missingProperty}}`
    };
    var def = {
      keyword: "required",
      type: "object",
      schemaType: "array",
      $data: true,
      error: error48,
      code(cxt) {
        const { gen, schema, schemaCode, data, $data, it } = cxt;
        const { opts } = it;
        if (!$data && schema.length === 0)
          return;
        const useLoop = schema.length >= opts.loopRequired;
        if (it.allErrors)
          allErrorsMode();
        else
          exitOnErrorMode();
        if (opts.strictRequired) {
          const props = cxt.parentSchema.properties;
          const { definedProperties } = cxt.it;
          for (const requiredKey of schema) {
            if ((props === null || props === void 0 ? void 0 : props[requiredKey]) === void 0 && !definedProperties.has(requiredKey)) {
              const schemaPath = it.schemaEnv.baseId + it.errSchemaPath;
              const msg = `required property "${requiredKey}" is not defined at "${schemaPath}" (strictRequired)`;
              (0, util_1.checkStrictMode)(it, msg, it.opts.strictRequired);
            }
          }
        }
        function allErrorsMode() {
          if (useLoop || $data) {
            cxt.block$data(codegen_1.nil, loopAllRequired);
          } else {
            for (const prop of schema) {
              (0, code_1.checkReportMissingProp)(cxt, prop);
            }
          }
        }
        function exitOnErrorMode() {
          const missing = gen.let("missing");
          if (useLoop || $data) {
            const valid = gen.let("valid", true);
            cxt.block$data(valid, () => loopUntilMissing(missing, valid));
            cxt.ok(valid);
          } else {
            gen.if((0, code_1.checkMissingProp)(cxt, schema, missing));
            (0, code_1.reportMissingProp)(cxt, missing);
            gen.else();
          }
        }
        function loopAllRequired() {
          gen.forOf("prop", schemaCode, (prop) => {
            cxt.setParams({ missingProperty: prop });
            gen.if((0, code_1.noPropertyInData)(gen, data, prop, opts.ownProperties), () => cxt.error());
          });
        }
        function loopUntilMissing(missing, valid) {
          cxt.setParams({ missingProperty: missing });
          gen.forOf(missing, schemaCode, () => {
            gen.assign(valid, (0, code_1.propertyInData)(gen, data, missing, opts.ownProperties));
            gen.if((0, codegen_1.not)(valid), () => {
              cxt.error();
              gen.break();
            });
          }, codegen_1.nil);
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/limitItems.js
var require_limitItems = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error48 = {
      message({ keyword, schemaCode }) {
        const comp = keyword === "maxItems" ? "more" : "fewer";
        return (0, codegen_1.str)`must NOT have ${comp} than ${schemaCode} items`;
      },
      params: ({ schemaCode }) => (0, codegen_1._)`{limit: ${schemaCode}}`
    };
    var def = {
      keyword: ["maxItems", "minItems"],
      type: "array",
      schemaType: "number",
      $data: true,
      error: error48,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        const op = keyword === "maxItems" ? codegen_1.operators.GT : codegen_1.operators.LT;
        cxt.fail$data((0, codegen_1._)`${data}.length ${op} ${schemaCode}`);
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/runtime/equal.js
var require_equal = __commonJS({
  "node_modules/ajv/dist/runtime/equal.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var equal = require_fast_deep_equal();
    equal.code = 'require("ajv/dist/runtime/equal").default';
    exports.default = equal;
  }
});

// node_modules/ajv/dist/vocabularies/validation/uniqueItems.js
var require_uniqueItems = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/uniqueItems.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var dataType_1 = require_dataType();
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var equal_1 = require_equal();
    var error48 = {
      message: ({ params: { i: i2, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i2} are identical)`,
      params: ({ params: { i: i2, j } }) => (0, codegen_1._)`{i: ${i2}, j: ${j}}`
    };
    var def = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error: error48,
      code(cxt) {
        const { gen, data, $data, schema, parentSchema, schemaCode, it } = cxt;
        if (!$data && !schema)
          return;
        const valid = gen.let("valid");
        const itemTypes = parentSchema.items ? (0, dataType_1.getSchemaTypes)(parentSchema.items) : [];
        cxt.block$data(valid, validateUniqueItems, (0, codegen_1._)`${schemaCode} === false`);
        cxt.ok(valid);
        function validateUniqueItems() {
          const i2 = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j = gen.let("j");
          cxt.setParams({ i: i2, j });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i2} > 1`, () => (canOptimize() ? loopN : loopN2)(i2, j));
        }
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t2) => t2 === "object" || t2 === "array");
        }
        function loopN(i2, j) {
          const item = gen.name("item");
          const wrongType = (0, dataType_1.checkDataTypes)(itemTypes, item, it.opts.strictNumbers, dataType_1.DataType.Wrong);
          const indices = gen.const("indices", (0, codegen_1._)`{}`);
          gen.for((0, codegen_1._)`;${i2}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i2}]`);
            gen.if(wrongType, (0, codegen_1._)`continue`);
            if (itemTypes.length > 1)
              gen.if((0, codegen_1._)`typeof ${item} == "string"`, (0, codegen_1._)`${item} += "_"`);
            gen.if((0, codegen_1._)`typeof ${indices}[${item}] == "number"`, () => {
              gen.assign(j, (0, codegen_1._)`${indices}[${item}]`);
              cxt.error();
              gen.assign(valid, false).break();
            }).code((0, codegen_1._)`${indices}[${item}] = ${i2}`);
          });
        }
        function loopN2(i2, j) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i2}--;`, () => gen.for((0, codegen_1._)`${j} = ${i2}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i2}], ${data}[${j}])`, () => {
            cxt.error();
            gen.assign(valid, false).break(outer);
          })));
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/const.js
var require_const = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/const.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var equal_1 = require_equal();
    var error48 = {
      message: "must be equal to constant",
      params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
    };
    var def = {
      keyword: "const",
      $data: true,
      error: error48,
      code(cxt) {
        const { gen, data, $data, schemaCode, schema } = cxt;
        if ($data || schema && typeof schema == "object") {
          cxt.fail$data((0, codegen_1._)`!${(0, util_1.useFunc)(gen, equal_1.default)}(${data}, ${schemaCode})`);
        } else {
          cxt.fail((0, codegen_1._)`${schema} !== ${data}`);
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/enum.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var equal_1 = require_equal();
    var error48 = {
      message: "must be equal to one of the allowed values",
      params: ({ schemaCode }) => (0, codegen_1._)`{allowedValues: ${schemaCode}}`
    };
    var def = {
      keyword: "enum",
      schemaType: "array",
      $data: true,
      error: error48,
      code(cxt) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        if (!$data && schema.length === 0)
          throw new Error("enum must have non-empty array");
        const useLoop = schema.length >= it.opts.loopEnum;
        let eql;
        const getEql = () => eql !== null && eql !== void 0 ? eql : eql = (0, util_1.useFunc)(gen, equal_1.default);
        let valid;
        if (useLoop || $data) {
          valid = gen.let("valid");
          cxt.block$data(valid, loopEnum);
        } else {
          if (!Array.isArray(schema))
            throw new Error("ajv implementation error");
          const vSchema = gen.const("vSchema", schemaCode);
          valid = (0, codegen_1.or)(...schema.map((_x, i2) => equalCode(vSchema, i2)));
        }
        cxt.pass(valid);
        function loopEnum() {
          gen.assign(valid, false);
          gen.forOf("v", schemaCode, (v2) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v2})`, () => gen.assign(valid, true).break()));
        }
        function equalCode(vSchema, i2) {
          const sch = schema[i2];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i2}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/validation/index.js
var require_validation = __commonJS({
  "node_modules/ajv/dist/vocabularies/validation/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var limitNumber_1 = require_limitNumber();
    var multipleOf_1 = require_multipleOf();
    var limitLength_1 = require_limitLength();
    var pattern_1 = require_pattern();
    var limitProperties_1 = require_limitProperties();
    var required_1 = require_required();
    var limitItems_1 = require_limitItems();
    var uniqueItems_1 = require_uniqueItems();
    var const_1 = require_const();
    var enum_1 = require_enum();
    var validation = [
      // number
      limitNumber_1.default,
      multipleOf_1.default,
      // string
      limitLength_1.default,
      pattern_1.default,
      // object
      limitProperties_1.default,
      required_1.default,
      // array
      limitItems_1.default,
      uniqueItems_1.default,
      // any
      { keyword: "type", schemaType: ["string", "array"] },
      { keyword: "nullable", schemaType: "boolean" },
      const_1.default,
      enum_1.default
    ];
    exports.default = validation;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
var require_additionalItems = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/additionalItems.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateAdditionalItems = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var error48 = {
      message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
      params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
    };
    var def = {
      keyword: "additionalItems",
      type: "array",
      schemaType: ["boolean", "object"],
      before: "uniqueItems",
      error: error48,
      code(cxt) {
        const { parentSchema, it } = cxt;
        const { items } = parentSchema;
        if (!Array.isArray(items)) {
          (0, util_1.checkStrictMode)(it, '"additionalItems" is ignored when "items" is not an array of schemas');
          return;
        }
        validateAdditionalItems(cxt, items);
      }
    };
    function validateAdditionalItems(cxt, items) {
      const { gen, schema, data, keyword, it } = cxt;
      it.items = true;
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      if (schema === false) {
        cxt.setParams({ len: items.length });
        cxt.pass((0, codegen_1._)`${len} <= ${items.length}`);
      } else if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
        const valid = gen.var("valid", (0, codegen_1._)`${len} <= ${items.length}`);
        gen.if((0, codegen_1.not)(valid), () => validateItems(valid));
        cxt.ok(valid);
      }
      function validateItems(valid) {
        gen.forRange("i", items.length, len, (i2) => {
          cxt.subschema({ keyword, dataProp: i2, dataPropType: util_1.Type.Num }, valid);
          if (!it.allErrors)
            gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
      }
    }
    exports.validateAdditionalItems = validateAdditionalItems;
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/items.js
var require_items = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/items.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateTuple = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var code_1 = require_code2();
    var def = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "array", "boolean"],
      before: "uniqueItems",
      code(cxt) {
        const { schema, it } = cxt;
        if (Array.isArray(schema))
          return validateTuple(cxt, "additionalItems", schema);
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    function validateTuple(cxt, extraItems, schArr = cxt.schema) {
      const { gen, parentSchema, data, keyword, it } = cxt;
      checkStrictTuple(parentSchema);
      if (it.opts.unevaluated && schArr.length && it.items !== true) {
        it.items = util_1.mergeEvaluated.items(gen, schArr.length, it.items);
      }
      const valid = gen.name("valid");
      const len = gen.const("len", (0, codegen_1._)`${data}.length`);
      schArr.forEach((sch, i2) => {
        if ((0, util_1.alwaysValidSchema)(it, sch))
          return;
        gen.if((0, codegen_1._)`${len} > ${i2}`, () => cxt.subschema({
          keyword,
          schemaProp: i2,
          dataProp: i2
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it;
        const l2 = schArr.length;
        const fullTuple = l2 === sch.minItems && (l2 === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
          const msg = `"${keyword}" is ${l2}-tuple, but minItems or maxItems/${extraItems} are not specified or different at path "${errSchemaPath}"`;
          (0, util_1.checkStrictMode)(it, msg, opts.strictTuples);
        }
      }
    }
    exports.validateTuple = validateTuple;
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/prefixItems.js
var require_prefixItems = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/prefixItems.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var items_1 = require_items();
    var def = {
      keyword: "prefixItems",
      type: "array",
      schemaType: ["array"],
      before: "uniqueItems",
      code: (cxt) => (0, items_1.validateTuple)(cxt, "items")
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/items2020.js
var require_items2020 = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/items2020.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var code_1 = require_code2();
    var additionalItems_1 = require_additionalItems();
    var error48 = {
      message: ({ params: { len } }) => (0, codegen_1.str)`must NOT have more than ${len} items`,
      params: ({ params: { len } }) => (0, codegen_1._)`{limit: ${len}}`
    };
    var def = {
      keyword: "items",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      error: error48,
      code(cxt) {
        const { schema, parentSchema, it } = cxt;
        const { prefixItems } = parentSchema;
        it.items = true;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        if (prefixItems)
          (0, additionalItems_1.validateAdditionalItems)(cxt, prefixItems);
        else
          cxt.ok((0, code_1.validateArray)(cxt));
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/contains.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var error48 = {
      message: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1.str)`must contain at least ${min} valid item(s)` : (0, codegen_1.str)`must contain at least ${min} and no more than ${max} valid item(s)`,
      params: ({ params: { min, max } }) => max === void 0 ? (0, codegen_1._)`{minContains: ${min}}` : (0, codegen_1._)`{minContains: ${min}, maxContains: ${max}}`
    };
    var def = {
      keyword: "contains",
      type: "array",
      schemaType: ["object", "boolean"],
      before: "uniqueItems",
      trackErrors: true,
      error: error48,
      code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        let min;
        let max;
        const { minContains, maxContains } = parentSchema;
        if (it.opts.next) {
          min = minContains === void 0 ? 1 : minContains;
          max = maxContains;
        } else {
          min = 1;
        }
        const len = gen.const("len", (0, codegen_1._)`${data}.length`);
        cxt.setParams({ min, max });
        if (max === void 0 && min === 0) {
          (0, util_1.checkStrictMode)(it, `"minContains" == 0 without "maxContains": "contains" keyword ignored`);
          return;
        }
        if (max !== void 0 && min > max) {
          (0, util_1.checkStrictMode)(it, `"minContains" > "maxContains" is always invalid`);
          cxt.fail();
          return;
        }
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
          let cond = (0, codegen_1._)`${len} >= ${min}`;
          if (max !== void 0)
            cond = (0, codegen_1._)`${cond} && ${len} <= ${max}`;
          cxt.pass(cond);
          return;
        }
        it.items = true;
        const valid = gen.name("valid");
        if (max === void 0 && min === 1) {
          validateItems(valid, () => gen.if(valid, () => gen.break()));
        } else if (min === 0) {
          gen.let(valid, true);
          if (max !== void 0)
            gen.if((0, codegen_1._)`${data}.length > 0`, validateItemsWithCount);
        } else {
          gen.let(valid, false);
          validateItemsWithCount();
        }
        cxt.result(valid, () => cxt.reset());
        function validateItemsWithCount() {
          const schValid = gen.name("_valid");
          const count = gen.let("count", 0);
          validateItems(schValid, () => gen.if(schValid, () => checkLimits(count)));
        }
        function validateItems(_valid, block) {
          gen.forRange("i", 0, len, (i2) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i2,
              dataPropType: util_1.Type.Num,
              compositeRule: true
            }, _valid);
            block();
          });
        }
        function checkLimits(count) {
          gen.code((0, codegen_1._)`${count}++`);
          if (max === void 0) {
            gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true).break());
          } else {
            gen.if((0, codegen_1._)`${count} > ${max}`, () => gen.assign(valid, false).break());
            if (min === 1)
              gen.assign(valid, true);
            else
              gen.if((0, codegen_1._)`${count} >= ${min}`, () => gen.assign(valid, true));
          }
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/dependencies.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.validateSchemaDeps = exports.validatePropertyDeps = exports.error = void 0;
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var code_1 = require_code2();
    exports.error = {
      message: ({ params: { property, depsCount, deps } }) => {
        const property_ies = depsCount === 1 ? "property" : "properties";
        return (0, codegen_1.str)`must have ${property_ies} ${deps} when property ${property} is present`;
      },
      params: ({ params: { property, depsCount, deps, missingProperty } }) => (0, codegen_1._)`{property: ${property},
    missingProperty: ${missingProperty},
    depsCount: ${depsCount},
    deps: ${deps}}`
      // TODO change to reference
    };
    var def = {
      keyword: "dependencies",
      type: "object",
      schemaType: "object",
      error: exports.error,
      code(cxt) {
        const [propDeps, schDeps] = splitDependencies(cxt);
        validatePropertyDeps(cxt, propDeps);
        validateSchemaDeps(cxt, schDeps);
      }
    };
    function splitDependencies({ schema }) {
      const propertyDeps = {};
      const schemaDeps = {};
      for (const key in schema) {
        if (key === "__proto__")
          continue;
        const deps = Array.isArray(schema[key]) ? propertyDeps : schemaDeps;
        deps[key] = schema[key];
      }
      return [propertyDeps, schemaDeps];
    }
    function validatePropertyDeps(cxt, propertyDeps = cxt.schema) {
      const { gen, data, it } = cxt;
      if (Object.keys(propertyDeps).length === 0)
        return;
      const missing = gen.let("missing");
      for (const prop in propertyDeps) {
        const deps = propertyDeps[prop];
        if (deps.length === 0)
          continue;
        const hasProperty = (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties);
        cxt.setParams({
          property: prop,
          depsCount: deps.length,
          deps: deps.join(", ")
        });
        if (it.allErrors) {
          gen.if(hasProperty, () => {
            for (const depProp of deps) {
              (0, code_1.checkReportMissingProp)(cxt, depProp);
            }
          });
        } else {
          gen.if((0, codegen_1._)`${hasProperty} && (${(0, code_1.checkMissingProp)(cxt, deps, missing)})`);
          (0, code_1.reportMissingProp)(cxt, missing);
          gen.else();
        }
      }
    }
    exports.validatePropertyDeps = validatePropertyDeps;
    function validateSchemaDeps(cxt, schemaDeps = cxt.schema) {
      const { gen, data, keyword, it } = cxt;
      const valid = gen.name("valid");
      for (const prop in schemaDeps) {
        if ((0, util_1.alwaysValidSchema)(it, schemaDeps[prop]))
          continue;
        gen.if(
          (0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties),
          () => {
            const schCxt = cxt.subschema({ keyword, schemaProp: prop }, valid);
            cxt.mergeValidEvaluated(schCxt, valid);
          },
          () => gen.var(valid, true)
          // TODO var
        );
        cxt.ok(valid);
      }
    }
    exports.validateSchemaDeps = validateSchemaDeps;
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/propertyNames.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var error48 = {
      message: "property name must be valid",
      params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
    };
    var def = {
      keyword: "propertyNames",
      type: "object",
      schemaType: ["object", "boolean"],
      error: error48,
      code(cxt) {
        const { gen, schema, data, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema))
          return;
        const valid = gen.name("valid");
        gen.forIn("key", data, (key) => {
          cxt.setParams({ propertyName: key });
          cxt.subschema({
            keyword: "propertyNames",
            data: key,
            dataTypes: ["string"],
            propertyName: key,
            compositeRule: true
          }, valid);
          gen.if((0, codegen_1.not)(valid), () => {
            cxt.error(true);
            if (!it.allErrors)
              gen.break();
          });
        });
        cxt.ok(valid);
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var names_1 = require_names();
    var util_1 = require_util();
    var error48 = {
      message: "must NOT have additional properties",
      params: ({ params }) => (0, codegen_1._)`{additionalProperty: ${params.additionalProperty}}`
    };
    var def = {
      keyword: "additionalProperties",
      type: ["object"],
      schemaType: ["boolean", "object"],
      allowUndefined: true,
      trackErrors: true,
      error: error48,
      code(cxt) {
        const { gen, schema, parentSchema, data, errsCount, it } = cxt;
        if (!errsCount)
          throw new Error("ajv implementation error");
        const { allErrors, opts } = it;
        it.props = true;
        if (opts.removeAdditional !== "all" && (0, util_1.alwaysValidSchema)(it, schema))
          return;
        const props = (0, code_1.allSchemaProperties)(parentSchema.properties);
        const patProps = (0, code_1.allSchemaProperties)(parentSchema.patternProperties);
        checkAdditionalProperties();
        cxt.ok((0, codegen_1._)`${errsCount} === ${names_1.default.errors}`);
        function checkAdditionalProperties() {
          gen.forIn("key", data, (key) => {
            if (!props.length && !patProps.length)
              additionalPropertyCode(key);
            else
              gen.if(isAdditional(key), () => additionalPropertyCode(key));
          });
        }
        function isAdditional(key) {
          let definedProp;
          if (props.length > 8) {
            const propsSchema = (0, util_1.schemaRefOrVal)(it, parentSchema.properties, "properties");
            definedProp = (0, code_1.isOwnProperty)(gen, propsSchema, key);
          } else if (props.length) {
            definedProp = (0, codegen_1.or)(...props.map((p) => (0, codegen_1._)`${key} === ${p}`));
          } else {
            definedProp = codegen_1.nil;
          }
          if (patProps.length) {
            definedProp = (0, codegen_1.or)(definedProp, ...patProps.map((p) => (0, codegen_1._)`${(0, code_1.usePattern)(cxt, p)}.test(${key})`));
          }
          return (0, codegen_1.not)(definedProp);
        }
        function deleteAdditional(key) {
          gen.code((0, codegen_1._)`delete ${data}[${key}]`);
        }
        function additionalPropertyCode(key) {
          if (opts.removeAdditional === "all" || opts.removeAdditional && schema === false) {
            deleteAdditional(key);
            return;
          }
          if (schema === false) {
            cxt.setParams({ additionalProperty: key });
            cxt.error();
            if (!allErrors)
              gen.break();
            return;
          }
          if (typeof schema == "object" && !(0, util_1.alwaysValidSchema)(it, schema)) {
            const valid = gen.name("valid");
            if (opts.removeAdditional === "failing") {
              applyAdditionalSchema(key, valid, false);
              gen.if((0, codegen_1.not)(valid), () => {
                cxt.reset();
                deleteAdditional(key);
              });
            } else {
              applyAdditionalSchema(key, valid);
              if (!allErrors)
                gen.if((0, codegen_1.not)(valid), () => gen.break());
            }
          }
        }
        function applyAdditionalSchema(key, valid, errors) {
          const subschema = {
            keyword: "additionalProperties",
            dataProp: key,
            dataPropType: util_1.Type.Str
          };
          if (errors === false) {
            Object.assign(subschema, {
              compositeRule: true,
              createErrors: false,
              allErrors: false
            });
          }
          cxt.subschema(subschema, valid);
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/properties.js
var require_properties = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/properties.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var validate_1 = require_validate();
    var code_1 = require_code2();
    var util_1 = require_util();
    var additionalProperties_1 = require_additionalProperties();
    var def = {
      keyword: "properties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, parentSchema, data, it } = cxt;
        if (it.opts.removeAdditional === "all" && parentSchema.additionalProperties === void 0) {
          additionalProperties_1.default.code(new validate_1.KeywordCxt(it, additionalProperties_1.default, "additionalProperties"));
        }
        const allProps = (0, code_1.allSchemaProperties)(schema);
        for (const prop of allProps) {
          it.definedProperties.add(prop);
        }
        if (it.opts.unevaluated && allProps.length && it.props !== true) {
          it.props = util_1.mergeEvaluated.props(gen, (0, util_1.toHash)(allProps), it.props);
        }
        const properties = allProps.filter((p) => !(0, util_1.alwaysValidSchema)(it, schema[p]));
        if (properties.length === 0)
          return;
        const valid = gen.name("valid");
        for (const prop of properties) {
          if (hasDefault(prop)) {
            applyPropertySchema(prop);
          } else {
            gen.if((0, code_1.propertyInData)(gen, data, prop, it.opts.ownProperties));
            applyPropertySchema(prop);
            if (!it.allErrors)
              gen.else().var(valid, true);
            gen.endIf();
          }
          cxt.it.definedProperties.add(prop);
          cxt.ok(valid);
        }
        function hasDefault(prop) {
          return it.opts.useDefaults && !it.compositeRule && schema[prop].default !== void 0;
        }
        function applyPropertySchema(prop) {
          cxt.subschema({
            keyword: "properties",
            schemaProp: prop,
            dataProp: prop
          }, valid);
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/patternProperties.js
var require_patternProperties = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/patternProperties.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var util_2 = require_util();
    var def = {
      keyword: "patternProperties",
      type: "object",
      schemaType: "object",
      code(cxt) {
        const { gen, schema, data, parentSchema, it } = cxt;
        const { opts } = it;
        const patterns = (0, code_1.allSchemaProperties)(schema);
        const alwaysValidPatterns = patterns.filter((p) => (0, util_1.alwaysValidSchema)(it, schema[p]));
        if (patterns.length === 0 || alwaysValidPatterns.length === patterns.length && (!it.opts.unevaluated || it.props === true)) {
          return;
        }
        const checkProperties = opts.strictSchema && !opts.allowMatchingProperties && parentSchema.properties;
        const valid = gen.name("valid");
        if (it.props !== true && !(it.props instanceof codegen_1.Name)) {
          it.props = (0, util_2.evaluatedPropsToName)(gen, it.props);
        }
        const { props } = it;
        validatePatternProperties();
        function validatePatternProperties() {
          for (const pat of patterns) {
            if (checkProperties)
              checkMatchingProperties(pat);
            if (it.allErrors) {
              validateProperties(pat);
            } else {
              gen.var(valid, true);
              validateProperties(pat);
              gen.if(valid);
            }
          }
        }
        function checkMatchingProperties(pat) {
          for (const prop in checkProperties) {
            if (new RegExp(pat).test(prop)) {
              (0, util_1.checkStrictMode)(it, `property ${prop} matches pattern ${pat} (use allowMatchingProperties)`);
            }
          }
        }
        function validateProperties(pat) {
          gen.forIn("key", data, (key) => {
            gen.if((0, codegen_1._)`${(0, code_1.usePattern)(cxt, pat)}.test(${key})`, () => {
              const alwaysValid = alwaysValidPatterns.includes(pat);
              if (!alwaysValid) {
                cxt.subschema({
                  keyword: "patternProperties",
                  schemaProp: pat,
                  dataProp: key,
                  dataPropType: util_2.Type.Str
                }, valid);
              }
              if (it.opts.unevaluated && props !== true) {
                gen.assign((0, codegen_1._)`${props}[${key}]`, true);
              } else if (!alwaysValid && !it.allErrors) {
                gen.if((0, codegen_1.not)(valid), () => gen.break());
              }
            });
          });
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/not.js
var require_not = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/not.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var util_1 = require_util();
    var def = {
      keyword: "not",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      code(cxt) {
        const { gen, schema, it } = cxt;
        if ((0, util_1.alwaysValidSchema)(it, schema)) {
          cxt.fail();
          return;
        }
        const valid = gen.name("valid");
        cxt.subschema({
          keyword: "not",
          compositeRule: true,
          createErrors: false,
          allErrors: false
        }, valid);
        cxt.failResult(valid, () => cxt.reset(), () => cxt.error());
      },
      error: { message: "must NOT be valid" }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/anyOf.js
var require_anyOf = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/anyOf.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var code_1 = require_code2();
    var def = {
      keyword: "anyOf",
      schemaType: "array",
      trackErrors: true,
      code: code_1.validateUnion,
      error: { message: "must match a schema in anyOf" }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/oneOf.js
var require_oneOf = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/oneOf.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var error48 = {
      message: "must match exactly one schema in oneOf",
      params: ({ params }) => (0, codegen_1._)`{passingSchemas: ${params.passing}}`
    };
    var def = {
      keyword: "oneOf",
      schemaType: "array",
      trackErrors: true,
      error: error48,
      code(cxt) {
        const { gen, schema, parentSchema, it } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        if (it.opts.discriminator && parentSchema.discriminator)
          return;
        const schArr = schema;
        const valid = gen.let("valid", false);
        const passing = gen.let("passing", null);
        const schValid = gen.name("_valid");
        cxt.setParams({ passing });
        gen.block(validateOneOf);
        cxt.result(valid, () => cxt.reset(), () => cxt.error(true));
        function validateOneOf() {
          schArr.forEach((sch, i2) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i2,
                compositeRule: true
              }, schValid);
            }
            if (i2 > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i2}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i2);
              if (schCxt)
                cxt.mergeEvaluated(schCxt, codegen_1.Name);
            });
          });
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/allOf.js
var require_allOf = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/allOf.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var util_1 = require_util();
    var def = {
      keyword: "allOf",
      schemaType: "array",
      code(cxt) {
        const { gen, schema, it } = cxt;
        if (!Array.isArray(schema))
          throw new Error("ajv implementation error");
        const valid = gen.name("valid");
        schema.forEach((sch, i2) => {
          if ((0, util_1.alwaysValidSchema)(it, sch))
            return;
          const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i2 }, valid);
          cxt.ok(valid);
          cxt.mergeEvaluated(schCxt);
        });
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/if.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var util_1 = require_util();
    var error48 = {
      message: ({ params }) => (0, codegen_1.str)`must match "${params.ifClause}" schema`,
      params: ({ params }) => (0, codegen_1._)`{failingKeyword: ${params.ifClause}}`
    };
    var def = {
      keyword: "if",
      schemaType: ["object", "boolean"],
      trackErrors: true,
      error: error48,
      code(cxt) {
        const { gen, parentSchema, it } = cxt;
        if (parentSchema.then === void 0 && parentSchema.else === void 0) {
          (0, util_1.checkStrictMode)(it, '"if" without "then" and "else" is ignored');
        }
        const hasThen = hasSchema(it, "then");
        const hasElse = hasSchema(it, "else");
        if (!hasThen && !hasElse)
          return;
        const valid = gen.let("valid", true);
        const schValid = gen.name("_valid");
        validateIf();
        cxt.reset();
        if (hasThen && hasElse) {
          const ifClause = gen.let("ifClause");
          cxt.setParams({ ifClause });
          gen.if(schValid, validateClause("then", ifClause), validateClause("else", ifClause));
        } else if (hasThen) {
          gen.if(schValid, validateClause("then"));
        } else {
          gen.if((0, codegen_1.not)(schValid), validateClause("else"));
        }
        cxt.pass(valid, () => cxt.error(true));
        function validateIf() {
          const schCxt = cxt.subschema({
            keyword: "if",
            compositeRule: true,
            createErrors: false,
            allErrors: false
          }, schValid);
          cxt.mergeEvaluated(schCxt);
        }
        function validateClause(keyword, ifClause) {
          return () => {
            const schCxt = cxt.subschema({ keyword }, schValid);
            gen.assign(valid, schValid);
            cxt.mergeValidEvaluated(schCxt, valid);
            if (ifClause)
              gen.assign(ifClause, (0, codegen_1._)`${keyword}`);
            else
              cxt.setParams({ ifClause: keyword });
          };
        }
      }
    };
    function hasSchema(it, keyword) {
      const schema = it.schema[keyword];
      return schema !== void 0 && !(0, util_1.alwaysValidSchema)(it, schema);
    }
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/thenElse.js
var require_thenElse = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/thenElse.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var util_1 = require_util();
    var def = {
      keyword: ["then", "else"],
      schemaType: ["object", "boolean"],
      code({ keyword, parentSchema, it }) {
        if (parentSchema.if === void 0)
          (0, util_1.checkStrictMode)(it, `"${keyword}" without "if" is ignored`);
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/applicator/index.js
var require_applicator = __commonJS({
  "node_modules/ajv/dist/vocabularies/applicator/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var additionalItems_1 = require_additionalItems();
    var prefixItems_1 = require_prefixItems();
    var items_1 = require_items();
    var items2020_1 = require_items2020();
    var contains_1 = require_contains();
    var dependencies_1 = require_dependencies();
    var propertyNames_1 = require_propertyNames();
    var additionalProperties_1 = require_additionalProperties();
    var properties_1 = require_properties();
    var patternProperties_1 = require_patternProperties();
    var not_1 = require_not();
    var anyOf_1 = require_anyOf();
    var oneOf_1 = require_oneOf();
    var allOf_1 = require_allOf();
    var if_1 = require_if();
    var thenElse_1 = require_thenElse();
    function getApplicator(draft2020 = false) {
      const applicator = [
        // any
        not_1.default,
        anyOf_1.default,
        oneOf_1.default,
        allOf_1.default,
        if_1.default,
        thenElse_1.default,
        // object
        propertyNames_1.default,
        additionalProperties_1.default,
        dependencies_1.default,
        properties_1.default,
        patternProperties_1.default
      ];
      if (draft2020)
        applicator.push(prefixItems_1.default, items2020_1.default);
      else
        applicator.push(additionalItems_1.default, items_1.default);
      applicator.push(contains_1.default);
      return applicator;
    }
    exports.default = getApplicator;
  }
});

// node_modules/ajv/dist/vocabularies/format/format.js
var require_format = __commonJS({
  "node_modules/ajv/dist/vocabularies/format/format.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error48 = {
      message: ({ schemaCode }) => (0, codegen_1.str)`must match format "${schemaCode}"`,
      params: ({ schemaCode }) => (0, codegen_1._)`{format: ${schemaCode}}`
    };
    var def = {
      keyword: "format",
      type: ["number", "string"],
      schemaType: "string",
      $data: true,
      error: error48,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self: self2 } = it;
        if (!opts.validateFormats)
          return;
        if ($data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
          const fType = gen.let("fType");
          const format = gen.let("format");
          gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format, fDef));
          cxt.fail$data((0, codegen_1.or)(unknownFmt(), invalidFmt()));
          function unknownFmt() {
            if (opts.strictSchema === false)
              return codegen_1.nil;
            return (0, codegen_1._)`${schemaCode} && !${format}`;
          }
          function invalidFmt() {
            const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format}(${data}) : ${format}(${data}))` : (0, codegen_1._)`${format}(${data})`;
            const validData = (0, codegen_1._)`(typeof ${format} == "function" ? ${callFormat} : ${format}.test(${data}))`;
            return (0, codegen_1._)`${format} && ${format} !== true && ${fType} === ${ruleType} && !${validData}`;
          }
        }
        function validateFormat() {
          const formatDef = self2.formats[schema];
          if (!formatDef) {
            unknownFormat();
            return;
          }
          if (formatDef === true)
            return;
          const [fmtType, format, fmtRef] = getFormat(formatDef);
          if (fmtType === ruleType)
            cxt.pass(validCondition());
          function unknownFormat() {
            if (opts.strictSchema === false) {
              self2.logger.warn(unknownMsg());
              return;
            }
            throw new Error(unknownMsg());
            function unknownMsg() {
              return `unknown format "${schema}" ignored in schema at path "${errSchemaPath}"`;
            }
          }
          function getFormat(fmtDef) {
            const code = fmtDef instanceof RegExp ? (0, codegen_1.regexpCode)(fmtDef) : opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(schema)}` : void 0;
            const fmt = gen.scopeValue("formats", { key: schema, ref: fmtDef, code });
            if (typeof fmtDef == "object" && !(fmtDef instanceof RegExp)) {
              return [fmtDef.type || "string", fmtDef.validate, (0, codegen_1._)`${fmt}.validate`];
            }
            return ["string", fmtDef, fmt];
          }
          function validCondition() {
            if (typeof formatDef == "object" && !(formatDef instanceof RegExp) && formatDef.async) {
              if (!schemaEnv.$async)
                throw new Error("async format in sync schema");
              return (0, codegen_1._)`await ${fmtRef}(${data})`;
            }
            return typeof format == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
          }
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/vocabularies/format/index.js
var require_format2 = __commonJS({
  "node_modules/ajv/dist/vocabularies/format/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var format_1 = require_format();
    var format = [format_1.default];
    exports.default = format;
  }
});

// node_modules/ajv/dist/vocabularies/metadata.js
var require_metadata = __commonJS({
  "node_modules/ajv/dist/vocabularies/metadata.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.contentVocabulary = exports.metadataVocabulary = void 0;
    exports.metadataVocabulary = [
      "title",
      "description",
      "default",
      "deprecated",
      "readOnly",
      "writeOnly",
      "examples"
    ];
    exports.contentVocabulary = [
      "contentMediaType",
      "contentEncoding",
      "contentSchema"
    ];
  }
});

// node_modules/ajv/dist/vocabularies/draft7.js
var require_draft7 = __commonJS({
  "node_modules/ajv/dist/vocabularies/draft7.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var core_1 = require_core2();
    var validation_1 = require_validation();
    var applicator_1 = require_applicator();
    var format_1 = require_format2();
    var metadata_1 = require_metadata();
    var draft7Vocabularies = [
      core_1.default,
      validation_1.default,
      (0, applicator_1.default)(),
      format_1.default,
      metadata_1.metadataVocabulary,
      metadata_1.contentVocabulary
    ];
    exports.default = draft7Vocabularies;
  }
});

// node_modules/ajv/dist/vocabularies/discriminator/types.js
var require_types = __commonJS({
  "node_modules/ajv/dist/vocabularies/discriminator/types.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.DiscrError = void 0;
    var DiscrError;
    (function(DiscrError2) {
      DiscrError2["Tag"] = "tag";
      DiscrError2["Mapping"] = "mapping";
    })(DiscrError || (exports.DiscrError = DiscrError = {}));
  }
});

// node_modules/ajv/dist/vocabularies/discriminator/index.js
var require_discriminator = __commonJS({
  "node_modules/ajv/dist/vocabularies/discriminator/index.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var types_1 = require_types();
    var compile_1 = require_compile();
    var ref_error_1 = require_ref_error();
    var util_1 = require_util();
    var error48 = {
      message: ({ params: { discrError, tagName } }) => discrError === types_1.DiscrError.Tag ? `tag "${tagName}" must be string` : `value of tag "${tagName}" must be in oneOf`,
      params: ({ params: { discrError, tag, tagName } }) => (0, codegen_1._)`{error: ${discrError}, tag: ${tagName}, tagValue: ${tag}}`
    };
    var def = {
      keyword: "discriminator",
      type: "object",
      schemaType: "object",
      error: error48,
      code(cxt) {
        const { gen, data, schema, parentSchema, it } = cxt;
        const { oneOf } = parentSchema;
        if (!it.opts.discriminator) {
          throw new Error("discriminator: requires discriminator option");
        }
        const tagName = schema.propertyName;
        if (typeof tagName != "string")
          throw new Error("discriminator: requires propertyName");
        if (schema.mapping)
          throw new Error("discriminator: mapping is not supported");
        if (!oneOf)
          throw new Error("discriminator: requires oneOf keyword");
        const valid = gen.let("valid", false);
        const tag = gen.const("tag", (0, codegen_1._)`${data}${(0, codegen_1.getProperty)(tagName)}`);
        gen.if((0, codegen_1._)`typeof ${tag} == "string"`, () => validateMapping(), () => cxt.error(false, { discrError: types_1.DiscrError.Tag, tag, tagName }));
        cxt.ok(valid);
        function validateMapping() {
          const mapping = getMapping();
          gen.if(false);
          for (const tagValue in mapping) {
            gen.elseIf((0, codegen_1._)`${tag} === ${tagValue}`);
            gen.assign(valid, applyTagSchema(mapping[tagValue]));
          }
          gen.else();
          cxt.error(false, { discrError: types_1.DiscrError.Mapping, tag, tagName });
          gen.endIf();
        }
        function applyTagSchema(schemaProp) {
          const _valid = gen.name("valid");
          const schCxt = cxt.subschema({ keyword: "oneOf", schemaProp }, _valid);
          cxt.mergeEvaluated(schCxt, codegen_1.Name);
          return _valid;
        }
        function getMapping() {
          var _a3;
          const oneOfMapping = {};
          const topRequired = hasRequired(parentSchema);
          let tagRequired = true;
          for (let i2 = 0; i2 < oneOf.length; i2++) {
            let sch = oneOf[i2];
            if ((sch === null || sch === void 0 ? void 0 : sch.$ref) && !(0, util_1.schemaHasRulesButRef)(sch, it.self.RULES)) {
              const ref = sch.$ref;
              sch = compile_1.resolveRef.call(it.self, it.schemaEnv.root, it.baseId, ref);
              if (sch instanceof compile_1.SchemaEnv)
                sch = sch.schema;
              if (sch === void 0)
                throw new ref_error_1.default(it.opts.uriResolver, it.baseId, ref);
            }
            const propSch = (_a3 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a3 === void 0 ? void 0 : _a3[tagName];
            if (typeof propSch != "object") {
              throw new Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${tagName}"`);
            }
            tagRequired = tagRequired && (topRequired || hasRequired(sch));
            addMappings(propSch, i2);
          }
          if (!tagRequired)
            throw new Error(`discriminator: "${tagName}" must be required`);
          return oneOfMapping;
          function hasRequired({ required: required2 }) {
            return Array.isArray(required2) && required2.includes(tagName);
          }
          function addMappings(sch, i2) {
            if (sch.const) {
              addMapping(sch.const, i2);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i2);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          function addMapping(tagValue, i2) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i2;
          }
        }
      }
    };
    exports.default = def;
  }
});

// node_modules/ajv/dist/refs/json-schema-draft-07.json
var require_json_schema_draft_07 = __commonJS({
  "node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module2) {
    module2.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: true,
          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: true,
        readOnly: {
          type: "boolean",
          default: false
        },
        examples: {
          type: "array",
          items: true
        },
        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: true
        },
        maxItems: { $ref: "#/definitions/nonNegativeInteger" },
        minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" },
        uniqueItems: {
          type: "boolean",
          default: false
        },
        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: true,
        enum: {
          type: "array",
          items: true,
          minItems: 1,
          uniqueItems: true
        },
        type: {
          anyOf: [
            { $ref: "#/definitions/simpleTypes" },
            {
              type: "array",
              items: { $ref: "#/definitions/simpleTypes" },
              minItems: 1,
              uniqueItems: true
            }
          ]
        },
        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: true
    };
  }
});

// node_modules/ajv/dist/ajv.js
var require_ajv = __commonJS({
  "node_modules/ajv/dist/ajv.js"(exports, module2) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.MissingRefError = exports.ValidationError = exports.CodeGen = exports.Name = exports.nil = exports.stringify = exports.str = exports._ = exports.KeywordCxt = exports.Ajv = void 0;
    var core_1 = require_core();
    var draft7_1 = require_draft7();
    var discriminator_1 = require_discriminator();
    var draft7MetaSchema = require_json_schema_draft_07();
    var META_SUPPORT_DATA = ["/properties"];
    var META_SCHEMA_ID = "http://json-schema.org/draft-07/schema";
    var Ajv2 = class extends core_1.default {
      _addVocabularies() {
        super._addVocabularies();
        draft7_1.default.forEach((v2) => this.addVocabulary(v2));
        if (this.opts.discriminator)
          this.addKeyword(discriminator_1.default);
      }
      _addDefaultMetaSchema() {
        super._addDefaultMetaSchema();
        if (!this.opts.meta)
          return;
        const metaSchema = this.opts.$data ? this.$dataMetaSchema(draft7MetaSchema, META_SUPPORT_DATA) : draft7MetaSchema;
        this.addMetaSchema(metaSchema, META_SCHEMA_ID, false);
        this.refs["http://json-schema.org/schema"] = META_SCHEMA_ID;
      }
      defaultMeta() {
        return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(META_SCHEMA_ID) ? META_SCHEMA_ID : void 0);
      }
    };
    exports.Ajv = Ajv2;
    module2.exports = exports = Ajv2;
    module2.exports.Ajv = Ajv2;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = Ajv2;
    var validate_1 = require_validate();
    Object.defineProperty(exports, "KeywordCxt", { enumerable: true, get: function() {
      return validate_1.KeywordCxt;
    } });
    var codegen_1 = require_codegen();
    Object.defineProperty(exports, "_", { enumerable: true, get: function() {
      return codegen_1._;
    } });
    Object.defineProperty(exports, "str", { enumerable: true, get: function() {
      return codegen_1.str;
    } });
    Object.defineProperty(exports, "stringify", { enumerable: true, get: function() {
      return codegen_1.stringify;
    } });
    Object.defineProperty(exports, "nil", { enumerable: true, get: function() {
      return codegen_1.nil;
    } });
    Object.defineProperty(exports, "Name", { enumerable: true, get: function() {
      return codegen_1.Name;
    } });
    Object.defineProperty(exports, "CodeGen", { enumerable: true, get: function() {
      return codegen_1.CodeGen;
    } });
    var validation_error_1 = require_validation_error();
    Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function() {
      return validation_error_1.default;
    } });
    var ref_error_1 = require_ref_error();
    Object.defineProperty(exports, "MissingRefError", { enumerable: true, get: function() {
      return ref_error_1.default;
    } });
  }
});

// node_modules/ajv-formats/dist/formats.js
var require_formats = __commonJS({
  "node_modules/ajv-formats/dist/formats.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.formatNames = exports.fastFormats = exports.fullFormats = void 0;
    function fmtDef(validate, compare) {
      return { validate, compare };
    }
    exports.fullFormats = {
      // date: http://tools.ietf.org/html/rfc3339#section-5.6
      date: fmtDef(date7, compareDate),
      // date-time: http://tools.ietf.org/html/rfc3339#section-5.6
      time: fmtDef(getTime(true), compareTime),
      "date-time": fmtDef(getDateTime(true), compareDateTime),
      "iso-time": fmtDef(getTime(), compareIsoTime),
      "iso-date-time": fmtDef(getDateTime(), compareIsoDateTime),
      // duration: https://tools.ietf.org/html/rfc3339#appendix-A
      duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,
      uri,
      "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: https://tools.ietf.org/html/rfc6570
      "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,
      // For the source: https://gist.github.com/dperini/729294
      // For test cases: https://mathiasbynens.be/demo/url-regex
      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,
      // optimized https://www.safaribooksonline.com/library/view/regular-expressions-cookbook/9780596802837/ch07s16.html
      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,
      // uuid: http://tools.ietf.org/html/rfc4122
      uuid: /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,
      // JSON-pointer: https://tools.ietf.org/html/rfc6901
      // uri fragment: https://tools.ietf.org/html/rfc3986#appendix-A
      "json-pointer": /^(?:\/(?:[^~/]|~0|~1)*)*$/,
      "json-pointer-uri-fragment": /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,
      // relative JSON-pointer: http://tools.ietf.org/html/draft-luff-relative-json-pointer-00
      "relative-json-pointer": /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,
      // the following formats are used by the openapi specification: https://spec.openapis.org/oas/v3.0.0#data-types
      // byte: https://github.com/miguelmota/is-base64
      byte,
      // signed 32 bit integer
      int32: { type: "number", validate: validateInt32 },
      // signed 64 bit integer
      int64: { type: "number", validate: validateInt64 },
      // C-type float
      float: { type: "number", validate: validateNumber },
      // C-type double
      double: { type: "number", validate: validateNumber },
      // hint to the UI to hide input strings
      password: true,
      // unchecked string payload
      binary: true
    };
    exports.fastFormats = {
      ...exports.fullFormats,
      date: fmtDef(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, compareDate),
      time: fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, compareTime),
      "date-time": fmtDef(/^\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, compareDateTime),
      "iso-time": fmtDef(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, compareIsoTime),
      "iso-date-time": fmtDef(/^\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, compareIsoDateTime),
      // uri: https://github.com/mafintosh/is-my-json-valid/blob/master/formats.js
      uri: /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,
      "uri-reference": /^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,
      // email (sources from jsen validator):
      // http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address#answer-8829363
      // http://www.w3.org/TR/html5/forms.html#valid-e-mail-address (search for 'wilful violation')
      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
    };
    exports.formatNames = Object.keys(exports.fullFormats);
    function isLeapYear(year) {
      return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
    }
    var DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/;
    var DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
    function date7(str) {
      const matches = DATE.exec(str);
      if (!matches)
        return false;
      const year = +matches[1];
      const month = +matches[2];
      const day = +matches[3];
      return month >= 1 && month <= 12 && day >= 1 && day <= (month === 2 && isLeapYear(year) ? 29 : DAYS[month]);
    }
    function compareDate(d12, d22) {
      if (!(d12 && d22))
        return void 0;
      if (d12 > d22)
        return 1;
      if (d12 < d22)
        return -1;
      return 0;
    }
    var TIME = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
    function getTime(strictTimeZone) {
      return function time4(str) {
        const matches = TIME.exec(str);
        if (!matches)
          return false;
        const hr = +matches[1];
        const min = +matches[2];
        const sec = +matches[3];
        const tz2 = matches[4];
        const tzSign = matches[5] === "-" ? -1 : 1;
        const tzH = +(matches[6] || 0);
        const tzM = +(matches[7] || 0);
        if (tzH > 23 || tzM > 59 || strictTimeZone && !tz2)
          return false;
        if (hr <= 23 && min <= 59 && sec < 60)
          return true;
        const utcMin = min - tzM * tzSign;
        const utcHr = hr - tzH * tzSign - (utcMin < 0 ? 1 : 0);
        return (utcHr === 23 || utcHr === -1) && (utcMin === 59 || utcMin === -1) && sec < 61;
      };
    }
    function compareTime(s12, s22) {
      if (!(s12 && s22))
        return void 0;
      const t12 = (/* @__PURE__ */ new Date("2020-01-01T" + s12)).valueOf();
      const t2 = (/* @__PURE__ */ new Date("2020-01-01T" + s22)).valueOf();
      if (!(t12 && t2))
        return void 0;
      return t12 - t2;
    }
    function compareIsoTime(t12, t2) {
      if (!(t12 && t2))
        return void 0;
      const a12 = TIME.exec(t12);
      const a2 = TIME.exec(t2);
      if (!(a12 && a2))
        return void 0;
      t12 = a12[1] + a12[2] + a12[3];
      t2 = a2[1] + a2[2] + a2[3];
      if (t12 > t2)
        return 1;
      if (t12 < t2)
        return -1;
      return 0;
    }
    var DATE_TIME_SEPARATOR = /t|\s/i;
    function getDateTime(strictTimeZone) {
      const time4 = getTime(strictTimeZone);
      return function date_time(str) {
        const dateTime = str.split(DATE_TIME_SEPARATOR);
        return dateTime.length === 2 && date7(dateTime[0]) && time4(dateTime[1]);
      };
    }
    function compareDateTime(dt1, dt2) {
      if (!(dt1 && dt2))
        return void 0;
      const d12 = new Date(dt1).valueOf();
      const d22 = new Date(dt2).valueOf();
      if (!(d12 && d22))
        return void 0;
      return d12 - d22;
    }
    function compareIsoDateTime(dt1, dt2) {
      if (!(dt1 && dt2))
        return void 0;
      const [d12, t12] = dt1.split(DATE_TIME_SEPARATOR);
      const [d22, t2] = dt2.split(DATE_TIME_SEPARATOR);
      const res = compareDate(d12, d22);
      if (res === void 0)
        return void 0;
      return res || compareTime(t12, t2);
    }
    var NOT_URI_FRAGMENT = /\/|:/;
    var URI = /^(?:[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 uri(str) {
      return NOT_URI_FRAGMENT.test(str) && URI.test(str);
    }
    var BYTE = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
    function byte(str) {
      BYTE.lastIndex = 0;
      return BYTE.test(str);
    }
    var MIN_INT32 = -(2 ** 31);
    var MAX_INT32 = 2 ** 31 - 1;
    function validateInt32(value) {
      return Number.isInteger(value) && value <= MAX_INT32 && value >= MIN_INT32;
    }
    function validateInt64(value) {
      return Number.isInteger(value);
    }
    function validateNumber() {
      return true;
    }
    var Z_ANCHOR = /[^\\]\\Z/;
    function regex(str) {
      if (Z_ANCHOR.test(str))
        return false;
      try {
        new RegExp(str);
        return true;
      } catch (e2) {
        return false;
      }
    }
  }
});

// node_modules/ajv-formats/dist/limit.js
var require_limit = __commonJS({
  "node_modules/ajv-formats/dist/limit.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.formatLimitDefinition = void 0;
    var ajv_1 = require_ajv();
    var codegen_1 = require_codegen();
    var ops = codegen_1.operators;
    var KWDs = {
      formatMaximum: { okStr: "<=", ok: ops.LTE, fail: ops.GT },
      formatMinimum: { okStr: ">=", ok: ops.GTE, fail: ops.LT },
      formatExclusiveMaximum: { okStr: "<", ok: ops.LT, fail: ops.GTE },
      formatExclusiveMinimum: { okStr: ">", ok: ops.GT, fail: ops.LTE }
    };
    var error48 = {
      message: ({ keyword, schemaCode }) => (0, codegen_1.str)`should be ${KWDs[keyword].okStr} ${schemaCode}`,
      params: ({ keyword, schemaCode }) => (0, codegen_1._)`{comparison: ${KWDs[keyword].okStr}, limit: ${schemaCode}}`
    };
    exports.formatLimitDefinition = {
      keyword: Object.keys(KWDs),
      type: "string",
      schemaType: "string",
      $data: true,
      error: error48,
      code(cxt) {
        const { gen, data, schemaCode, keyword, it } = cxt;
        const { opts, self: self2 } = it;
        if (!opts.validateFormats)
          return;
        const fCxt = new ajv_1.KeywordCxt(it, self2.RULES.all.format.definition, "format");
        if (fCxt.$data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self2.formats,
            code: opts.code.formats
          });
          const fmt = gen.const("fmt", (0, codegen_1._)`${fmts}[${fCxt.schemaCode}]`);
          cxt.fail$data((0, codegen_1.or)((0, codegen_1._)`typeof ${fmt} != "object"`, (0, codegen_1._)`${fmt} instanceof RegExp`, (0, codegen_1._)`typeof ${fmt}.compare != "function"`, compareCode(fmt)));
        }
        function validateFormat() {
          const format = fCxt.schema;
          const fmtDef = self2.formats[format];
          if (!fmtDef || fmtDef === true)
            return;
          if (typeof fmtDef != "object" || fmtDef instanceof RegExp || typeof fmtDef.compare != "function") {
            throw new Error(`"${keyword}": format "${format}" does not define "compare" function`);
          }
          const fmt = gen.scopeValue("formats", {
            key: format,
            ref: fmtDef,
            code: opts.code.formats ? (0, codegen_1._)`${opts.code.formats}${(0, codegen_1.getProperty)(format)}` : void 0
          });
          cxt.fail$data(compareCode(fmt));
        }
        function compareCode(fmt) {
          return (0, codegen_1._)`${fmt}.compare(${data}, ${schemaCode}) ${KWDs[keyword].fail} 0`;
        }
      },
      dependencies: ["format"]
    };
    var formatLimitPlugin = (ajv) => {
      ajv.addKeyword(exports.formatLimitDefinition);
      return ajv;
    };
    exports.default = formatLimitPlugin;
  }
});

// node_modules/ajv-formats/dist/index.js
var require_dist = __commonJS({
  "node_modules/ajv-formats/dist/index.js"(exports, module2) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var formats_1 = require_formats();
    var limit_1 = require_limit();
    var codegen_1 = require_codegen();
    var fullName = new codegen_1.Name("fullFormats");
    var fastName = new codegen_1.Name("fastFormats");
    var formatsPlugin = (ajv, opts = { keywords: true }) => {
      if (Array.isArray(opts)) {
        addFormats(ajv, opts, formats_1.fullFormats, fullName);
        return ajv;
      }
      const [formats, exportName] = opts.mode === "fast" ? [formats_1.fastFormats, fastName] : [formats_1.fullFormats, fullName];
      const list = opts.formats || formats_1.formatNames;
      addFormats(ajv, list, formats, exportName);
      if (opts.keywords)
        (0, limit_1.default)(ajv);
      return ajv;
    };
    formatsPlugin.get = (name, mode = "full") => {
      const formats = mode === "fast" ? formats_1.fastFormats : formats_1.fullFormats;
      const f2 = formats[name];
      if (!f2)
        throw new Error(`Unknown format "${name}"`);
      return f2;
    };
    function addFormats(ajv, list, fs26, exportName) {
      var _a3;
      var _b2;
      (_a3 = (_b2 = ajv.opts.code).formats) !== null && _a3 !== void 0 ? _a3 : _b2.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`;
      for (const f2 of list)
        ajv.addFormat(f2, fs26[f2]);
    }
    module2.exports = exports = formatsPlugin;
    Object.defineProperty(exports, "__esModule", { value: true });
    exports.default = formatsPlugin;
  }
});

// node_modules/isexe/windows.js
var require_windows = __commonJS({
  "node_modules/isexe/windows.js"(exports, module2) {
    module2.exports = isexe;
    isexe.sync = sync;
    var fs26 = require("fs");
    function checkPathExt(path24, options) {
      var pathext = options.pathExt !== void 0 ? options.pathExt : process.env.PATHEXT;
      if (!pathext) {
        return true;
      }
      pathext = pathext.split(";");
      if (pathext.indexOf("") !== -1) {
        return true;
      }
      for (var i2 = 0; i2 < pathext.length; i2++) {
        var p = pathext[i2].toLowerCase();
        if (p && path24.substr(-p.length).toLowerCase() === p) {
          return true;
        }
      }
      return false;
    }
    function checkStat(stat, path24, options) {
      if (!stat.isSymbolicLink() && !stat.isFile()) {
        return false;
      }
      return checkPathExt(path24, options);
    }
    function isexe(path24, options, cb) {
      fs26.stat(path24, function(er, stat) {
        cb(er, er ? false : checkStat(stat, path24, options));
      });
    }
    function sync(path24, options) {
      return checkStat(fs26.statSync(path24), path24, options);
    }
  }
});

// node_modules/isexe/mode.js
var require_mode = __commonJS({
  "node_modules/isexe/mode.js"(exports, module2) {
    module2.exports = isexe;
    isexe.sync = sync;
    var fs26 = require("fs");
    function isexe(path24, options, cb) {
      fs26.stat(path24, function(er, stat) {
        cb(er, er ? false : checkStat(stat, options));
      });
    }
    function sync(path24, options) {
      return checkStat(fs26.statSync(path24), options);
    }
    function checkStat(stat, options) {
      return stat.isFile() && checkMode(stat, options);
    }
    function checkMode(stat, options) {
      var mod = stat.mode;
      var uid = stat.uid;
      var gid = stat.gid;
      var myUid = options.uid !== void 0 ? options.uid : process.getuid && process.getuid();
      var myGid = options.gid !== void 0 ? options.gid : process.getgid && process.getgid();
      var u = parseInt("100", 8);
      var g2 = parseInt("010", 8);
      var o2 = parseInt("001", 8);
      var ug = u | g2;
      var ret = mod & o2 || mod & g2 && gid === myGid || mod & u && uid === myUid || mod & ug && myUid === 0;
      return ret;
    }
  }
});

// node_modules/isexe/index.js
var require_isexe = __commonJS({
  "node_modules/isexe/index.js"(exports, module2) {
    var fs26 = require("fs");
    var core;
    if (process.platform === "win32" || global.TESTING_WINDOWS) {
      core = require_windows();
    } else {
      core = require_mode();
    }
    module2.exports = isexe;
    isexe.sync = sync;
    function isexe(path24, options, cb) {
      if (typeof options === "function") {
        cb = options;
        options = {};
      }
      if (!cb) {
        if (typeof Promise !== "function") {
          throw new TypeError("callback not provided");
        }
        return new Promise(function(resolve8, reject) {
          isexe(path24, options || {}, function(er, is) {
            if (er) {
              reject(er);
            } else {
              resolve8(is);
            }
          });
        });
      }
      core(path24, options || {}, function(er, is) {
        if (er) {
          if (er.code === "EACCES" || options && options.ignoreErrors) {
            er = null;
            is = false;
          }
        }
        cb(er, is);
      });
    }
    function sync(path24, options) {
      try {
        return core.sync(path24, options || {});
      } catch (er) {
        if (options && options.ignoreErrors || er.code === "EACCES") {
          return false;
        } else {
          throw er;
        }
      }
    }
  }
});

// node_modules/which/which.js
var require_which = __commonJS({
  "node_modules/which/which.js"(exports, module2) {
    var isWindows2 = process.platform === "win32" || process.env.OSTYPE === "cygwin" || process.env.OSTYPE === "msys";
    var path24 = require("path");
    var COLON = isWindows2 ? ";" : ":";
    var isexe = require_isexe();
    var getNotFoundError = (cmd) => Object.assign(new Error(`not found: ${cmd}`), { code: "ENOENT" });
    var getPathInfo = (cmd, opt) => {
      const colon = opt.colon || COLON;
      const pathEnv = cmd.match(/\//) || isWindows2 && cmd.match(/\\/) ? [""] : [
        // windows always checks the cwd first
        ...isWindows2 ? [process.cwd()] : [],
        ...(opt.path || process.env.PATH || /* istanbul ignore next: very unusual */
        "").split(colon)
      ];
      const pathExtExe = isWindows2 ? opt.pathExt || process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM" : "";
      const pathExt = isWindows2 ? pathExtExe.split(colon) : [""];
      if (isWindows2) {
        if (cmd.indexOf(".") !== -1 && pathExt[0] !== "")
          pathExt.unshift("");
      }
      return {
        pathEnv,
        pathExt,
        pathExtExe
      };
    };
    var which = (cmd, opt, cb) => {
      if (typeof opt === "function") {
        cb = opt;
        opt = {};
      }
      if (!opt)
        opt = {};
      const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
      const found = [];
      const step = (i2) => new Promise((resolve8, reject) => {
        if (i2 === pathEnv.length)
          return opt.all && found.length ? resolve8(found) : reject(getNotFoundError(cmd));
        const ppRaw = pathEnv[i2];
        const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
        const pCmd = path24.join(pathPart, cmd);
        const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
        resolve8(subStep(p, i2, 0));
      });
      const subStep = (p, i2, ii) => new Promise((resolve8, reject) => {
        if (ii === pathExt.length)
          return resolve8(step(i2 + 1));
        const ext = pathExt[ii];
        isexe(p + ext, { pathExt: pathExtExe }, (er, is) => {
          if (!er && is) {
            if (opt.all)
              found.push(p + ext);
            else
              return resolve8(p + ext);
          }
          return resolve8(subStep(p, i2, ii + 1));
        });
      });
      return cb ? step(0).then((res) => cb(null, res), cb) : step(0);
    };
    var whichSync = (cmd, opt) => {
      opt = opt || {};
      const { pathEnv, pathExt, pathExtExe } = getPathInfo(cmd, opt);
      const found = [];
      for (let i2 = 0; i2 < pathEnv.length; i2++) {
        const ppRaw = pathEnv[i2];
        const pathPart = /^".*"$/.test(ppRaw) ? ppRaw.slice(1, -1) : ppRaw;
        const pCmd = path24.join(pathPart, cmd);
        const p = !pathPart && /^\.[\\\/]/.test(cmd) ? cmd.slice(0, 2) + pCmd : pCmd;
        for (let j = 0; j < pathExt.length; j++) {
          const cur = p + pathExt[j];
          try {
            const is = isexe.sync(cur, { pathExt: pathExtExe });
            if (is) {
              if (opt.all)
                found.push(cur);
              else
                return cur;
            }
          } catch (ex) {
          }
        }
      }
      if (opt.all && found.length)
        return found;
      if (opt.nothrow)
        return null;
      throw getNotFoundError(cmd);
    };
    module2.exports = which;
    which.sync = whichSync;
  }
});

// node_modules/path-key/index.js
var require_path_key = __commonJS({
  "node_modules/path-key/index.js"(exports, module2) {
    "use strict";
    var pathKey = (options = {}) => {
      const environment = options.env || process.env;
      const platform = options.platform || process.platform;
      if (platform !== "win32") {
        return "PATH";
      }
      return Object.keys(environment).reverse().find((key) => key.toUpperCase() === "PATH") || "Path";
    };
    module2.exports = pathKey;
    module2.exports.default = pathKey;
  }
});

// node_modules/cross-spawn/lib/util/resolveCommand.js
var require_resolveCommand = __commonJS({
  "node_modules/cross-spawn/lib/util/resolveCommand.js"(exports, module2) {
    "use strict";
    var path24 = require("path");
    var which = require_which();
    var getPathKey = require_path_key();
    function resolveCommandAttempt(parsed, withoutPathExt) {
      const env = parsed.options.env || process.env;
      const cwd = process.cwd();
      const hasCustomCwd = parsed.options.cwd != null;
      const shouldSwitchCwd = hasCustomCwd && process.chdir !== void 0 && !process.chdir.disabled;
      if (shouldSwitchCwd) {
        try {
          process.chdir(parsed.options.cwd);
        } catch (err) {
        }
      }
      let resolved;
      try {
        resolved = which.sync(parsed.command, {
          path: env[getPathKey({ env })],
          pathExt: withoutPathExt ? path24.delimiter : void 0
        });
      } catch (e2) {
      } finally {
        if (shouldSwitchCwd) {
          process.chdir(cwd);
        }
      }
      if (resolved) {
        resolved = path24.resolve(hasCustomCwd ? parsed.options.cwd : "", resolved);
      }
      return resolved;
    }
    function resolveCommand(parsed) {
      return resolveCommandAttempt(parsed) || resolveCommandAttempt(parsed, true);
    }
    module2.exports = resolveCommand;
  }
});

// node_modules/cross-spawn/lib/util/escape.js
var require_escape = __commonJS({
  "node_modules/cross-spawn/lib/util/escape.js"(exports, module2) {
    "use strict";
    var metaCharsRegExp = /([()\][%!^"`<>&|;, *?])/g;
    function escapeCommand(arg) {
      arg = arg.replace(metaCharsRegExp, "^$1");
      return arg;
    }
    function escapeArgument(arg, doubleEscapeMetaChars) {
      arg = `${arg}`;
      arg = arg.replace(/(?=(\\+?)?)\1"/g, '$1$1\\"');
      arg = arg.replace(/(?=(\\+?)?)\1$/, "$1$1");
      arg = `"${arg}"`;
      arg = arg.replace(metaCharsRegExp, "^$1");
      if (doubleEscapeMetaChars) {
        arg = arg.replace(metaCharsRegExp, "^$1");
      }
      return arg;
    }
    module2.exports.command = escapeCommand;
    module2.exports.argument = escapeArgument;
  }
});

// node_modules/shebang-regex/index.js
var require_shebang_regex = __commonJS({
  "node_modules/shebang-regex/index.js"(exports, module2) {
    "use strict";
    module2.exports = /^#!(.*)/;
  }
});

// node_modules/shebang-command/index.js
var require_shebang_command = __commonJS({
  "node_modules/shebang-command/index.js"(exports, module2) {
    "use strict";
    var shebangRegex = require_shebang_regex();
    module2.exports = (string5 = "") => {
      const match = string5.match(shebangRegex);
      if (!match) {
        return null;
      }
      const [path24, argument] = match[0].replace(/#! ?/, "").split(" ");
      const binary = path24.split("/").pop();
      if (binary === "env") {
        return argument;
      }
      return argument ? `${binary} ${argument}` : binary;
    };
  }
});

// node_modules/cross-spawn/lib/util/readShebang.js
var require_readShebang = __commonJS({
  "node_modules/cross-spawn/lib/util/readShebang.js"(exports, module2) {
    "use strict";
    var fs26 = require("fs");
    var shebangCommand = require_shebang_command();
    function readShebang(command) {
      const size = 150;
      const buffer = Buffer.alloc(size);
      let fd2;
      try {
        fd2 = fs26.openSync(command, "r");
        fs26.readSync(fd2, buffer, 0, size, 0);
        fs26.closeSync(fd2);
      } catch (e2) {
      }
      return shebangCommand(buffer.toString());
    }
    module2.exports = readShebang;
  }
});

// node_modules/cross-spawn/lib/parse.js
var require_parse = __commonJS({
  "node_modules/cross-spawn/lib/parse.js"(exports, module2) {
    "use strict";
    var path24 = require("path");
    var resolveCommand = require_resolveCommand();
    var escape2 = require_escape();
    var readShebang = require_readShebang();
    var isWin = process.platform === "win32";
    var isExecutableRegExp = /\.(?:com|exe)$/i;
    var isCmdShimRegExp = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
    function detectShebang(parsed) {
      parsed.file = resolveCommand(parsed);
      const shebang = parsed.file && readShebang(parsed.file);
      if (shebang) {
        parsed.args.unshift(parsed.file);
        parsed.command = shebang;
        return resolveCommand(parsed);
      }
      return parsed.file;
    }
    function parseNonShell(parsed) {
      if (!isWin) {
        return parsed;
      }
      const commandFile = detectShebang(parsed);
      const needsShell = !isExecutableRegExp.test(commandFile);
      if (parsed.options.forceShell || needsShell) {
        const needsDoubleEscapeMetaChars = isCmdShimRegExp.test(commandFile);
        parsed.command = path24.normalize(parsed.command);
        parsed.command = escape2.command(parsed.command);
        parsed.args = parsed.args.map((arg) => escape2.argument(arg, needsDoubleEscapeMetaChars));
        const shellCommand = [parsed.command].concat(parsed.args).join(" ");
        parsed.args = ["/d", "/s", "/c", `"${shellCommand}"`];
        parsed.command = process.env.comspec || "cmd.exe";
        parsed.options.windowsVerbatimArguments = true;
      }
      return parsed;
    }
    function parse4(command, args, options) {
      if (args && !Array.isArray(args)) {
        options = args;
        args = null;
      }
      args = args ? args.slice(0) : [];
      options = Object.assign({}, options);
      const parsed = {
        command,
        args,
        options,
        file: void 0,
        original: {
          command,
          args
        }
      };
      return options.shell ? parsed : parseNonShell(parsed);
    }
    module2.exports = parse4;
  }
});

// node_modules/cross-spawn/lib/enoent.js
var require_enoent = __commonJS({
  "node_modules/cross-spawn/lib/enoent.js"(exports, module2) {
    "use strict";
    var isWin = process.platform === "win32";
    function notFoundError(original, syscall) {
      return Object.assign(new Error(`${syscall} ${original.command} ENOENT`), {
        code: "ENOENT",
        errno: "ENOENT",
        syscall: `${syscall} ${original.command}`,
        path: original.command,
        spawnargs: original.args
      });
    }
    function hookChildProcess(cp, parsed) {
      if (!isWin) {
        return;
      }
      const originalEmit = cp.emit;
      cp.emit = function(name, arg1) {
        if (name === "exit") {
          const err = verifyENOENT(arg1, parsed);
          if (err) {
            return originalEmit.call(cp, "error", err);
          }
        }
        return originalEmit.apply(cp, arguments);
      };
    }
    function verifyENOENT(status, parsed) {
      if (isWin && status === 1 && !parsed.file) {
        return notFoundError(parsed.original, "spawn");
      }
      return null;
    }
    function verifyENOENTSync(status, parsed) {
      if (isWin && status === 1 && !parsed.file) {
        return notFoundError(parsed.original, "spawnSync");
      }
      return null;
    }
    module2.exports = {
      hookChildProcess,
      verifyENOENT,
      verifyENOENTSync,
      notFoundError
    };
  }
});

// node_modules/cross-spawn/index.js
var require_cross_spawn = __commonJS({
  "node_modules/cross-spawn/index.js"(exports, module2) {
    "use strict";
    var cp = require("child_process");
    var parse4 = require_parse();
    var enoent = require_enoent();
    function spawn5(command, args, options) {
      const parsed = parse4(command, args, options);
      const spawned = cp.spawn(parsed.command, parsed.args, parsed.options);
      enoent.hookChildProcess(spawned, parsed);
      return spawned;
    }
    function spawnSync2(command, args, options) {
      const parsed = parse4(command, args, options);
      const result = cp.spawnSync(parsed.command, parsed.args, parsed.options);
      result.error = result.error || enoent.verifyENOENTSync(result.status, parsed);
      return result;
    }
    module2.exports = spawn5;
    module2.exports.spawn = spawn5;
    module2.exports.sync = spawnSync2;
    module2.exports._parse = parse4;
    module2.exports._enoent = enoent;
  }
});

// src/main.ts
var main_exports = {};
__export(main_exports, {
  default: () => ClaudianPlugin
});
module.exports = __toCommonJS(main_exports);

// src/utils/electronCompat.ts
function isAbortSignalLike(target) {
  if (!target || typeof target !== "object") return false;
  const t2 = target;
  return typeof t2.aborted === "boolean" && typeof t2.addEventListener === "function" && typeof t2.removeEventListener === "function";
}
function patchSetMaxListenersForElectron() {
  const events = require("events");
  if (events.setMaxListeners.__electronPatched) return;
  const original = events.setMaxListeners;
  const patched = function patchedSetMaxListeners(...args) {
    try {
      return original.apply(this, args);
    } catch (error48) {
      const eventTargets = args.slice(1);
      if (eventTargets.length > 0 && eventTargets.every(isAbortSignalLike)) {
        return;
      }
      throw error48;
    }
  };
  patched.__electronPatched = true;
  events.setMaxListeners = patched;
}

// src/core/providers/types.ts
var DEFAULT_CHAT_PROVIDER_ID = "claude";

// src/core/providers/ProviderRegistry.ts
var ProviderRegistry = class {
  static register(providerId, registration) {
    this.registrations[providerId] = registration;
  }
  static getProviderRegistration(providerId) {
    const registration = this.registrations[providerId];
    if (!registration) {
      throw new Error(`Provider "${providerId}" is not registered.`);
    }
    return registration;
  }
  static createChatRuntime(options) {
    var _a3;
    const providerId = (_a3 = options.providerId) != null ? _a3 : DEFAULT_CHAT_PROVIDER_ID;
    return this.getProviderRegistration(providerId).createRuntime(options);
  }
  static createTitleGenerationService(plugin, providerId = DEFAULT_CHAT_PROVIDER_ID) {
    return this.getProviderRegistration(providerId).createTitleGenerationService(plugin);
  }
  static createInstructionRefineService(plugin, providerId = DEFAULT_CHAT_PROVIDER_ID) {
    return this.getProviderRegistration(providerId).createInstructionRefineService(plugin);
  }
  static createInlineEditService(plugin, providerId = DEFAULT_CHAT_PROVIDER_ID) {
    return this.getProviderRegistration(providerId).createInlineEditService(plugin);
  }
  static getConversationHistoryService(providerId = DEFAULT_CHAT_PROVIDER_ID) {
    return this.getProviderRegistration(providerId).historyService;
  }
  static getTaskResultInterpreter(providerId = DEFAULT_CHAT_PROVIDER_ID) {
    return this.getProviderRegistration(providerId).taskResultInterpreter;
  }
  static getSubagentLifecycleAdapter(providerId = DEFAULT_CHAT_PROVIDER_ID) {
    var _a3;
    return (_a3 = this.getProviderRegistration(providerId).subagentLifecycleAdapter) != null ? _a3 : null;
  }
  static getCapabilities(providerId = DEFAULT_CHAT_PROVIDER_ID) {
    return this.getProviderRegistration(providerId).capabilities;
  }
  static getEnvironmentKeyPatterns(providerId) {
    var _a3;
    return (_a3 = this.getProviderRegistration(providerId).environmentKeyPatterns) != null ? _a3 : [];
  }
  static getChatUIConfig(providerId = DEFAULT_CHAT_PROVIDER_ID) {
    return this.getProviderRegistration(providerId).chatUIConfig;
  }
  static getSettingsReconciler(providerId = DEFAULT_CHAT_PROVIDER_ID) {
    return this.getProviderRegistration(providerId).settingsReconciler;
  }
  static getRegisteredProviderIds() {
    return Object.keys(this.registrations);
  }
  static getEnabledProviderIds(settings11) {
    return this.getRegisteredProviderIds().filter((providerId) => this.getProviderRegistration(providerId).isEnabled(settings11)).sort((a2, b10) => this.getProviderRegistration(a2).blankTabOrder - this.getProviderRegistration(b10).blankTabOrder);
  }
  static getProviderDisplayName(providerId) {
    return this.getProviderRegistration(providerId).displayName;
  }
  static isEnabled(providerId, settings11) {
    return this.getProviderRegistration(providerId).isEnabled(settings11);
  }
  static resolveSettingsProviderId(settings11) {
    var _a3;
    const current = settings11.settingsProvider;
    if (typeof current === "string") {
      const currentProvider = current;
      if (this.getRegisteredProviderIds().includes(currentProvider) && this.isEnabled(currentProvider, settings11)) {
        return currentProvider;
      }
    }
    if (this.isEnabled(DEFAULT_CHAT_PROVIDER_ID, settings11)) {
      return DEFAULT_CHAT_PROVIDER_ID;
    }
    return (_a3 = this.getEnabledProviderIds(settings11)[0]) != null ? _a3 : DEFAULT_CHAT_PROVIDER_ID;
  }
  static resolveProviderForModel(model, settings11 = {}, options = {}) {
    const providerIds = options.onlyEnabledProviders ? this.getEnabledProviderIds(settings11) : this.getRegisteredProviderIds();
    const fallbackProviderId = options.fallbackProviderId && (!options.onlyEnabledProviders || this.isEnabled(options.fallbackProviderId, settings11)) ? options.fallbackProviderId : options.onlyEnabledProviders ? this.resolveSettingsProviderId(settings11) : DEFAULT_CHAT_PROVIDER_ID;
    for (const providerId of providerIds) {
      if (providerId === fallbackProviderId) {
        continue;
      }
      if (this.getChatUIConfig(providerId).ownsModel(model, settings11)) {
        return providerId;
      }
    }
    return fallbackProviderId;
  }
  static getCustomModelIds(envVars) {
    const ids = /* @__PURE__ */ new Set();
    for (const providerId of this.getRegisteredProviderIds()) {
      for (const modelId of this.getChatUIConfig(providerId).getCustomModelIds(envVars)) {
        ids.add(modelId);
      }
    }
    return ids;
  }
};
ProviderRegistry.registrations = {};

// src/core/storage/HomeFileAdapter.ts
var fs = __toESM(require("fs"));
var os = __toESM(require("os"));
var path = __toESM(require("path"));
var HomeFileAdapter = class {
  constructor(root = os.homedir()) {
    this.root = root;
  }
  resolve(relativePath) {
    return path.join(this.root, relativePath);
  }
  async exists(p) {
    try {
      await fs.promises.access(this.resolve(p));
      return true;
    } catch (e2) {
      return false;
    }
  }
  async read(p) {
    return fs.promises.readFile(this.resolve(p), "utf-8");
  }
  async write(p, content) {
    const full = this.resolve(p);
    await fs.promises.mkdir(path.dirname(full), { recursive: true });
    await fs.promises.writeFile(full, content, "utf-8");
  }
  async delete(p) {
    try {
      await fs.promises.unlink(this.resolve(p));
    } catch (err) {
      if (err.code !== "ENOENT") throw err;
    }
  }
  async deleteFolder(p) {
    try {
      await fs.promises.rmdir(this.resolve(p));
    } catch (e2) {
    }
  }
  async listFolders(folder) {
    const full = this.resolve(folder);
    try {
      const entries = await fs.promises.readdir(full, { withFileTypes: true });
      return entries.filter((e2) => e2.isDirectory()).map((e2) => `${folder}/${e2.name}`);
    } catch (e2) {
      return [];
    }
  }
  async ensureFolder(p) {
    await fs.promises.mkdir(this.resolve(p), { recursive: true });
  }
};

// src/core/providers/ProviderWorkspaceRegistry.ts
var ProviderWorkspaceRegistry = class {
  static register(providerId, registration) {
    this.registrations[providerId] = registration;
  }
  static getWorkspaceRegistration(providerId) {
    const registration = this.registrations[providerId];
    if (!registration) {
      throw new Error(`Provider workspace "${providerId}" is not registered.`);
    }
    return registration;
  }
  static async initializeAll(plugin) {
    const providerIds = Object.keys(this.registrations);
    const storage = plugin.storage;
    const vaultAdapter = storage.getAdapter();
    const homeAdapter = new HomeFileAdapter();
    for (const providerId of providerIds) {
      this.services[providerId] = await this.getWorkspaceRegistration(providerId).initialize({
        plugin,
        storage,
        vaultAdapter,
        homeAdapter
      });
    }
  }
  static setServices(providerId, services) {
    if (services) {
      this.services[providerId] = services;
    } else {
      delete this.services[providerId];
    }
  }
  static clear() {
    this.services = {};
  }
  static getServices(providerId) {
    var _a3;
    return (_a3 = this.services[providerId]) != null ? _a3 : null;
  }
  static requireServices(providerId) {
    const services = this.getServices(providerId);
    if (!services) {
      throw new Error(`Provider workspace "${providerId}" is not initialized.`);
    }
    return services;
  }
  static getCommandCatalog(providerId) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.getServices(providerId)) == null ? void 0 : _a3.commandCatalog) != null ? _b2 : null;
  }
  static getAgentMentionProvider(providerId) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.getServices(providerId)) == null ? void 0 : _a3.agentMentionProvider) != null ? _b2 : null;
  }
  static async refreshAgentMentions(providerId) {
    var _a3, _b2;
    await ((_b2 = (_a3 = this.getServices(providerId)) == null ? void 0 : _a3.refreshAgentMentions) == null ? void 0 : _b2.call(_a3));
  }
  static getCliResolver(providerId) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.getServices(providerId)) == null ? void 0 : _a3.cliResolver) != null ? _b2 : null;
  }
  static getRuntimeCommandLoader(providerId) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.getServices(providerId)) == null ? void 0 : _a3.runtimeCommandLoader) != null ? _b2 : null;
  }
  static getTabWarmupPolicy(providerId) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.getServices(providerId)) == null ? void 0 : _a3.tabWarmupPolicy) != null ? _b2 : null;
  }
  static getMcpServerManager(providerId) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.getServices(providerId)) == null ? void 0 : _a3.mcpServerManager) != null ? _b2 : null;
  }
  static getSettingsTabRenderer(providerId) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.getServices(providerId)) == null ? void 0 : _a3.settingsTabRenderer) != null ? _b2 : null;
  }
};
ProviderWorkspaceRegistry.registrations = {};
ProviderWorkspaceRegistry.services = {};

// src/utils/mcp.ts
function extractMcpMentions(text, validNames) {
  const mentions = /* @__PURE__ */ new Set();
  const regex = /@([a-zA-Z0-9._-]+)(?!\/)/g;
  let match;
  while ((match = regex.exec(text)) !== null) {
    const name = match[1];
    if (validNames.has(name)) {
      mentions.add(name);
    }
  }
  return mentions;
}
function transformMcpMentions(text, validNames) {
  if (validNames.size === 0) return text;
  const sortedNames = Array.from(validNames).sort((a2, b10) => b10.length - a2.length);
  const escapedNames = sortedNames.map(escapeRegExp).join("|");
  const pattern = new RegExp(
    `@(${escapedNames})(?! MCP)(?!/)(?![a-zA-Z0-9_-])(?!\\.[a-zA-Z0-9_-])`,
    "g"
  );
  return text.replace(pattern, "@$1 MCP");
}
function escapeRegExp(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function parseCommand(command, providedArgs) {
  if (providedArgs && providedArgs.length > 0) {
    return { cmd: command, args: providedArgs };
  }
  const parts = splitCommandString(command);
  if (parts.length === 0) {
    return { cmd: "", args: [] };
  }
  return { cmd: parts[0], args: parts.slice(1) };
}
function splitCommandString(cmdStr) {
  const parts = [];
  let current = "";
  let inQuote = false;
  let quoteChar = "";
  for (let i2 = 0; i2 < cmdStr.length; i2++) {
    const char = cmdStr[i2];
    if ((char === '"' || char === "'") && !inQuote) {
      inQuote = true;
      quoteChar = char;
      continue;
    }
    if (char === quoteChar && inQuote) {
      inQuote = false;
      quoteChar = "";
      continue;
    }
    if (/\s/.test(char) && !inQuote) {
      if (current) {
        parts.push(current);
        current = "";
      }
      continue;
    }
    current += char;
  }
  if (current) {
    parts.push(current);
  }
  return parts;
}

// src/core/mcp/McpServerManager.ts
var McpServerManager = class {
  constructor(storage) {
    this.servers = [];
    this.storage = storage;
  }
  async loadServers() {
    this.servers = await this.storage.load();
  }
  getServers() {
    return this.servers;
  }
  getEnabledCount() {
    return this.servers.filter((s4) => s4.enabled).length;
  }
  /**
   * Get servers to include in SDK options.
   *
   * A server is included if:
   * - It is enabled AND
   * - Either context-saving is disabled OR the server is @-mentioned
   *
   * @param mentionedNames Set of server names that were @-mentioned in the prompt
   */
  getActiveServers(mentionedNames) {
    const result = {};
    for (const server of this.servers) {
      if (!server.enabled) continue;
      if (server.contextSaving && !mentionedNames.has(server.name)) {
        continue;
      }
      result[server.name] = server.config;
    }
    return result;
  }
  /**
   * Get disabled MCP tools formatted for SDK disallowedTools option.
   *
   * Only returns disabled tools from servers that would be active (same filter as getActiveServers).
   *
   * @param mentionedNames Set of server names that were @-mentioned in the prompt
   */
  getDisallowedMcpTools(mentionedNames) {
    return this.collectDisallowedTools(
      (s4) => !s4.contextSaving || mentionedNames.has(s4.name)
    );
  }
  /**
   * Get all disabled MCP tools from ALL enabled servers (ignoring @-mentions).
   *
   * Used for persistent queries to pre-register all disabled tools upfront,
   * so @-mentioning servers doesn't require cold start.
   */
  getAllDisallowedMcpTools() {
    return this.collectDisallowedTools().sort();
  }
  collectDisallowedTools(filter) {
    const disallowed = /* @__PURE__ */ new Set();
    for (const server of this.servers) {
      if (!server.enabled) continue;
      if (filter && !filter(server)) continue;
      if (!server.disabledTools || server.disabledTools.length === 0) continue;
      for (const tool of server.disabledTools) {
        const normalized = tool.trim();
        if (!normalized) continue;
        disallowed.add(`mcp__${server.name}__${normalized}`);
      }
    }
    return Array.from(disallowed);
  }
  hasServers() {
    return this.servers.length > 0;
  }
  getContextSavingServers() {
    return this.servers.filter((s4) => s4.enabled && s4.contextSaving);
  }
  getContextSavingNames() {
    return new Set(this.getContextSavingServers().map((s4) => s4.name));
  }
  /** Only matches against enabled servers with context-saving mode. */
  extractMentions(text) {
    return extractMcpMentions(text, this.getContextSavingNames());
  }
  /**
   * Appends " MCP" after each valid @mention. Applied to API requests only, not shown in UI.
   */
  transformMentions(text) {
    return transformMcpMentions(text, this.getContextSavingNames());
  }
};

// src/providers/claude/app/ClaudeWorkspaceServices.ts
init_path();

// src/providers/claude/agents/AgentManager.ts
var fs3 = __toESM(require("fs"));
var os3 = __toESM(require("os"));
var path3 = __toESM(require("path"));

// src/utils/frontmatter.ts
var import_obsidian = require("obsidian");
var FRONTMATTER_PATTERN = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?([\s\S]*)$/;
var VALID_KEY_PATTERN = /^[\w-]+$/;
function isValidKey(key) {
  return key.length > 0 && VALID_KEY_PATTERN.test(key);
}
function unquote(value) {
  if (value.startsWith('"') && value.endsWith('"') || value.startsWith("'") && value.endsWith("'")) {
    return value.slice(1, -1);
  }
  return value;
}
function parseScalarValue(rawValue) {
  const value = rawValue.trim();
  if (value === "true") return true;
  if (value === "false") return false;
  if (value === "null" || value === "") return null;
  if (!Number.isNaN(Number(value))) return Number(value);
  if (value.startsWith("[") && value.endsWith("]")) {
    return value.slice(1, -1).split(",").map((item) => item.trim()).filter(Boolean).map((item) => unquote(item));
  }
  return unquote(value);
}
function parseFrontmatterFallback(yamlContent) {
  const result = {};
  const lines = yamlContent.split(/\r?\n/);
  let currentListKey = null;
  let currentList = [];
  function flushList() {
    if (!currentListKey) return;
    result[currentListKey] = currentList;
    currentListKey = null;
    currentList = [];
  }
  let pendingBareKey = null;
  for (const line of lines) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) continue;
    if (currentListKey) {
      if (trimmed.startsWith("- ")) {
        currentList.push(parseScalarValue(trimmed.slice(2)));
        continue;
      }
      flushList();
    }
    if (pendingBareKey) {
      if (trimmed.startsWith("- ")) {
        currentListKey = pendingBareKey;
        currentList = [];
        pendingBareKey = null;
        currentList.push(parseScalarValue(trimmed.slice(2)));
        continue;
      }
      result[pendingBareKey] = "";
      pendingBareKey = null;
    }
    const colonIndex = trimmed.indexOf(": ");
    if (colonIndex === -1) {
      if (trimmed.endsWith(":")) {
        const key2 = trimmed.slice(0, -1).trim();
        if (isValidKey(key2)) {
          pendingBareKey = key2;
        }
      }
      continue;
    }
    const key = trimmed.slice(0, colonIndex).trim();
    if (!isValidKey(key)) continue;
    result[key] = parseScalarValue(trimmed.slice(colonIndex + 2));
  }
  if (pendingBareKey) {
    result[pendingBareKey] = "";
  }
  flushList();
  return result;
}
function parseFrontmatter(content) {
  const match = content.match(FRONTMATTER_PATTERN);
  if (!match) return null;
  try {
    const parsed = (0, import_obsidian.parseYaml)(match[1]);
    if (parsed !== null && parsed !== void 0 && typeof parsed !== "object") {
      return null;
    }
    return {
      frontmatter: parsed != null ? parsed : {},
      body: match[2]
    };
  } catch (e2) {
    const fallbackParsed = parseFrontmatterFallback(match[1]);
    if (Object.keys(fallbackParsed).length > 0) {
      return {
        frontmatter: fallbackParsed,
        body: match[2]
      };
    }
    return null;
  }
}
function extractString(fm, key) {
  const val = fm[key];
  if (typeof val === "string" && val.length > 0) return val;
  if (Array.isArray(val) && val.length > 0 && val.every((v2) => typeof v2 === "string")) {
    return val.map((v2) => `[${v2}]`).join(" ");
  }
  return void 0;
}
function normalizeStringArray(val) {
  if (val === void 0 || val === null) return void 0;
  if (Array.isArray(val)) {
    return val.map((v2) => String(v2).trim()).filter(Boolean);
  }
  if (typeof val === "string") {
    const trimmed = val.trim();
    if (!trimmed) return void 0;
    return trimmed.split(",").map((s4) => s4.trim()).filter(Boolean);
  }
  return void 0;
}
function extractStringArray(fm, key) {
  return normalizeStringArray(fm[key]);
}
function extractBoolean(fm, key) {
  const val = fm[key];
  if (typeof val === "boolean") return val;
  return void 0;
}
function isRecord(value) {
  return value != null && typeof value === "object" && !Array.isArray(value);
}
var MAX_SLUG_LENGTH = 64;
var SLUG_PATTERN = /^[a-z0-9-]+$/;
var YAML_RESERVED_WORDS = /* @__PURE__ */ new Set(["true", "false", "null", "yes", "no", "on", "off"]);
function validateSlugName(name, label) {
  if (!name) {
    return `${label} name is required`;
  }
  if (name.length > MAX_SLUG_LENGTH) {
    return `${label} name must be ${MAX_SLUG_LENGTH} characters or fewer`;
  }
  if (!SLUG_PATTERN.test(name)) {
    return `${label} name can only contain lowercase letters, numbers, and hyphens`;
  }
  if (YAML_RESERVED_WORDS.has(name)) {
    return `${label} name cannot be a YAML reserved word (true, false, null, yes, no, on, off)`;
  }
  return null;
}

// src/providers/claude/types/agent.ts
var AGENT_PERMISSION_MODES = ["default", "acceptEdits", "auto", "dontAsk", "bypassPermissions", "plan", "delegate"];

// src/providers/claude/agents/AgentStorage.ts
var KNOWN_AGENT_KEYS = /* @__PURE__ */ new Set([
  "name",
  "description",
  "tools",
  "disallowedTools",
  "model",
  "skills",
  "permissionMode",
  "hooks"
]);
function parseAgentFile(content) {
  const parsed = parseFrontmatter(content);
  if (!parsed) return null;
  const { frontmatter: fm, body } = parsed;
  const name = fm.name;
  const description = fm.description;
  if (typeof name !== "string" || !name.trim()) return null;
  if (typeof description !== "string" || !description.trim()) return null;
  const tools = fm.tools;
  const disallowedTools = fm.disallowedTools;
  if (tools !== void 0 && !isStringOrArray(tools)) return null;
  if (disallowedTools !== void 0 && !isStringOrArray(disallowedTools)) return null;
  const model = typeof fm.model === "string" ? fm.model : void 0;
  const extra = {};
  for (const key of Object.keys(fm)) {
    if (!KNOWN_AGENT_KEYS.has(key)) {
      extra[key] = fm[key];
    }
  }
  const frontmatter = {
    name,
    description,
    tools,
    disallowedTools,
    model,
    skills: extractStringArray(fm, "skills"),
    permissionMode: typeof fm.permissionMode === "string" ? fm.permissionMode : void 0,
    hooks: isRecord(fm.hooks) ? fm.hooks : void 0,
    extraFrontmatter: Object.keys(extra).length > 0 ? extra : void 0
  };
  return { frontmatter, body: body.trim() };
}
function isStringOrArray(value) {
  return typeof value === "string" || Array.isArray(value);
}
function parseToolsList(tools) {
  return normalizeStringArray(tools);
}
function parsePermissionMode(mode) {
  if (!mode) return void 0;
  const trimmed = mode.trim();
  if (AGENT_PERMISSION_MODES.includes(trimmed)) {
    return trimmed;
  }
  return void 0;
}
var VALID_MODELS = ["sonnet", "opus", "haiku", "inherit"];
function parseModel(model) {
  if (!model) return "inherit";
  const normalized = model.toLowerCase().trim();
  if (VALID_MODELS.includes(normalized)) {
    return normalized;
  }
  return "inherit";
}
function buildAgentFromFrontmatter(frontmatter, body, meta3) {
  return {
    id: meta3.id,
    name: frontmatter.name,
    description: frontmatter.description,
    prompt: body,
    tools: parseToolsList(frontmatter.tools),
    disallowedTools: parseToolsList(frontmatter.disallowedTools),
    model: parseModel(frontmatter.model),
    source: meta3.source,
    filePath: meta3.filePath,
    pluginName: meta3.pluginName,
    skills: frontmatter.skills,
    permissionMode: parsePermissionMode(frontmatter.permissionMode),
    hooks: frontmatter.hooks,
    extraFrontmatter: frontmatter.extraFrontmatter
  };
}

// src/providers/claude/agents/AgentManager.ts
var GLOBAL_AGENTS_DIR = path3.join(os3.homedir(), ".claude", "agents");
var VAULT_AGENTS_DIR = ".claude/agents";
var PLUGIN_AGENTS_DIR = "agents";
var FALLBACK_BUILTIN_AGENT_NAMES = ["Explore", "Plan", "Bash", "general-purpose"];
var BUILTIN_AGENT_DESCRIPTIONS = {
  "Explore": "Fast codebase exploration and search",
  "Plan": "Implementation planning and architecture",
  "Bash": "Command execution specialist",
  "general-purpose": "Multi-step tasks and complex workflows"
};
function makeBuiltinAgent(name) {
  var _a3;
  return {
    id: name,
    name: name.replace(/-/g, " ").replace(/\b\w/g, (l2) => l2.toUpperCase()),
    description: (_a3 = BUILTIN_AGENT_DESCRIPTIONS[name]) != null ? _a3 : "",
    prompt: "",
    // Built-in — prompt managed by SDK
    source: "builtin"
  };
}
function normalizePluginName(name) {
  return name.toLowerCase().replace(/\s+/g, "-");
}
var AgentManager = class {
  constructor(vaultPath, pluginManager) {
    this.agents = [];
    this.builtinAgentNames = FALLBACK_BUILTIN_AGENT_NAMES;
    this.vaultPath = vaultPath;
    this.pluginManager = pluginManager;
  }
  /** Built-in agents are those from init that are NOT loaded from files. */
  setBuiltinAgentNames(names) {
    this.builtinAgentNames = names;
    const fileAgentIds = new Set(
      this.agents.filter((a2) => a2.source !== "builtin").map((a2) => a2.id)
    );
    this.agents = [
      ...names.filter((n) => !fileAgentIds.has(n)).map(makeBuiltinAgent),
      ...this.agents.filter((a2) => a2.source !== "builtin")
    ];
  }
  async loadAgents() {
    this.agents = [];
    for (const name of this.builtinAgentNames) {
      this.addAgent(makeBuiltinAgent(name));
    }
    try {
      this.loadPluginAgents();
    } catch (e2) {
    }
    try {
      this.loadVaultAgents();
    } catch (e2) {
    }
    try {
      this.loadGlobalAgents();
    } catch (e2) {
    }
  }
  getAvailableAgents() {
    return [...this.agents];
  }
  getAgentById(id) {
    return this.agents.find((a2) => a2.id === id);
  }
  /** Used for @-mention filtering in the chat input. */
  searchAgents(query) {
    const q10 = query.toLowerCase();
    return this.agents.filter(
      (a2) => a2.name.toLowerCase().includes(q10) || a2.id.toLowerCase().includes(q10) || a2.description.toLowerCase().includes(q10)
    );
  }
  loadPluginAgents() {
    for (const plugin of this.pluginManager.getPlugins()) {
      if (!plugin.enabled) continue;
      const agentsDir = path3.join(plugin.installPath, PLUGIN_AGENTS_DIR);
      if (!fs3.existsSync(agentsDir)) continue;
      this.loadAgentsFromFiles(
        this.listMarkdownFiles(agentsDir),
        (filePath) => this.parsePluginAgentFromFile(filePath, plugin.name)
      );
    }
  }
  loadVaultAgents() {
    this.loadAgentsFromDirectory(path3.join(this.vaultPath, VAULT_AGENTS_DIR), "vault");
  }
  loadGlobalAgents() {
    this.loadAgentsFromDirectory(GLOBAL_AGENTS_DIR, "global");
  }
  loadAgentsFromDirectory(dir, source) {
    if (!fs3.existsSync(dir)) return;
    this.loadAgentsFromFiles(
      this.listMarkdownFiles(dir),
      (filePath) => this.parseAgentFromFile(filePath, source)
    );
  }
  listMarkdownFiles(dir) {
    const files = [];
    try {
      const entries = fs3.readdirSync(dir, { withFileTypes: true });
      for (const entry of entries) {
        if (entry.isFile() && entry.name.endsWith(".md")) {
          files.push(path3.join(dir, entry.name));
        }
      }
    } catch (e2) {
    }
    return files;
  }
  parsePluginAgentFromFile(filePath, pluginName) {
    return this.parseAgentDefinition(
      filePath,
      (agentName) => `${normalizePluginName(pluginName)}:${agentName}`,
      (frontmatter, body, id) => buildAgentFromFrontmatter(frontmatter, body, {
        id,
        source: "plugin",
        pluginName,
        filePath
      })
    );
  }
  parseAgentFromFile(filePath, source) {
    return this.parseAgentDefinition(
      filePath,
      (agentName) => agentName,
      (frontmatter, body, id) => buildAgentFromFrontmatter(frontmatter, body, {
        id,
        source,
        filePath
      })
    );
  }
  loadAgentsFromFiles(filePaths, loadAgent) {
    for (const filePath of filePaths) {
      this.addAgent(loadAgent(filePath));
    }
  }
  addAgent(agent) {
    if (!agent) {
      return;
    }
    if (this.agents.some((existing) => existing.id === agent.id)) {
      return;
    }
    this.agents.push(agent);
  }
  parseAgentDefinition(filePath, buildId, buildAgent) {
    try {
      const content = fs3.readFileSync(filePath, "utf-8");
      const parsed = parseAgentFile(content);
      if (!parsed) {
        return null;
      }
      const { frontmatter, body } = parsed;
      return buildAgent(frontmatter, body, buildId(frontmatter.name));
    } catch (e2) {
      return null;
    }
  }
};

// src/utils/slashCommand.ts
function extractFirstParagraph(content) {
  const paragraph = content.split(/\n\s*\n/).find((p) => p.trim());
  if (!paragraph) return void 0;
  return paragraph.trim().replace(/\n/g, " ");
}
function validateCommandName(name) {
  return validateSlugName(name, "Command");
}
function isSkill(cmd) {
  if (cmd.kind) return cmd.kind === "skill";
  return cmd.id.startsWith("skill-");
}
function parsedToSlashCommand(parsed, identity) {
  return {
    ...identity,
    description: parsed.description,
    argumentHint: parsed.argumentHint,
    allowedTools: parsed.allowedTools,
    model: parsed.model,
    content: parsed.promptContent,
    disableModelInvocation: parsed.disableModelInvocation,
    userInvocable: parsed.userInvocable,
    context: parsed.context,
    agent: parsed.agent,
    hooks: parsed.hooks
  };
}
function parseSlashCommandContent(content) {
  var _a3, _b2, _c, _d2;
  const parsed = parseFrontmatter(content);
  if (!parsed) {
    return { promptContent: content };
  }
  const fm = parsed.frontmatter;
  return {
    // Existing fields — support both kebab-case (file format) and camelCase
    description: extractString(fm, "description"),
    argumentHint: (_a3 = extractString(fm, "argument-hint")) != null ? _a3 : extractString(fm, "argumentHint"),
    allowedTools: (_b2 = extractStringArray(fm, "allowed-tools")) != null ? _b2 : extractStringArray(fm, "allowedTools"),
    model: extractString(fm, "model"),
    promptContent: parsed.body,
    // Skill fields — kebab-case preferred (CC file format), camelCase for backwards compat
    disableModelInvocation: (_c = extractBoolean(fm, "disable-model-invocation")) != null ? _c : extractBoolean(fm, "disableModelInvocation"),
    userInvocable: (_d2 = extractBoolean(fm, "user-invocable")) != null ? _d2 : extractBoolean(fm, "userInvocable"),
    context: extractString(fm, "context") === "fork" ? "fork" : void 0,
    agent: extractString(fm, "agent"),
    hooks: isRecord(fm.hooks) ? fm.hooks : void 0
  };
}
function normalizeArgumentHint(hint) {
  if (!hint) return hint;
  if (hint.includes("[") || hint.includes("<")) return hint;
  return `[${hint}]`;
}
function yamlString(value) {
  if (value.includes(":") || value.includes("#") || value.includes("\n") || value.startsWith(" ") || value.endsWith(" ") || value.startsWith("[") || value.startsWith("{")) {
    return `"${value.replace(/"/g, '\\"')}"`;
  }
  return value;
}
function serializeCommand(cmd) {
  const parsed = parseSlashCommandContent(cmd.content);
  return serializeSlashCommandMarkdown(cmd, parsed.promptContent);
}
function serializeSlashCommandMarkdown(cmd, body) {
  const lines = ["---"];
  if (cmd.name) {
    lines.push(`name: ${cmd.name}`);
  }
  if (cmd.description) {
    lines.push(`description: ${yamlString(cmd.description)}`);
  }
  if (cmd.argumentHint) {
    lines.push(`argument-hint: ${yamlString(cmd.argumentHint)}`);
  }
  if (cmd.allowedTools && cmd.allowedTools.length > 0) {
    lines.push("allowed-tools:");
    for (const tool of cmd.allowedTools) {
      lines.push(`  - ${yamlString(tool)}`);
    }
  }
  if (cmd.model) {
    lines.push(`model: ${cmd.model}`);
  }
  if (cmd.disableModelInvocation !== void 0) {
    lines.push(`disable-model-invocation: ${cmd.disableModelInvocation}`);
  }
  if (cmd.userInvocable !== void 0) {
    lines.push(`user-invocable: ${cmd.userInvocable}`);
  }
  if (cmd.context) {
    lines.push(`context: ${cmd.context}`);
  }
  if (cmd.agent) {
    lines.push(`agent: ${cmd.agent}`);
  }
  if (cmd.hooks !== void 0) {
    lines.push(`hooks: ${JSON.stringify(cmd.hooks)}`);
  }
  if (lines.length === 1) {
    lines.push("");
  }
  lines.push("---");
  lines.push(body);
  return lines.join("\n");
}

// src/providers/claude/commands/ClaudeCommandCatalog.ts
function slashCommandToEntry(cmd) {
  var _a3;
  const skill = isSkill(cmd);
  return {
    id: cmd.id,
    providerId: "claude",
    kind: skill ? "skill" : "command",
    name: cmd.name,
    description: cmd.description,
    content: cmd.content,
    argumentHint: cmd.argumentHint,
    allowedTools: cmd.allowedTools,
    model: cmd.model,
    disableModelInvocation: cmd.disableModelInvocation,
    userInvocable: cmd.userInvocable,
    context: cmd.context,
    agent: cmd.agent,
    hooks: cmd.hooks,
    scope: cmd.source === "sdk" ? "runtime" : "vault",
    source: (_a3 = cmd.source) != null ? _a3 : "user",
    isEditable: cmd.source !== "sdk",
    isDeletable: cmd.source !== "sdk",
    displayPrefix: "/",
    insertPrefix: "/"
  };
}
function entryToSlashCommand(entry) {
  return {
    id: entry.id,
    name: entry.name,
    description: entry.description,
    content: entry.content,
    argumentHint: entry.argumentHint,
    allowedTools: entry.allowedTools,
    model: entry.model,
    disableModelInvocation: entry.disableModelInvocation,
    userInvocable: entry.userInvocable,
    context: entry.context,
    agent: entry.agent,
    hooks: entry.hooks,
    source: entry.source,
    kind: entry.kind
  };
}
var BUILTIN_HIDDEN_COMMANDS = /* @__PURE__ */ new Set([
  "context",
  "cost",
  "debug",
  "extra-usage",
  "heapdump",
  "init",
  "insights",
  "loop",
  "schedule",
  "security-review",
  "simplify",
  "update-config"
]);
var ClaudeCommandCatalog = class {
  constructor(commandStorage, skillStorage, probe) {
    this.commandStorage = commandStorage;
    this.skillStorage = skillStorage;
    this.probe = probe;
    this.sdkCommands = [];
    this.probePromise = null;
  }
  setRuntimeCommands(commands) {
    this.sdkCommands = commands;
  }
  async listDropdownEntries(context) {
    void context;
    if (this.sdkCommands.length === 0 && this.probe) {
      await this.ensureProbed();
    }
    const runtimeEntries = this.sdkCommands.filter((cmd) => !BUILTIN_HIDDEN_COMMANDS.has(cmd.name.toLowerCase())).map(slashCommandToEntry);
    if (runtimeEntries.length > 0) {
      return runtimeEntries;
    }
    return this.listVaultEntries();
  }
  /** Probe the SDK for commands. Deduplicates concurrent calls. */
  async ensureProbed() {
    if (!this.probe) return;
    if (!this.probePromise) {
      this.probePromise = this.probe().then((commands) => {
        if (this.sdkCommands.length === 0 && commands.length > 0) {
          this.sdkCommands = commands;
        }
      }).catch(() => {
      }).finally(() => {
        this.probePromise = null;
      });
    }
    await this.probePromise;
  }
  async listVaultEntries() {
    const commands = await this.commandStorage.loadAll();
    const skills = await this.skillStorage.loadAll();
    return [...commands, ...skills].map(slashCommandToEntry);
  }
  async saveVaultEntry(entry) {
    const cmd = entryToSlashCommand(entry);
    if (entry.kind === "skill") {
      await this.skillStorage.save(cmd);
    } else {
      await this.commandStorage.save(cmd);
    }
  }
  async deleteVaultEntry(entry) {
    if (entry.kind === "skill") {
      await this.skillStorage.delete(entry.id);
    } else {
      await this.commandStorage.delete(entry.id);
    }
  }
  getDropdownConfig() {
    return {
      providerId: "claude",
      triggerChars: ["/"],
      builtInPrefix: "/",
      skillPrefix: "/",
      commandPrefix: "/"
    };
  }
  async refresh() {
  }
};

// node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs
var import_child_process = require("child_process");
var import_crypto = require("crypto");
var import_promises = require("fs/promises");
var import_module = require("module");
var import_os = require("os");
var import_path = require("path");
var import_url = require("url");
var import_events = require("events");
var import_child_process2 = require("child_process");
var import_readline = require("readline");
var import_os2 = require("os");
var import_path2 = require("path");
var import_crypto2 = require("crypto");
var import_promises2 = require("fs/promises");
var import_path3 = require("path");
var import_fs = require("fs");
var import_process = require("process");
var import_crypto3 = require("crypto");
var import_promises3 = require("fs/promises");
var import_path4 = require("path");
var r = __toESM(require("fs"), 1);
var import_promises4 = require("fs/promises");
var import_module2 = require("module");
var import_url2 = require("url");
var import_promises5 = require("fs/promises");
var import_events2 = require("events");
var import_fs2 = require("fs");
var import_promises6 = require("fs/promises");
var import_path5 = require("path");
var import_child_process3 = require("child_process");
var import_util = require("util");
var import_promises7 = require("fs/promises");
var import_path6 = require("path");
var import_fs3 = require("fs");
var import_promises8 = require("fs/promises");
var import_path7 = require("path");
var import_crypto4 = require("crypto");
var import_promises9 = require("fs/promises");
var import_path8 = require("path");
var import_promises10 = require("fs/promises");
var import_path9 = require("path");
var import_crypto5 = require("crypto");
var import_os3 = require("os");
var import_meta = {};
var Aj = Object.create;
var { getPrototypeOf: Ij, defineProperty: M5, getOwnPropertyNames: bj } = Object;
var Zj = Object.prototype.hasOwnProperty;
function Pj($) {
  return this[$];
}
var Rj;
var Ej;
var qH = ($, X, J) => {
  var Q = $ != null && typeof $ === "object";
  if (Q) {
    var Y = X ? Rj != null ? Rj : Rj = /* @__PURE__ */ new WeakMap() : Ej != null ? Ej : Ej = /* @__PURE__ */ new WeakMap(), W = Y.get($);
    if (W) return W;
  }
  J = $ != null ? Aj(Ij($)) : {};
  let z8 = X || !$ || !$.__esModule ? M5(J, "default", { value: $, enumerable: true }) : J;
  for (let G of bj($)) if (!Zj.call(z8, G)) M5(z8, G, { get: Pj.bind($, G), enumerable: true });
  if (Q) Y.set($, z8);
  return z8;
};
var k = ($, X) => () => (X || $((X = { exports: {} }).exports, X), X.exports);
var Sj = ($) => $;
function vj($, X) {
  this[$] = Sj.bind(null, X);
}
var H1 = ($, X) => {
  for (var J in X) M5($, J, { get: X[J], enumerable: true, configurable: true, set: vj.bind(X, J) });
};
var Cj = Symbol.dispose || /* @__PURE__ */ Symbol.for("Symbol.dispose");
var kj = Symbol.asyncDispose || /* @__PURE__ */ Symbol.for("Symbol.asyncDispose");
var w$ = ($, X, J) => {
  if (X != null) {
    if (typeof X !== "object" && typeof X !== "function") throw TypeError('Object expected to be assigned to "using" declaration');
    var Q;
    if (J) Q = X[kj];
    if (Q === void 0) Q = X[Cj];
    if (typeof Q !== "function") throw TypeError("Object not disposable");
    $.push([J, Q, X]);
  } else if (J) $.push([J]);
  return X;
};
var B$ = ($, X, J) => {
  var Q = typeof SuppressedError === "function" ? SuppressedError : function(z8, G, U, H) {
    return H = Error(U), H.name = "SuppressedError", H.error = z8, H.suppressed = G, H;
  }, Y = (z8) => X = J ? new Q(z8, X, "An error was suppressed during disposal") : (J = true, z8), W = (z8) => {
    while (z8 = $.pop()) try {
      var G = z8[1] && z8[1].call(z8[2]);
      if (z8[0]) return Promise.resolve(G).then(W, (U) => (Y(U), W()));
    } catch (U) {
      Y(U);
    }
    if (J) throw X;
  };
  return W();
};
var f9 = k((Jw) => {
  Object.defineProperty(Jw, "__esModule", { value: true });
  Jw.regexpCode = Jw.getEsmExportName = Jw.getProperty = Jw.safeStringify = Jw.stringify = Jw.strConcat = Jw.addCodeArg = Jw.str = Jw._ = Jw.nil = Jw._Code = Jw.Name = Jw.IDENTIFIER = Jw._CodeOrName = void 0;
  class xQ {
  }
  Jw._CodeOrName = xQ;
  Jw.IDENTIFIER = /^[a-z$_][a-z$_0-9]*$/i;
  class r0 extends xQ {
    constructor($) {
      super();
      if (!Jw.IDENTIFIER.test($)) throw Error("CodeGen: name must be a valid identifier");
      this.str = $;
    }
    toString() {
      return this.str;
    }
    emptyStr() {
      return false;
    }
    get names() {
      return { [this.str]: 1 };
    }
  }
  Jw.Name = r0;
  class u6 extends xQ {
    constructor($) {
      super();
      this._items = typeof $ === "string" ? [$] : $;
    }
    toString() {
      return this.str;
    }
    emptyStr() {
      if (this._items.length > 1) return false;
      let $ = this._items[0];
      return $ === "" || $ === '""';
    }
    get str() {
      var $;
      return ($ = this._str) !== null && $ !== void 0 ? $ : this._str = this._items.reduce((X, J) => `${X}${J}`, "");
    }
    get names() {
      var $;
      return ($ = this._names) !== null && $ !== void 0 ? $ : this._names = this._items.reduce((X, J) => {
        if (J instanceof r0) X[J.str] = (X[J.str] || 0) + 1;
        return X;
      }, {});
    }
  }
  Jw._Code = u6;
  Jw.nil = new u6("");
  function $w($, ...X) {
    let J = [$[0]], Q = 0;
    while (Q < X.length) rG(J, X[Q]), J.push($[++Q]);
    return new u6(J);
  }
  Jw._ = $w;
  var nG = new u6("+");
  function Xw($, ...X) {
    let J = [y9($[0])], Q = 0;
    while (Q < X.length) J.push(nG), rG(J, X[Q]), J.push(nG, y9($[++Q]));
    return xR(J), new u6(J);
  }
  Jw.str = Xw;
  function rG($, X) {
    if (X instanceof u6) $.push(...X._items);
    else if (X instanceof r0) $.push(X);
    else $.push(fR(X));
  }
  Jw.addCodeArg = rG;
  function xR($) {
    let X = 1;
    while (X < $.length - 1) {
      if ($[X] === nG) {
        let J = TR($[X - 1], $[X + 1]);
        if (J !== void 0) {
          $.splice(X - 1, 3, J);
          continue;
        }
        $[X++] = "+";
      }
      X++;
    }
  }
  function TR($, X) {
    if (X === '""') return $;
    if ($ === '""') return X;
    if (typeof $ == "string") {
      if (X instanceof r0 || $[$.length - 1] !== '"') return;
      if (typeof X != "string") return `${$.slice(0, -1)}${X}"`;
      if (X[0] === '"') return $.slice(0, -1) + X.slice(1);
      return;
    }
    if (typeof X == "string" && X[0] === '"' && !($ instanceof r0)) return `"${$}${X.slice(1)}`;
    return;
  }
  function yR($, X) {
    return X.emptyStr() ? $ : $.emptyStr() ? X : Xw`${$}${X}`;
  }
  Jw.strConcat = yR;
  function fR($) {
    return typeof $ == "number" || typeof $ == "boolean" || $ === null ? $ : y9(Array.isArray($) ? $.join(",") : $);
  }
  function gR($) {
    return new u6(y9($));
  }
  Jw.stringify = gR;
  function y9($) {
    return JSON.stringify($).replace(/\u2028/g, "\\u2028").replace(/\u2029/g, "\\u2029");
  }
  Jw.safeStringify = y9;
  function hR($) {
    return typeof $ == "string" && Jw.IDENTIFIER.test($) ? new u6(`.${$}`) : $w`[${$}]`;
  }
  Jw.getProperty = hR;
  function uR($) {
    if (typeof $ == "string" && Jw.IDENTIFIER.test($)) return new u6(`${$}`);
    throw Error(`CodeGen: invalid export name: ${$}, use explicit $id name mapping`);
  }
  Jw.getEsmExportName = uR;
  function mR($) {
    return new u6($.toString());
  }
  Jw.regexpCode = mR;
});
var sG = k((zw) => {
  Object.defineProperty(zw, "__esModule", { value: true });
  zw.ValueScope = zw.ValueScopeName = zw.Scope = zw.varKinds = zw.UsedValueState = void 0;
  var H6 = f9();
  class Qw extends Error {
    constructor($) {
      super(`CodeGen: "code" for ${$} not defined`);
      this.value = $.value;
    }
  }
  var yQ;
  (function($) {
    $[$.Started = 0] = "Started", $[$.Completed = 1] = "Completed";
  })(yQ || (zw.UsedValueState = yQ = {}));
  zw.varKinds = { const: new H6.Name("const"), let: new H6.Name("let"), var: new H6.Name("var") };
  class tG {
    constructor({ prefixes: $, parent: X } = {}) {
      this._names = {}, this._prefixes = $, this._parent = X;
    }
    toName($) {
      return $ instanceof H6.Name ? $ : this.name($);
    }
    name($) {
      return new H6.Name(this._newName($));
    }
    _newName($) {
      let X = this._names[$] || this._nameGroup($);
      return `${$}${X.index++}`;
    }
    _nameGroup($) {
      var X, J;
      if (((J = (X = this._parent) === null || X === void 0 ? void 0 : X._prefixes) === null || J === void 0 ? void 0 : J.has($)) || this._prefixes && !this._prefixes.has($)) throw Error(`CodeGen: prefix "${$}" is not allowed in this scope`);
      return this._names[$] = { prefix: $, index: 0 };
    }
  }
  zw.Scope = tG;
  class aG extends H6.Name {
    constructor($, X) {
      super(X);
      this.prefix = $;
    }
    setValue($, { property: X, itemIndex: J }) {
      this.value = $, this.scopePath = H6._`.${new H6.Name(X)}[${J}]`;
    }
  }
  zw.ValueScopeName = aG;
  var $E = H6._`\n`;
  class Ww extends tG {
    constructor($) {
      super($);
      this._values = {}, this._scope = $.scope, this.opts = { ...$, _n: $.lines ? $E : H6.nil };
    }
    get() {
      return this._scope;
    }
    name($) {
      return new aG($, this._newName($));
    }
    value($, X) {
      var J;
      if (X.ref === void 0) throw Error("CodeGen: ref must be passed in value");
      let Q = this.toName($), { prefix: Y } = Q, W = (J = X.key) !== null && J !== void 0 ? J : X.ref, z8 = this._values[Y];
      if (z8) {
        let H = z8.get(W);
        if (H) return H;
      } else z8 = this._values[Y] = /* @__PURE__ */ new Map();
      z8.set(W, Q);
      let G = this._scope[Y] || (this._scope[Y] = []), U = G.length;
      return G[U] = X.ref, Q.setValue(X, { property: Y, itemIndex: U }), Q;
    }
    getValue($, X) {
      let J = this._values[$];
      if (!J) return;
      return J.get(X);
    }
    scopeRefs($, X = this._values) {
      return this._reduceValues(X, (J) => {
        if (J.scopePath === void 0) throw Error(`CodeGen: name "${J}" has no value`);
        return H6._`${$}${J.scopePath}`;
      });
    }
    scopeCode($ = this._values, X, J) {
      return this._reduceValues($, (Q) => {
        if (Q.value === void 0) throw Error(`CodeGen: name "${Q}" has no value`);
        return Q.value.code;
      }, X, J);
    }
    _reduceValues($, X, J = {}, Q) {
      let Y = H6.nil;
      for (let W in $) {
        let z8 = $[W];
        if (!z8) continue;
        let G = J[W] = J[W] || /* @__PURE__ */ new Map();
        z8.forEach((U) => {
          if (G.has(U)) return;
          G.set(U, yQ.Started);
          let H = X(U);
          if (H) {
            let K = this.opts.es5 ? zw.varKinds.var : zw.varKinds.const;
            Y = H6._`${Y}${K} ${U} = ${H};${this.opts._n}`;
          } else if (H = Q === null || Q === void 0 ? void 0 : Q(U)) Y = H6._`${Y}${H}${this.opts._n}`;
          else throw new Qw(U);
          G.set(U, yQ.Completed);
        });
      }
      return Y;
    }
  }
  zw.ValueScope = Ww;
});
var a = k((K6) => {
  Object.defineProperty(K6, "__esModule", { value: true });
  K6.or = K6.and = K6.not = K6.CodeGen = K6.operators = K6.varKinds = K6.ValueScopeName = K6.ValueScope = K6.Scope = K6.Name = K6.regexpCode = K6.stringify = K6.getProperty = K6.nil = K6.strConcat = K6.str = K6._ = void 0;
  var Y$ = f9(), m6 = sG(), e4 = f9();
  Object.defineProperty(K6, "_", { enumerable: true, get: function() {
    return e4._;
  } });
  Object.defineProperty(K6, "str", { enumerable: true, get: function() {
    return e4.str;
  } });
  Object.defineProperty(K6, "strConcat", { enumerable: true, get: function() {
    return e4.strConcat;
  } });
  Object.defineProperty(K6, "nil", { enumerable: true, get: function() {
    return e4.nil;
  } });
  Object.defineProperty(K6, "getProperty", { enumerable: true, get: function() {
    return e4.getProperty;
  } });
  Object.defineProperty(K6, "stringify", { enumerable: true, get: function() {
    return e4.stringify;
  } });
  Object.defineProperty(K6, "regexpCode", { enumerable: true, get: function() {
    return e4.regexpCode;
  } });
  Object.defineProperty(K6, "Name", { enumerable: true, get: function() {
    return e4.Name;
  } });
  var lQ = sG();
  Object.defineProperty(K6, "Scope", { enumerable: true, get: function() {
    return lQ.Scope;
  } });
  Object.defineProperty(K6, "ValueScope", { enumerable: true, get: function() {
    return lQ.ValueScope;
  } });
  Object.defineProperty(K6, "ValueScopeName", { enumerable: true, get: function() {
    return lQ.ValueScopeName;
  } });
  Object.defineProperty(K6, "varKinds", { enumerable: true, get: function() {
    return lQ.varKinds;
  } });
  K6.operators = { GT: new Y$._Code(">"), GTE: new Y$._Code(">="), LT: new Y$._Code("<"), LTE: new Y$._Code("<="), EQ: new Y$._Code("==="), NEQ: new Y$._Code("!=="), NOT: new Y$._Code("!"), OR: new Y$._Code("||"), AND: new Y$._Code("&&"), ADD: new Y$._Code("+") };
  class $1 {
    optimizeNodes() {
      return this;
    }
    optimizeNames($, X) {
      return this;
    }
  }
  class Uw extends $1 {
    constructor($, X, J) {
      super();
      this.varKind = $, this.name = X, this.rhs = J;
    }
    render({ es5: $, _n: X }) {
      let J = $ ? m6.varKinds.var : this.varKind, Q = this.rhs === void 0 ? "" : ` = ${this.rhs}`;
      return `${J} ${this.name}${Q};` + X;
    }
    optimizeNames($, X) {
      if (!$[this.name.str]) return;
      if (this.rhs) this.rhs = t0(this.rhs, $, X);
      return this;
    }
    get names() {
      return this.rhs instanceof Y$._CodeOrName ? this.rhs.names : {};
    }
  }
  class XU extends $1 {
    constructor($, X, J) {
      super();
      this.lhs = $, this.rhs = X, this.sideEffects = J;
    }
    render({ _n: $ }) {
      return `${this.lhs} = ${this.rhs};` + $;
    }
    optimizeNames($, X) {
      if (this.lhs instanceof Y$.Name && !$[this.lhs.str] && !this.sideEffects) return;
      return this.rhs = t0(this.rhs, $, X), this;
    }
    get names() {
      let $ = this.lhs instanceof Y$.Name ? {} : { ...this.lhs.names };
      return mQ($, this.rhs);
    }
  }
  class Hw extends XU {
    constructor($, X, J, Q) {
      super($, J, Q);
      this.op = X;
    }
    render({ _n: $ }) {
      return `${this.lhs} ${this.op}= ${this.rhs};` + $;
    }
  }
  class Kw extends $1 {
    constructor($) {
      super();
      this.label = $, this.names = {};
    }
    render({ _n: $ }) {
      return `${this.label}:` + $;
    }
  }
  class Vw extends $1 {
    constructor($) {
      super();
      this.label = $, this.names = {};
    }
    render({ _n: $ }) {
      return `break${this.label ? ` ${this.label}` : ""};` + $;
    }
  }
  class Nw extends $1 {
    constructor($) {
      super();
      this.error = $;
    }
    render({ _n: $ }) {
      return `throw ${this.error};` + $;
    }
    get names() {
      return this.error.names;
    }
  }
  class Ow extends $1 {
    constructor($) {
      super();
      this.code = $;
    }
    render({ _n: $ }) {
      return `${this.code};` + $;
    }
    optimizeNodes() {
      return `${this.code}` ? this : void 0;
    }
    optimizeNames($, X) {
      return this.code = t0(this.code, $, X), this;
    }
    get names() {
      return this.code instanceof Y$._CodeOrName ? this.code.names : {};
    }
  }
  class cQ extends $1 {
    constructor($ = []) {
      super();
      this.nodes = $;
    }
    render($) {
      return this.nodes.reduce((X, J) => X + J.render($), "");
    }
    optimizeNodes() {
      let { nodes: $ } = this, X = $.length;
      while (X--) {
        let J = $[X].optimizeNodes();
        if (Array.isArray(J)) $.splice(X, 1, ...J);
        else if (J) $[X] = J;
        else $.splice(X, 1);
      }
      return $.length > 0 ? this : void 0;
    }
    optimizeNames($, X) {
      let { nodes: J } = this, Q = J.length;
      while (Q--) {
        let Y = J[Q];
        if (Y.optimizeNames($, X)) continue;
        QE($, Y.names), J.splice(Q, 1);
      }
      return J.length > 0 ? this : void 0;
    }
    get names() {
      return this.nodes.reduce(($, X) => y1($, X.names), {});
    }
  }
  class X1 extends cQ {
    render($) {
      return "{" + $._n + super.render($) + "}" + $._n;
    }
  }
  class ww extends cQ {
  }
  class g9 extends X1 {
  }
  g9.kind = "else";
  class I4 extends X1 {
    constructor($, X) {
      super(X);
      this.condition = $;
    }
    render($) {
      let X = `if(${this.condition})` + super.render($);
      if (this.else) X += "else " + this.else.render($);
      return X;
    }
    optimizeNodes() {
      super.optimizeNodes();
      let $ = this.condition;
      if ($ === true) return this.nodes;
      let X = this.else;
      if (X) {
        let J = X.optimizeNodes();
        X = this.else = Array.isArray(J) ? new g9(J) : J;
      }
      if (X) {
        if ($ === false) return X instanceof I4 ? X : X.nodes;
        if (this.nodes.length) return this;
        return new I4(jw($), X instanceof I4 ? [X] : X.nodes);
      }
      if ($ === false || !this.nodes.length) return;
      return this;
    }
    optimizeNames($, X) {
      var J;
      if (this.else = (J = this.else) === null || J === void 0 ? void 0 : J.optimizeNames($, X), !(super.optimizeNames($, X) || this.else)) return;
      return this.condition = t0(this.condition, $, X), this;
    }
    get names() {
      let $ = super.names;
      if (mQ($, this.condition), this.else) y1($, this.else.names);
      return $;
    }
  }
  I4.kind = "if";
  class o0 extends X1 {
  }
  o0.kind = "for";
  class Bw extends o0 {
    constructor($) {
      super();
      this.iteration = $;
    }
    render($) {
      return `for(${this.iteration})` + super.render($);
    }
    optimizeNames($, X) {
      if (!super.optimizeNames($, X)) return;
      return this.iteration = t0(this.iteration, $, X), this;
    }
    get names() {
      return y1(super.names, this.iteration.names);
    }
  }
  class qw extends o0 {
    constructor($, X, J, Q) {
      super();
      this.varKind = $, this.name = X, this.from = J, this.to = Q;
    }
    render($) {
      let X = $.es5 ? m6.varKinds.var : this.varKind, { name: J, from: Q, to: Y } = this;
      return `for(${X} ${J}=${Q}; ${J}<${Y}; ${J}++)` + super.render($);
    }
    get names() {
      let $ = mQ(super.names, this.from);
      return mQ($, this.to);
    }
  }
  class eG extends o0 {
    constructor($, X, J, Q) {
      super();
      this.loop = $, this.varKind = X, this.name = J, this.iterable = Q;
    }
    render($) {
      return `for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})` + super.render($);
    }
    optimizeNames($, X) {
      if (!super.optimizeNames($, X)) return;
      return this.iterable = t0(this.iterable, $, X), this;
    }
    get names() {
      return y1(super.names, this.iterable.names);
    }
  }
  class fQ extends X1 {
    constructor($, X, J) {
      super();
      this.name = $, this.args = X, this.async = J;
    }
    render($) {
      return `${this.async ? "async " : ""}function ${this.name}(${this.args})` + super.render($);
    }
  }
  fQ.kind = "func";
  class gQ extends cQ {
    render($) {
      return "return " + super.render($);
    }
  }
  gQ.kind = "return";
  class Lw extends X1 {
    render($) {
      let X = "try" + super.render($);
      if (this.catch) X += this.catch.render($);
      if (this.finally) X += this.finally.render($);
      return X;
    }
    optimizeNodes() {
      var $, X;
      return super.optimizeNodes(), ($ = this.catch) === null || $ === void 0 || $.optimizeNodes(), (X = this.finally) === null || X === void 0 || X.optimizeNodes(), this;
    }
    optimizeNames($, X) {
      var J, Q;
      return super.optimizeNames($, X), (J = this.catch) === null || J === void 0 || J.optimizeNames($, X), (Q = this.finally) === null || Q === void 0 || Q.optimizeNames($, X), this;
    }
    get names() {
      let $ = super.names;
      if (this.catch) y1($, this.catch.names);
      if (this.finally) y1($, this.finally.names);
      return $;
    }
  }
  class hQ extends X1 {
    constructor($) {
      super();
      this.error = $;
    }
    render($) {
      return `catch(${this.error})` + super.render($);
    }
  }
  hQ.kind = "catch";
  class uQ extends X1 {
    render($) {
      return "finally" + super.render($);
    }
  }
  uQ.kind = "finally";
  class Dw {
    constructor($, X = {}) {
      this._values = {}, this._blockStarts = [], this._constants = {}, this.opts = { ...X, _n: X.lines ? `
` : "" }, this._extScope = $, this._scope = new m6.Scope({ parent: $ }), this._nodes = [new ww()];
    }
    toString() {
      return this._root.render(this.opts);
    }
    name($) {
      return this._scope.name($);
    }
    scopeName($) {
      return this._extScope.name($);
    }
    scopeValue($, X) {
      let J = this._extScope.value($, X);
      return (this._values[J.prefix] || (this._values[J.prefix] = /* @__PURE__ */ new Set())).add(J), J;
    }
    getScopeValue($, X) {
      return this._extScope.getValue($, X);
    }
    scopeRefs($) {
      return this._extScope.scopeRefs($, this._values);
    }
    scopeCode() {
      return this._extScope.scopeCode(this._values);
    }
    _def($, X, J, Q) {
      let Y = this._scope.toName(X);
      if (J !== void 0 && Q) this._constants[Y.str] = J;
      return this._leafNode(new Uw($, Y, J)), Y;
    }
    const($, X, J) {
      return this._def(m6.varKinds.const, $, X, J);
    }
    let($, X, J) {
      return this._def(m6.varKinds.let, $, X, J);
    }
    var($, X, J) {
      return this._def(m6.varKinds.var, $, X, J);
    }
    assign($, X, J) {
      return this._leafNode(new XU($, X, J));
    }
    add($, X) {
      return this._leafNode(new Hw($, K6.operators.ADD, X));
    }
    code($) {
      if (typeof $ == "function") $();
      else if ($ !== Y$.nil) this._leafNode(new Ow($));
      return this;
    }
    object(...$) {
      let X = ["{"];
      for (let [J, Q] of $) {
        if (X.length > 1) X.push(",");
        if (X.push(J), J !== Q || this.opts.es5) X.push(":"), (0, Y$.addCodeArg)(X, Q);
      }
      return X.push("}"), new Y$._Code(X);
    }
    if($, X, J) {
      if (this._blockNode(new I4($)), X && J) this.code(X).else().code(J).endIf();
      else if (X) this.code(X).endIf();
      else if (J) throw Error('CodeGen: "else" body without "then" body');
      return this;
    }
    elseIf($) {
      return this._elseNode(new I4($));
    }
    else() {
      return this._elseNode(new g9());
    }
    endIf() {
      return this._endBlockNode(I4, g9);
    }
    _for($, X) {
      if (this._blockNode($), X) this.code(X).endFor();
      return this;
    }
    for($, X) {
      return this._for(new Bw($), X);
    }
    forRange($, X, J, Q, Y = this.opts.es5 ? m6.varKinds.var : m6.varKinds.let) {
      let W = this._scope.toName($);
      return this._for(new qw(Y, W, X, J), () => Q(W));
    }
    forOf($, X, J, Q = m6.varKinds.const) {
      let Y = this._scope.toName($);
      if (this.opts.es5) {
        let W = X instanceof Y$.Name ? X : this.var("_arr", X);
        return this.forRange("_i", 0, Y$._`${W}.length`, (z8) => {
          this.var(Y, Y$._`${W}[${z8}]`), J(Y);
        });
      }
      return this._for(new eG("of", Q, Y, X), () => J(Y));
    }
    forIn($, X, J, Q = this.opts.es5 ? m6.varKinds.var : m6.varKinds.const) {
      if (this.opts.ownProperties) return this.forOf($, Y$._`Object.keys(${X})`, J);
      let Y = this._scope.toName($);
      return this._for(new eG("in", Q, Y, X), () => J(Y));
    }
    endFor() {
      return this._endBlockNode(o0);
    }
    label($) {
      return this._leafNode(new Kw($));
    }
    break($) {
      return this._leafNode(new Vw($));
    }
    return($) {
      let X = new gQ();
      if (this._blockNode(X), this.code($), X.nodes.length !== 1) throw Error('CodeGen: "return" should have one node');
      return this._endBlockNode(gQ);
    }
    try($, X, J) {
      if (!X && !J) throw Error('CodeGen: "try" without "catch" and "finally"');
      let Q = new Lw();
      if (this._blockNode(Q), this.code($), X) {
        let Y = this.name("e");
        this._currNode = Q.catch = new hQ(Y), X(Y);
      }
      if (J) this._currNode = Q.finally = new uQ(), this.code(J);
      return this._endBlockNode(hQ, uQ);
    }
    throw($) {
      return this._leafNode(new Nw($));
    }
    block($, X) {
      if (this._blockStarts.push(this._nodes.length), $) this.code($).endBlock(X);
      return this;
    }
    endBlock($) {
      let X = this._blockStarts.pop();
      if (X === void 0) throw Error("CodeGen: not in self-balancing block");
      let J = this._nodes.length - X;
      if (J < 0 || $ !== void 0 && J !== $) throw Error(`CodeGen: wrong number of nodes: ${J} vs ${$} expected`);
      return this._nodes.length = X, this;
    }
    func($, X = Y$.nil, J, Q) {
      if (this._blockNode(new fQ($, X, J)), Q) this.code(Q).endFunc();
      return this;
    }
    endFunc() {
      return this._endBlockNode(fQ);
    }
    optimize($ = 1) {
      while ($-- > 0) this._root.optimizeNodes(), this._root.optimizeNames(this._root.names, this._constants);
    }
    _leafNode($) {
      return this._currNode.nodes.push($), this;
    }
    _blockNode($) {
      this._currNode.nodes.push($), this._nodes.push($);
    }
    _endBlockNode($, X) {
      let J = this._currNode;
      if (J instanceof $ || X && J instanceof X) return this._nodes.pop(), this;
      throw Error(`CodeGen: not in block "${X ? `${$.kind}/${X.kind}` : $.kind}"`);
    }
    _elseNode($) {
      let X = this._currNode;
      if (!(X instanceof I4)) throw Error('CodeGen: "else" without "if"');
      return this._currNode = X.else = $, this;
    }
    get _root() {
      return this._nodes[0];
    }
    get _currNode() {
      let $ = this._nodes;
      return $[$.length - 1];
    }
    set _currNode($) {
      let X = this._nodes;
      X[X.length - 1] = $;
    }
  }
  K6.CodeGen = Dw;
  function y1($, X) {
    for (let J in X) $[J] = ($[J] || 0) + (X[J] || 0);
    return $;
  }
  function mQ($, X) {
    return X instanceof Y$._CodeOrName ? y1($, X.names) : $;
  }
  function t0($, X, J) {
    if ($ instanceof Y$.Name) return Q($);
    if (!Y($)) return $;
    return new Y$._Code($._items.reduce((W, z8) => {
      if (z8 instanceof Y$.Name) z8 = Q(z8);
      if (z8 instanceof Y$._Code) W.push(...z8._items);
      else W.push(z8);
      return W;
    }, []));
    function Q(W) {
      let z8 = J[W.str];
      if (z8 === void 0 || X[W.str] !== 1) return W;
      return delete X[W.str], z8;
    }
    function Y(W) {
      return W instanceof Y$._Code && W._items.some((z8) => z8 instanceof Y$.Name && X[z8.str] === 1 && J[z8.str] !== void 0);
    }
  }
  function QE($, X) {
    for (let J in X) $[J] = ($[J] || 0) - (X[J] || 0);
  }
  function jw($) {
    return typeof $ == "boolean" || typeof $ == "number" || $ === null ? !$ : Y$._`!${$U($)}`;
  }
  K6.not = jw;
  var WE = Fw(K6.operators.AND);
  function zE(...$) {
    return $.reduce(WE);
  }
  K6.and = zE;
  var GE = Fw(K6.operators.OR);
  function UE(...$) {
    return $.reduce(GE);
  }
  K6.or = UE;
  function Fw($) {
    return (X, J) => X === Y$.nil ? J : J === Y$.nil ? X : Y$._`${$U(X)} ${$} ${$U(J)}`;
  }
  function $U($) {
    return $ instanceof Y$.Name ? $ : Y$._`(${$})`;
  }
});
var Q$ = k((Sw) => {
  Object.defineProperty(Sw, "__esModule", { value: true });
  Sw.checkStrictMode = Sw.getErrorPath = Sw.Type = Sw.useFunc = Sw.setEvaluated = Sw.evaluatedPropsToName = Sw.mergeEvaluated = Sw.eachItem = Sw.unescapeJsonPointer = Sw.escapeJsonPointer = Sw.escapeFragment = Sw.unescapeFragment = Sw.schemaRefOrVal = Sw.schemaHasRulesButRef = Sw.schemaHasRules = Sw.checkUnknownRules = Sw.alwaysValidSchema = Sw.toHash = void 0;
  var O$ = a(), NE = f9();
  function OE($) {
    let X = {};
    for (let J of $) X[J] = true;
    return X;
  }
  Sw.toHash = OE;
  function wE($, X) {
    if (typeof X == "boolean") return X;
    if (Object.keys(X).length === 0) return true;
    return bw($, X), !Zw(X, $.self.RULES.all);
  }
  Sw.alwaysValidSchema = wE;
  function bw($, X = $.schema) {
    let { opts: J, self: Q } = $;
    if (!J.strictSchema) return;
    if (typeof X === "boolean") return;
    let Y = Q.RULES.keywords;
    for (let W in X) if (!Y[W]) Ew($, `unknown keyword: "${W}"`);
  }
  Sw.checkUnknownRules = bw;
  function Zw($, X) {
    if (typeof $ == "boolean") return !$;
    for (let J in $) if (X[J]) return true;
    return false;
  }
  Sw.schemaHasRules = Zw;
  function BE($, X) {
    if (typeof $ == "boolean") return !$;
    for (let J in $) if (J !== "$ref" && X.all[J]) return true;
    return false;
  }
  Sw.schemaHasRulesButRef = BE;
  function qE({ topSchemaRef: $, schemaPath: X }, J, Q, Y) {
    if (!Y) {
      if (typeof J == "number" || typeof J == "boolean") return J;
      if (typeof J == "string") return O$._`${J}`;
    }
    return O$._`${$}${X}${(0, O$.getProperty)(Q)}`;
  }
  Sw.schemaRefOrVal = qE;
  function LE($) {
    return Pw(decodeURIComponent($));
  }
  Sw.unescapeFragment = LE;
  function DE($) {
    return encodeURIComponent(YU($));
  }
  Sw.escapeFragment = DE;
  function YU($) {
    if (typeof $ == "number") return `${$}`;
    return $.replace(/~/g, "~0").replace(/\//g, "~1");
  }
  Sw.escapeJsonPointer = YU;
  function Pw($) {
    return $.replace(/~1/g, "/").replace(/~0/g, "~");
  }
  Sw.unescapeJsonPointer = Pw;
  function jE($, X) {
    if (Array.isArray($)) for (let J of $) X(J);
    else X($);
  }
  Sw.eachItem = jE;
  function Aw({ mergeNames: $, mergeToName: X, mergeValues: J, resultToName: Q }) {
    return (Y, W, z8, G) => {
      let U = z8 === void 0 ? W : z8 instanceof O$.Name ? (W instanceof O$.Name ? $(Y, W, z8) : X(Y, W, z8), z8) : W instanceof O$.Name ? (X(Y, z8, W), W) : J(W, z8);
      return G === O$.Name && !(U instanceof O$.Name) ? Q(Y, U) : U;
    };
  }
  Sw.mergeEvaluated = { props: Aw({ mergeNames: ($, X, J) => $.if(O$._`${J} !== true && ${X} !== undefined`, () => {
    $.if(O$._`${X} === true`, () => $.assign(J, true), () => $.assign(J, O$._`${J} || {}`).code(O$._`Object.assign(${J}, ${X})`));
  }), mergeToName: ($, X, J) => $.if(O$._`${J} !== true`, () => {
    if (X === true) $.assign(J, true);
    else $.assign(J, O$._`${J} || {}`), QU($, J, X);
  }), mergeValues: ($, X) => $ === true ? true : { ...$, ...X }, resultToName: Rw }), items: Aw({ mergeNames: ($, X, J) => $.if(O$._`${J} !== true && ${X} !== undefined`, () => $.assign(J, O$._`${X} === true ? true : ${J} > ${X} ? ${J} : ${X}`)), mergeToName: ($, X, J) => $.if(O$._`${J} !== true`, () => $.assign(J, X === true ? true : O$._`${J} > ${X} ? ${J} : ${X}`)), mergeValues: ($, X) => $ === true ? true : Math.max($, X), resultToName: ($, X) => $.var("items", X) }) };
  function Rw($, X) {
    if (X === true) return $.var("props", true);
    let J = $.var("props", O$._`{}`);
    if (X !== void 0) QU($, J, X);
    return J;
  }
  Sw.evaluatedPropsToName = Rw;
  function QU($, X, J) {
    Object.keys(J).forEach((Q) => $.assign(O$._`${X}${(0, O$.getProperty)(Q)}`, true));
  }
  Sw.setEvaluated = QU;
  var Iw = {};
  function FE($, X) {
    return $.scopeValue("func", { ref: X, code: Iw[X.code] || (Iw[X.code] = new NE._Code(X.code)) });
  }
  Sw.useFunc = FE;
  var JU;
  (function($) {
    $[$.Num = 0] = "Num", $[$.Str = 1] = "Str";
  })(JU || (Sw.Type = JU = {}));
  function ME($, X, J) {
    if ($ instanceof O$.Name) {
      let Q = X === JU.Num;
      return J ? Q ? O$._`"[" + ${$} + "]"` : O$._`"['" + ${$} + "']"` : Q ? O$._`"/" + ${$}` : O$._`"/" + ${$}.replace(/~/g, "~0").replace(/\\//g, "~1")`;
    }
    return J ? (0, O$.getProperty)($).toString() : "/" + YU($);
  }
  Sw.getErrorPath = ME;
  function Ew($, X, J = $.opts.strictSchema) {
    if (!J) return;
    if (X = `strict mode: ${X}`, J === true) throw Error(X);
    $.self.logger.warn(X);
  }
  Sw.checkStrictMode = Ew;
});
var b4 = k((Cw) => {
  Object.defineProperty(Cw, "__esModule", { value: true });
  var i$ = a(), hE = { data: new i$.Name("data"), valCxt: new i$.Name("valCxt"), instancePath: new i$.Name("instancePath"), parentData: new i$.Name("parentData"), parentDataProperty: new i$.Name("parentDataProperty"), rootData: new i$.Name("rootData"), dynamicAnchors: new i$.Name("dynamicAnchors"), vErrors: new i$.Name("vErrors"), errors: new i$.Name("errors"), this: new i$.Name("this"), self: new i$.Name("self"), scope: new i$.Name("scope"), json: new i$.Name("json"), jsonPos: new i$.Name("jsonPos"), jsonLen: new i$.Name("jsonLen"), jsonPart: new i$.Name("jsonPart") };
  Cw.default = hE;
});
var h9 = k((Tw) => {
  Object.defineProperty(Tw, "__esModule", { value: true });
  Tw.extendErrors = Tw.resetErrorsCount = Tw.reportExtraError = Tw.reportError = Tw.keyword$DataError = Tw.keywordError = void 0;
  var W$ = a(), dQ = Q$(), e$ = b4();
  Tw.keywordError = { message: ({ keyword: $ }) => W$.str`must pass "${$}" keyword validation` };
  Tw.keyword$DataError = { message: ({ keyword: $, schemaType: X }) => X ? W$.str`"${$}" keyword must be ${X} ($data)` : W$.str`"${$}" keyword is invalid ($data)` };
  function mE($, X = Tw.keywordError, J, Q) {
    let { it: Y } = $, { gen: W, compositeRule: z8, allErrors: G } = Y, U = xw($, X, J);
    if (Q !== null && Q !== void 0 ? Q : z8 || G) kw(W, U);
    else _w(Y, W$._`[${U}]`);
  }
  Tw.reportError = mE;
  function lE($, X = Tw.keywordError, J) {
    let { it: Q } = $, { gen: Y, compositeRule: W, allErrors: z8 } = Q, G = xw($, X, J);
    if (kw(Y, G), !(W || z8)) _w(Q, e$.default.vErrors);
  }
  Tw.reportExtraError = lE;
  function cE($, X) {
    $.assign(e$.default.errors, X), $.if(W$._`${e$.default.vErrors} !== null`, () => $.if(X, () => $.assign(W$._`${e$.default.vErrors}.length`, X), () => $.assign(e$.default.vErrors, null)));
  }
  Tw.resetErrorsCount = cE;
  function pE({ gen: $, keyword: X, schemaValue: J, data: Q, errsCount: Y, it: W }) {
    if (Y === void 0) throw Error("ajv implementation error");
    let z8 = $.name("err");
    $.forRange("i", Y, e$.default.errors, (G) => {
      if ($.const(z8, W$._`${e$.default.vErrors}[${G}]`), $.if(W$._`${z8}.instancePath === undefined`, () => $.assign(W$._`${z8}.instancePath`, (0, W$.strConcat)(e$.default.instancePath, W.errorPath))), $.assign(W$._`${z8}.schemaPath`, W$.str`${W.errSchemaPath}/${X}`), W.opts.verbose) $.assign(W$._`${z8}.schema`, J), $.assign(W$._`${z8}.data`, Q);
    });
  }
  Tw.extendErrors = pE;
  function kw($, X) {
    let J = $.const("err", X);
    $.if(W$._`${e$.default.vErrors} === null`, () => $.assign(e$.default.vErrors, W$._`[${J}]`), W$._`${e$.default.vErrors}.push(${J})`), $.code(W$._`${e$.default.errors}++`);
  }
  function _w($, X) {
    let { gen: J, validateName: Q, schemaEnv: Y } = $;
    if (Y.$async) J.throw(W$._`new ${$.ValidationError}(${X})`);
    else J.assign(W$._`${Q}.errors`, X), J.return(false);
  }
  var f1 = { keyword: new W$.Name("keyword"), schemaPath: new W$.Name("schemaPath"), params: new W$.Name("params"), propertyName: new W$.Name("propertyName"), message: new W$.Name("message"), schema: new W$.Name("schema"), parentSchema: new W$.Name("parentSchema") };
  function xw($, X, J) {
    let { createErrors: Q } = $.it;
    if (Q === false) return W$._`{}`;
    return dE($, X, J);
  }
  function dE($, X, J = {}) {
    let { gen: Q, it: Y } = $, W = [iE(Y, J), nE($, J)];
    return rE($, X, W), Q.object(...W);
  }
  function iE({ errorPath: $ }, { instancePath: X }) {
    let J = X ? W$.str`${$}${(0, dQ.getErrorPath)(X, dQ.Type.Str)}` : $;
    return [e$.default.instancePath, (0, W$.strConcat)(e$.default.instancePath, J)];
  }
  function nE({ keyword: $, it: { errSchemaPath: X } }, { schemaPath: J, parentSchema: Q }) {
    let Y = Q ? X : W$.str`${X}/${$}`;
    if (J) Y = W$.str`${Y}${(0, dQ.getErrorPath)(J, dQ.Type.Str)}`;
    return [f1.schemaPath, Y];
  }
  function rE($, { params: X, message: J }, Q) {
    let { keyword: Y, data: W, schemaValue: z8, it: G } = $, { opts: U, propertyName: H, topSchemaRef: K, schemaPath: V } = G;
    if (Q.push([f1.keyword, Y], [f1.params, typeof X == "function" ? X($) : X || W$._`{}`]), U.messages) Q.push([f1.message, typeof J == "function" ? J($) : J]);
    if (U.verbose) Q.push([f1.schema, z8], [f1.parentSchema, W$._`${K}${V}`], [e$.default.data, W]);
    if (H) Q.push([f1.propertyName, H]);
  }
});
var uw = k((gw) => {
  Object.defineProperty(gw, "__esModule", { value: true });
  gw.boolOrEmptySchema = gw.topBoolOrEmptySchema = void 0;
  var eE = h9(), $S = a(), XS = b4(), JS = { message: "boolean schema is false" };
  function YS($) {
    let { gen: X, schema: J, validateName: Q } = $;
    if (J === false) fw($, false);
    else if (typeof J == "object" && J.$async === true) X.return(XS.default.data);
    else X.assign($S._`${Q}.errors`, null), X.return(true);
  }
  gw.topBoolOrEmptySchema = YS;
  function QS($, X) {
    let { gen: J, schema: Q } = $;
    if (Q === false) J.var(X, false), fw($);
    else J.var(X, true);
  }
  gw.boolOrEmptySchema = QS;
  function fw($, X) {
    let { gen: J, data: Q } = $, Y = { gen: J, keyword: "false schema", data: Q, schema: false, schemaCode: false, schemaValue: false, params: {}, it: $ };
    (0, eE.reportError)(Y, JS, void 0, X);
  }
});
var zU = k((mw) => {
  Object.defineProperty(mw, "__esModule", { value: true });
  mw.getRules = mw.isJSONType = void 0;
  var zS = ["string", "number", "integer", "boolean", "null", "object", "array"], GS = new Set(zS);
  function US($) {
    return typeof $ == "string" && GS.has($);
  }
  mw.isJSONType = US;
  function HS() {
    let $ = { number: { type: "number", rules: [] }, string: { type: "string", rules: [] }, array: { type: "array", rules: [] }, object: { type: "object", rules: [] } };
    return { types: { ...$, integer: true, boolean: true, null: true }, rules: [{ rules: [] }, $.number, $.string, $.array, $.object], post: { rules: [] }, all: {}, keywords: {} };
  }
  mw.getRules = HS;
});
var GU = k((dw) => {
  Object.defineProperty(dw, "__esModule", { value: true });
  dw.shouldUseRule = dw.shouldUseGroup = dw.schemaHasRulesForType = void 0;
  function VS({ schema: $, self: X }, J) {
    let Q = X.RULES.types[J];
    return Q && Q !== true && cw($, Q);
  }
  dw.schemaHasRulesForType = VS;
  function cw($, X) {
    return X.rules.some((J) => pw($, J));
  }
  dw.shouldUseGroup = cw;
  function pw($, X) {
    var J;
    return $[X.keyword] !== void 0 || ((J = X.definition.implements) === null || J === void 0 ? void 0 : J.some((Q) => $[Q] !== void 0));
  }
  dw.shouldUseRule = pw;
});
var u9 = k((tw) => {
  Object.defineProperty(tw, "__esModule", { value: true });
  tw.reportTypeError = tw.checkDataTypes = tw.checkDataType = tw.coerceAndCheckDataType = tw.getJSONTypes = tw.getSchemaTypes = tw.DataType = void 0;
  var wS = zU(), BS = GU(), qS = h9(), t2 = a(), nw = Q$(), a0;
  (function($) {
    $[$.Correct = 0] = "Correct", $[$.Wrong = 1] = "Wrong";
  })(a0 || (tw.DataType = a0 = {}));
  function LS($) {
    let X = rw($.type);
    if (X.includes("null")) {
      if ($.nullable === false) throw Error("type: null contradicts nullable: false");
    } else {
      if (!X.length && $.nullable !== void 0) throw Error('"nullable" cannot be used without "type"');
      if ($.nullable === true) X.push("null");
    }
    return X;
  }
  tw.getSchemaTypes = LS;
  function rw($) {
    let X = Array.isArray($) ? $ : $ ? [$] : [];
    if (X.every(wS.isJSONType)) return X;
    throw Error("type must be JSONType or JSONType[]: " + X.join(","));
  }
  tw.getJSONTypes = rw;
  function DS($, X) {
    let { gen: J, data: Q, opts: Y } = $, W = jS(X, Y.coerceTypes), z8 = X.length > 0 && !(W.length === 0 && X.length === 1 && (0, BS.schemaHasRulesForType)($, X[0]));
    if (z8) {
      let G = HU(X, Q, Y.strictNumbers, a0.Wrong);
      J.if(G, () => {
        if (W.length) FS($, X, W);
        else KU($);
      });
    }
    return z8;
  }
  tw.coerceAndCheckDataType = DS;
  var ow = /* @__PURE__ */ new Set(["string", "number", "integer", "boolean", "null"]);
  function jS($, X) {
    return X ? $.filter((J) => ow.has(J) || X === "array" && J === "array") : [];
  }
  function FS($, X, J) {
    let { gen: Q, data: Y, opts: W } = $, z8 = Q.let("dataType", t2._`typeof ${Y}`), G = Q.let("coerced", t2._`undefined`);
    if (W.coerceTypes === "array") Q.if(t2._`${z8} == 'object' && Array.isArray(${Y}) && ${Y}.length == 1`, () => Q.assign(Y, t2._`${Y}[0]`).assign(z8, t2._`typeof ${Y}`).if(HU(X, Y, W.strictNumbers), () => Q.assign(G, Y)));
    Q.if(t2._`${G} !== undefined`);
    for (let H of J) if (ow.has(H) || H === "array" && W.coerceTypes === "array") U(H);
    Q.else(), KU($), Q.endIf(), Q.if(t2._`${G} !== undefined`, () => {
      Q.assign(Y, G), MS($, G);
    });
    function U(H) {
      switch (H) {
        case "string":
          Q.elseIf(t2._`${z8} == "number" || ${z8} == "boolean"`).assign(G, t2._`"" + ${Y}`).elseIf(t2._`${Y} === null`).assign(G, t2._`""`);
          return;
        case "number":
          Q.elseIf(t2._`${z8} == "boolean" || ${Y} === null
              || (${z8} == "string" && ${Y} && ${Y} == +${Y})`).assign(G, t2._`+${Y}`);
          return;
        case "integer":
          Q.elseIf(t2._`${z8} === "boolean" || ${Y} === null
              || (${z8} === "string" && ${Y} && ${Y} == +${Y} && !(${Y} % 1))`).assign(G, t2._`+${Y}`);
          return;
        case "boolean":
          Q.elseIf(t2._`${Y} === "false" || ${Y} === 0 || ${Y} === null`).assign(G, false).elseIf(t2._`${Y} === "true" || ${Y} === 1`).assign(G, true);
          return;
        case "null":
          Q.elseIf(t2._`${Y} === "" || ${Y} === 0 || ${Y} === false`), Q.assign(G, null);
          return;
        case "array":
          Q.elseIf(t2._`${z8} === "string" || ${z8} === "number"
              || ${z8} === "boolean" || ${Y} === null`).assign(G, t2._`[${Y}]`);
      }
    }
  }
  function MS({ gen: $, parentData: X, parentDataProperty: J }, Q) {
    $.if(t2._`${X} !== undefined`, () => $.assign(t2._`${X}[${J}]`, Q));
  }
  function UU($, X, J, Q = a0.Correct) {
    let Y = Q === a0.Correct ? t2.operators.EQ : t2.operators.NEQ, W;
    switch ($) {
      case "null":
        return t2._`${X} ${Y} null`;
      case "array":
        W = t2._`Array.isArray(${X})`;
        break;
      case "object":
        W = t2._`${X} && typeof ${X} == "object" && !Array.isArray(${X})`;
        break;
      case "integer":
        W = z8(t2._`!(${X} % 1) && !isNaN(${X})`);
        break;
      case "number":
        W = z8();
        break;
      default:
        return t2._`typeof ${X} ${Y} ${$}`;
    }
    return Q === a0.Correct ? W : (0, t2.not)(W);
    function z8(G = t2.nil) {
      return (0, t2.and)(t2._`typeof ${X} == "number"`, G, J ? t2._`isFinite(${X})` : t2.nil);
    }
  }
  tw.checkDataType = UU;
  function HU($, X, J, Q) {
    if ($.length === 1) return UU($[0], X, J, Q);
    let Y, W = (0, nw.toHash)($);
    if (W.array && W.object) {
      let z8 = t2._`typeof ${X} != "object"`;
      Y = W.null ? z8 : t2._`!${X} || ${z8}`, delete W.null, delete W.array, delete W.object;
    } else Y = t2.nil;
    if (W.number) delete W.integer;
    for (let z8 in W) Y = (0, t2.and)(Y, UU(z8, X, J, Q));
    return Y;
  }
  tw.checkDataTypes = HU;
  var AS = { message: ({ schema: $ }) => `must be ${$}`, params: ({ schema: $, schemaValue: X }) => typeof $ == "string" ? t2._`{type: ${$}}` : t2._`{type: ${X}}` };
  function KU($) {
    let X = IS($);
    (0, qS.reportError)(X, AS);
  }
  tw.reportTypeError = KU;
  function IS($) {
    let { gen: X, data: J, schema: Q } = $, Y = (0, nw.schemaRefOrVal)($, Q, "type");
    return { gen: X, keyword: "type", data: J, schema: Q.type, schemaCode: Y, schemaValue: Y, parentSchema: Q, params: {}, it: $ };
  }
});
var XB = k((ew) => {
  Object.defineProperty(ew, "__esModule", { value: true });
  ew.assignDefaults = void 0;
  var s0 = a(), vS = Q$();
  function CS($, X) {
    let { properties: J, items: Q } = $.schema;
    if (X === "object" && J) for (let Y in J) sw($, Y, J[Y].default);
    else if (X === "array" && Array.isArray(Q)) Q.forEach((Y, W) => sw($, W, Y.default));
  }
  ew.assignDefaults = CS;
  function sw($, X, J) {
    let { gen: Q, compositeRule: Y, data: W, opts: z8 } = $;
    if (J === void 0) return;
    let G = s0._`${W}${(0, s0.getProperty)(X)}`;
    if (Y) {
      (0, vS.checkStrictMode)($, `default is ignored for: ${G}`);
      return;
    }
    let U = s0._`${G} === undefined`;
    if (z8.useDefaults === "empty") U = s0._`${U} || ${G} === null || ${G} === ""`;
    Q.if(U, s0._`${G} = ${(0, s0.stringify)(J)}`);
  }
});
var E6 = k((QB) => {
  Object.defineProperty(QB, "__esModule", { value: true });
  QB.validateUnion = QB.validateArray = QB.usePattern = QB.callValidateCode = QB.schemaProperties = QB.allSchemaProperties = QB.noPropertyInData = QB.propertyInData = QB.isOwnProperty = QB.hasPropFunc = QB.reportMissingProp = QB.checkMissingProp = QB.checkReportMissingProp = void 0;
  var F$ = a(), VU = Q$(), J1 = b4(), kS = Q$();
  function _S($, X) {
    let { gen: J, data: Q, it: Y } = $;
    J.if(OU(J, Q, X, Y.opts.ownProperties), () => {
      $.setParams({ missingProperty: F$._`${X}` }, true), $.error();
    });
  }
  QB.checkReportMissingProp = _S;
  function xS({ gen: $, data: X, it: { opts: J } }, Q, Y) {
    return (0, F$.or)(...Q.map((W) => (0, F$.and)(OU($, X, W, J.ownProperties), F$._`${Y} = ${W}`)));
  }
  QB.checkMissingProp = xS;
  function TS($, X) {
    $.setParams({ missingProperty: X }, true), $.error();
  }
  QB.reportMissingProp = TS;
  function JB($) {
    return $.scopeValue("func", { ref: Object.prototype.hasOwnProperty, code: F$._`Object.prototype.hasOwnProperty` });
  }
  QB.hasPropFunc = JB;
  function NU($, X, J) {
    return F$._`${JB($)}.call(${X}, ${J})`;
  }
  QB.isOwnProperty = NU;
  function yS($, X, J, Q) {
    let Y = F$._`${X}${(0, F$.getProperty)(J)} !== undefined`;
    return Q ? F$._`${Y} && ${NU($, X, J)}` : Y;
  }
  QB.propertyInData = yS;
  function OU($, X, J, Q) {
    let Y = F$._`${X}${(0, F$.getProperty)(J)} === undefined`;
    return Q ? (0, F$.or)(Y, (0, F$.not)(NU($, X, J))) : Y;
  }
  QB.noPropertyInData = OU;
  function YB($) {
    return $ ? Object.keys($).filter((X) => X !== "__proto__") : [];
  }
  QB.allSchemaProperties = YB;
  function fS($, X) {
    return YB(X).filter((J) => !(0, VU.alwaysValidSchema)($, X[J]));
  }
  QB.schemaProperties = fS;
  function gS({ schemaCode: $, data: X, it: { gen: J, topSchemaRef: Q, schemaPath: Y, errorPath: W }, it: z8 }, G, U, H) {
    let K = H ? F$._`${$}, ${X}, ${Q}${Y}` : X, V = [[J1.default.instancePath, (0, F$.strConcat)(J1.default.instancePath, W)], [J1.default.parentData, z8.parentData], [J1.default.parentDataProperty, z8.parentDataProperty], [J1.default.rootData, J1.default.rootData]];
    if (z8.opts.dynamicRef) V.push([J1.default.dynamicAnchors, J1.default.dynamicAnchors]);
    let N = F$._`${K}, ${J.object(...V)}`;
    return U !== F$.nil ? F$._`${G}.call(${U}, ${N})` : F$._`${G}(${N})`;
  }
  QB.callValidateCode = gS;
  var hS = F$._`new RegExp`;
  function uS({ gen: $, it: { opts: X } }, J) {
    let Q = X.unicodeRegExp ? "u" : "", { regExp: Y } = X.code, W = Y(J, Q);
    return $.scopeValue("pattern", { key: W.toString(), ref: W, code: F$._`${Y.code === "new RegExp" ? hS : (0, kS.useFunc)($, Y)}(${J}, ${Q})` });
  }
  QB.usePattern = uS;
  function mS($) {
    let { gen: X, data: J, keyword: Q, it: Y } = $, W = X.name("valid");
    if (Y.allErrors) {
      let G = X.let("valid", true);
      return z8(() => X.assign(G, false)), G;
    }
    return X.var(W, true), z8(() => X.break()), W;
    function z8(G) {
      let U = X.const("len", F$._`${J}.length`);
      X.forRange("i", 0, U, (H) => {
        $.subschema({ keyword: Q, dataProp: H, dataPropType: VU.Type.Num }, W), X.if((0, F$.not)(W), G);
      });
    }
  }
  QB.validateArray = mS;
  function lS($) {
    let { gen: X, schema: J, keyword: Q, it: Y } = $;
    if (!Array.isArray(J)) throw Error("ajv implementation error");
    if (J.some((U) => (0, VU.alwaysValidSchema)(Y, U)) && !Y.opts.unevaluated) return;
    let z8 = X.let("valid", false), G = X.name("_valid");
    X.block(() => J.forEach((U, H) => {
      let K = $.subschema({ keyword: Q, schemaProp: H, compositeRule: true }, G);
      if (X.assign(z8, F$._`${z8} || ${G}`), !$.mergeValidEvaluated(K, G)) X.if((0, F$.not)(z8));
    })), $.result(z8, () => $.reset(), () => $.error(true));
  }
  QB.validateUnion = lS;
});
var KB = k((UB) => {
  Object.defineProperty(UB, "__esModule", { value: true });
  UB.validateKeywordUsage = UB.validSchemaType = UB.funcKeywordCode = UB.macroKeywordCode = void 0;
  var $6 = a(), g1 = b4(), Xv = E6(), Jv = h9();
  function Yv($, X) {
    let { gen: J, keyword: Q, schema: Y, parentSchema: W, it: z8 } = $, G = X.macro.call(z8.self, Y, W, z8), U = GB(J, Q, G);
    if (z8.opts.validateSchema !== false) z8.self.validateSchema(G, true);
    let H = J.name("valid");
    $.subschema({ schema: G, schemaPath: $6.nil, errSchemaPath: `${z8.errSchemaPath}/${Q}`, topSchemaRef: U, compositeRule: true }, H), $.pass(H, () => $.error(true));
  }
  UB.macroKeywordCode = Yv;
  function Qv($, X) {
    var J;
    let { gen: Q, keyword: Y, schema: W, parentSchema: z8, $data: G, it: U } = $;
    zv(U, X);
    let H = !G && X.compile ? X.compile.call(U.self, W, z8, U) : X.validate, K = GB(Q, Y, H), V = Q.let("valid");
    $.block$data(V, N), $.ok((J = X.valid) !== null && J !== void 0 ? J : V);
    function N() {
      if (X.errors === false) {
        if (B(), X.modifying) zB($);
        D(() => $.error());
      } else {
        let j = X.async ? O() : w();
        if (X.modifying) zB($);
        D(() => Wv($, j));
      }
    }
    function O() {
      let j = Q.let("ruleErrs", null);
      return Q.try(() => B($6._`await `), (A) => Q.assign(V, false).if($6._`${A} instanceof ${U.ValidationError}`, () => Q.assign(j, $6._`${A}.errors`), () => Q.throw(A))), j;
    }
    function w() {
      let j = $6._`${K}.errors`;
      return Q.assign(j, null), B($6.nil), j;
    }
    function B(j = X.async ? $6._`await ` : $6.nil) {
      let A = U.opts.passContext ? g1.default.this : g1.default.self, I = !("compile" in X && !G || X.schema === false);
      Q.assign(V, $6._`${j}${(0, Xv.callValidateCode)($, K, A, I)}`, X.modifying);
    }
    function D(j) {
      var A;
      Q.if((0, $6.not)((A = X.valid) !== null && A !== void 0 ? A : V), j);
    }
  }
  UB.funcKeywordCode = Qv;
  function zB($) {
    let { gen: X, data: J, it: Q } = $;
    X.if(Q.parentData, () => X.assign(J, $6._`${Q.parentData}[${Q.parentDataProperty}]`));
  }
  function Wv($, X) {
    let { gen: J } = $;
    J.if($6._`Array.isArray(${X})`, () => {
      J.assign(g1.default.vErrors, $6._`${g1.default.vErrors} === null ? ${X} : ${g1.default.vErrors}.concat(${X})`).assign(g1.default.errors, $6._`${g1.default.vErrors}.length`), (0, Jv.extendErrors)($);
    }, () => $.error());
  }
  function zv({ schemaEnv: $ }, X) {
    if (X.async && !$.$async) throw Error("async keyword in sync schema");
  }
  function GB($, X, J) {
    if (J === void 0) throw Error(`keyword "${X}" failed to compile`);
    return $.scopeValue("keyword", typeof J == "function" ? { ref: J } : { ref: J, code: (0, $6.stringify)(J) });
  }
  function Gv($, X, J = false) {
    return !X.length || X.some((Q) => Q === "array" ? Array.isArray($) : Q === "object" ? $ && typeof $ == "object" && !Array.isArray($) : typeof $ == Q || J && typeof $ > "u");
  }
  UB.validSchemaType = Gv;
  function Uv({ schema: $, opts: X, self: J, errSchemaPath: Q }, Y, W) {
    if (Array.isArray(Y.keyword) ? !Y.keyword.includes(W) : Y.keyword !== W) throw Error("ajv implementation error");
    let z8 = Y.dependencies;
    if (z8 === null || z8 === void 0 ? void 0 : z8.some((G) => !Object.prototype.hasOwnProperty.call($, G))) throw Error(`parent schema must have dependencies of ${W}: ${z8.join(",")}`);
    if (Y.validateSchema) {
      if (!Y.validateSchema($[W])) {
        let U = `keyword "${W}" value is invalid at path "${Q}": ` + J.errorsText(Y.validateSchema.errors);
        if (X.validateSchema === "log") J.logger.error(U);
        else throw Error(U);
      }
    }
  }
  UB.validateKeywordUsage = Uv;
});
var wB = k((NB) => {
  Object.defineProperty(NB, "__esModule", { value: true });
  NB.extendSubschemaMode = NB.extendSubschemaData = NB.getSubschema = void 0;
  var a6 = a(), VB = Q$();
  function Nv($, { keyword: X, schemaProp: J, schema: Q, schemaPath: Y, errSchemaPath: W, topSchemaRef: z8 }) {
    if (X !== void 0 && Q !== void 0) throw Error('both "keyword" and "schema" passed, only one allowed');
    if (X !== void 0) {
      let G = $.schema[X];
      return J === void 0 ? { schema: G, schemaPath: a6._`${$.schemaPath}${(0, a6.getProperty)(X)}`, errSchemaPath: `${$.errSchemaPath}/${X}` } : { schema: G[J], schemaPath: a6._`${$.schemaPath}${(0, a6.getProperty)(X)}${(0, a6.getProperty)(J)}`, errSchemaPath: `${$.errSchemaPath}/${X}/${(0, VB.escapeFragment)(J)}` };
    }
    if (Q !== void 0) {
      if (Y === void 0 || W === void 0 || z8 === void 0) throw Error('"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"');
      return { schema: Q, schemaPath: Y, topSchemaRef: z8, errSchemaPath: W };
    }
    throw Error('either "keyword" or "schema" must be passed');
  }
  NB.getSubschema = Nv;
  function Ov($, X, { dataProp: J, dataPropType: Q, data: Y, dataTypes: W, propertyName: z8 }) {
    if (Y !== void 0 && J !== void 0) throw Error('both "data" and "dataProp" passed, only one allowed');
    let { gen: G } = X;
    if (J !== void 0) {
      let { errorPath: H, dataPathArr: K, opts: V } = X, N = G.let("data", a6._`${X.data}${(0, a6.getProperty)(J)}`, true);
      U(N), $.errorPath = a6.str`${H}${(0, VB.getErrorPath)(J, Q, V.jsPropertySyntax)}`, $.parentDataProperty = a6._`${J}`, $.dataPathArr = [...K, $.parentDataProperty];
    }
    if (Y !== void 0) {
      let H = Y instanceof a6.Name ? Y : G.let("data", Y, true);
      if (U(H), z8 !== void 0) $.propertyName = z8;
    }
    if (W) $.dataTypes = W;
    function U(H) {
      $.data = H, $.dataLevel = X.dataLevel + 1, $.dataTypes = [], X.definedProperties = /* @__PURE__ */ new Set(), $.parentData = X.data, $.dataNames = [...X.dataNames, H];
    }
  }
  NB.extendSubschemaData = Ov;
  function wv($, { jtdDiscriminator: X, jtdMetadata: J, compositeRule: Q, createErrors: Y, allErrors: W }) {
    if (Q !== void 0) $.compositeRule = Q;
    if (Y !== void 0) $.createErrors = Y;
    if (W !== void 0) $.allErrors = W;
    $.jtdDiscriminator = X, $.jtdMetadata = J;
  }
  NB.extendSubschemaMode = wv;
});
var wU = k(($s, BB) => {
  BB.exports = function $(X, J) {
    if (X === J) return true;
    if (X && J && typeof X == "object" && typeof J == "object") {
      if (X.constructor !== J.constructor) return false;
      var Q, Y, W;
      if (Array.isArray(X)) {
        if (Q = X.length, Q != J.length) return false;
        for (Y = Q; Y-- !== 0; ) if (!$(X[Y], J[Y])) return false;
        return true;
      }
      if (X.constructor === RegExp) return X.source === J.source && X.flags === J.flags;
      if (X.valueOf !== Object.prototype.valueOf) return X.valueOf() === J.valueOf();
      if (X.toString !== Object.prototype.toString) return X.toString() === J.toString();
      if (W = Object.keys(X), Q = W.length, Q !== Object.keys(J).length) return false;
      for (Y = Q; Y-- !== 0; ) if (!Object.prototype.hasOwnProperty.call(J, W[Y])) return false;
      for (Y = Q; Y-- !== 0; ) {
        var z8 = W[Y];
        if (!$(X[z8], J[z8])) return false;
      }
      return true;
    }
    return X !== X && J !== J;
  };
});
var LB = k((Xs, qB) => {
  var Y1 = qB.exports = function($, X, J) {
    if (typeof X == "function") J = X, X = {};
    J = X.cb || J;
    var Q = typeof J == "function" ? J : J.pre || function() {
    }, Y = J.post || function() {
    };
    iQ(X, Q, Y, $, "", $);
  };
  Y1.keywords = { additionalItems: true, items: true, contains: true, additionalProperties: true, propertyNames: true, not: true, if: true, then: true, else: true };
  Y1.arrayKeywords = { items: true, allOf: true, anyOf: true, oneOf: true };
  Y1.propsKeywords = { $defs: true, definitions: true, properties: true, patternProperties: true, dependencies: true };
  Y1.skipKeywords = { default: true, enum: true, const: true, required: true, maximum: true, minimum: true, exclusiveMaximum: true, exclusiveMinimum: true, multipleOf: true, maxLength: true, minLength: true, pattern: true, format: true, maxItems: true, minItems: true, uniqueItems: true, maxProperties: true, minProperties: true };
  function iQ($, X, J, Q, Y, W, z8, G, U, H) {
    if (Q && typeof Q == "object" && !Array.isArray(Q)) {
      X(Q, Y, W, z8, G, U, H);
      for (var K in Q) {
        var V = Q[K];
        if (Array.isArray(V)) {
          if (K in Y1.arrayKeywords) for (var N = 0; N < V.length; N++) iQ($, X, J, V[N], Y + "/" + K + "/" + N, W, Y, K, Q, N);
        } else if (K in Y1.propsKeywords) {
          if (V && typeof V == "object") for (var O in V) iQ($, X, J, V[O], Y + "/" + K + "/" + Lv(O), W, Y, K, Q, O);
        } else if (K in Y1.keywords || $.allKeys && !(K in Y1.skipKeywords)) iQ($, X, J, V, Y + "/" + K, W, Y, K, Q);
      }
      J(Q, Y, W, z8, G, U, H);
    }
  }
  function Lv($) {
    return $.replace(/~/g, "~0").replace(/\//g, "~1");
  }
});
var m9 = k((MB) => {
  Object.defineProperty(MB, "__esModule", { value: true });
  MB.getSchemaRefs = MB.resolveUrl = MB.normalizeId = MB._getFullPath = MB.getFullPath = MB.inlineRef = void 0;
  var Dv = Q$(), jv = wU(), Fv = LB(), Mv = /* @__PURE__ */ new Set(["type", "format", "pattern", "maxLength", "minLength", "maxProperties", "minProperties", "maxItems", "minItems", "maximum", "minimum", "uniqueItems", "multipleOf", "required", "enum", "const"]);
  function Av($, X = true) {
    if (typeof $ == "boolean") return true;
    if (X === true) return !BU($);
    if (!X) return false;
    return DB($) <= X;
  }
  MB.inlineRef = Av;
  var Iv = /* @__PURE__ */ new Set(["$ref", "$recursiveRef", "$recursiveAnchor", "$dynamicRef", "$dynamicAnchor"]);
  function BU($) {
    for (let X in $) {
      if (Iv.has(X)) return true;
      let J = $[X];
      if (Array.isArray(J) && J.some(BU)) return true;
      if (typeof J == "object" && BU(J)) return true;
    }
    return false;
  }
  function DB($) {
    let X = 0;
    for (let J in $) {
      if (J === "$ref") return 1 / 0;
      if (X++, Mv.has(J)) continue;
      if (typeof $[J] == "object") (0, Dv.eachItem)($[J], (Q) => X += DB(Q));
      if (X === 1 / 0) return 1 / 0;
    }
    return X;
  }
  function jB($, X = "", J) {
    if (J !== false) X = e0(X);
    let Q = $.parse(X);
    return FB($, Q);
  }
  MB.getFullPath = jB;
  function FB($, X) {
    return $.serialize(X).split("#")[0] + "#";
  }
  MB._getFullPath = FB;
  var bv = /#\/?$/;
  function e0($) {
    return $ ? $.replace(bv, "") : "";
  }
  MB.normalizeId = e0;
  function Zv($, X, J) {
    return J = e0(J), $.resolve(X, J);
  }
  MB.resolveUrl = Zv;
  var Pv = /^[a-z_][-a-z0-9._]*$/i;
  function Rv($, X) {
    if (typeof $ == "boolean") return {};
    let { schemaId: J, uriResolver: Q } = this.opts, Y = e0($[J] || X), W = { "": Y }, z8 = jB(Q, Y, false), G = {}, U = /* @__PURE__ */ new Set();
    return Fv($, { allKeys: true }, (V, N, O, w) => {
      if (w === void 0) return;
      let B = z8 + N, D = W[w];
      if (typeof V[J] == "string") D = j.call(this, V[J]);
      A.call(this, V.$anchor), A.call(this, V.$dynamicAnchor), W[N] = D;
      function j(I) {
        let x = this.opts.uriResolver.resolve;
        if (I = e0(D ? x(D, I) : I), U.has(I)) throw K(I);
        U.add(I);
        let T = this.refs[I];
        if (typeof T == "string") T = this.refs[T];
        if (typeof T == "object") H(V, T.schema, I);
        else if (I !== e0(B)) if (I[0] === "#") H(V, G[I], I), G[I] = V;
        else this.refs[I] = B;
        return I;
      }
      function A(I) {
        if (typeof I == "string") {
          if (!Pv.test(I)) throw Error(`invalid anchor "${I}"`);
          j.call(this, `#${I}`);
        }
      }
    }), G;
    function H(V, N, O) {
      if (N !== void 0 && !jv(V, N)) throw K(O);
    }
    function K(V) {
      return Error(`reference "${V}" resolves to more than one schema`);
    }
  }
  MB.getSchemaRefs = Rv;
});
var p9 = k((fB) => {
  Object.defineProperty(fB, "__esModule", { value: true });
  fB.getData = fB.KeywordCxt = fB.validateFunctionCode = void 0;
  var RB = uw(), IB = u9(), LU = GU(), nQ = u9(), _v = XB(), c9 = KB(), qU = wB(), u = a(), n = b4(), xv = m9(), Z4 = Q$(), l9 = h9();
  function Tv($) {
    if (vB($)) {
      if (CB($), SB($)) {
        gv($);
        return;
      }
    }
    EB($, () => (0, RB.topBoolOrEmptySchema)($));
  }
  fB.validateFunctionCode = Tv;
  function EB({ gen: $, validateName: X, schema: J, schemaEnv: Q, opts: Y }, W) {
    if (Y.code.es5) $.func(X, u._`${n.default.data}, ${n.default.valCxt}`, Q.$async, () => {
      $.code(u._`"use strict"; ${bB(J, Y)}`), fv($, Y), $.code(W);
    });
    else $.func(X, u._`${n.default.data}, ${yv(Y)}`, Q.$async, () => $.code(bB(J, Y)).code(W));
  }
  function yv($) {
    return u._`{${n.default.instancePath}="", ${n.default.parentData}, ${n.default.parentDataProperty}, ${n.default.rootData}=${n.default.data}${$.dynamicRef ? u._`, ${n.default.dynamicAnchors}={}` : u.nil}}={}`;
  }
  function fv($, X) {
    $.if(n.default.valCxt, () => {
      if ($.var(n.default.instancePath, u._`${n.default.valCxt}.${n.default.instancePath}`), $.var(n.default.parentData, u._`${n.default.valCxt}.${n.default.parentData}`), $.var(n.default.parentDataProperty, u._`${n.default.valCxt}.${n.default.parentDataProperty}`), $.var(n.default.rootData, u._`${n.default.valCxt}.${n.default.rootData}`), X.dynamicRef) $.var(n.default.dynamicAnchors, u._`${n.default.valCxt}.${n.default.dynamicAnchors}`);
    }, () => {
      if ($.var(n.default.instancePath, u._`""`), $.var(n.default.parentData, u._`undefined`), $.var(n.default.parentDataProperty, u._`undefined`), $.var(n.default.rootData, n.default.data), X.dynamicRef) $.var(n.default.dynamicAnchors, u._`{}`);
    });
  }
  function gv($) {
    let { schema: X, opts: J, gen: Q } = $;
    EB($, () => {
      if (J.$comment && X.$comment) _B($);
      if (cv($), Q.let(n.default.vErrors, null), Q.let(n.default.errors, 0), J.unevaluated) hv($);
      kB($), iv($);
    });
    return;
  }
  function hv($) {
    let { gen: X, validateName: J } = $;
    $.evaluated = X.const("evaluated", u._`${J}.evaluated`), X.if(u._`${$.evaluated}.dynamicProps`, () => X.assign(u._`${$.evaluated}.props`, u._`undefined`)), X.if(u._`${$.evaluated}.dynamicItems`, () => X.assign(u._`${$.evaluated}.items`, u._`undefined`));
  }
  function bB($, X) {
    let J = typeof $ == "object" && $[X.schemaId];
    return J && (X.code.source || X.code.process) ? u._`/*# sourceURL=${J} */` : u.nil;
  }
  function uv($, X) {
    if (vB($)) {
      if (CB($), SB($)) {
        mv($, X);
        return;
      }
    }
    (0, RB.boolOrEmptySchema)($, X);
  }
  function SB({ schema: $, self: X }) {
    if (typeof $ == "boolean") return !$;
    for (let J in $) if (X.RULES.all[J]) return true;
    return false;
  }
  function vB($) {
    return typeof $.schema != "boolean";
  }
  function mv($, X) {
    let { schema: J, gen: Q, opts: Y } = $;
    if (Y.$comment && J.$comment) _B($);
    pv($), dv($);
    let W = Q.const("_errs", n.default.errors);
    kB($, W), Q.var(X, u._`${W} === ${n.default.errors}`);
  }
  function CB($) {
    (0, Z4.checkUnknownRules)($), lv($);
  }
  function kB($, X) {
    if ($.opts.jtd) return ZB($, [], false, X);
    let J = (0, IB.getSchemaTypes)($.schema), Q = (0, IB.coerceAndCheckDataType)($, J);
    ZB($, J, !Q, X);
  }
  function lv($) {
    let { schema: X, errSchemaPath: J, opts: Q, self: Y } = $;
    if (X.$ref && Q.ignoreKeywordsWithRef && (0, Z4.schemaHasRulesButRef)(X, Y.RULES)) Y.logger.warn(`$ref: keywords ignored in schema at path "${J}"`);
  }
  function cv($) {
    let { schema: X, opts: J } = $;
    if (X.default !== void 0 && J.useDefaults && J.strictSchema) (0, Z4.checkStrictMode)($, "default is ignored in the schema root");
  }
  function pv($) {
    let X = $.schema[$.opts.schemaId];
    if (X) $.baseId = (0, xv.resolveUrl)($.opts.uriResolver, $.baseId, X);
  }
  function dv($) {
    if ($.schema.$async && !$.schemaEnv.$async) throw Error("async schema in sync schema");
  }
  function _B({ gen: $, schemaEnv: X, schema: J, errSchemaPath: Q, opts: Y }) {
    let W = J.$comment;
    if (Y.$comment === true) $.code(u._`${n.default.self}.logger.log(${W})`);
    else if (typeof Y.$comment == "function") {
      let z8 = u.str`${Q}/$comment`, G = $.scopeValue("root", { ref: X.root });
      $.code(u._`${n.default.self}.opts.$comment(${W}, ${z8}, ${G}.schema)`);
    }
  }
  function iv($) {
    let { gen: X, schemaEnv: J, validateName: Q, ValidationError: Y, opts: W } = $;
    if (J.$async) X.if(u._`${n.default.errors} === 0`, () => X.return(n.default.data), () => X.throw(u._`new ${Y}(${n.default.vErrors})`));
    else {
      if (X.assign(u._`${Q}.errors`, n.default.vErrors), W.unevaluated) nv($);
      X.return(u._`${n.default.errors} === 0`);
    }
  }
  function nv({ gen: $, evaluated: X, props: J, items: Q }) {
    if (J instanceof u.Name) $.assign(u._`${X}.props`, J);
    if (Q instanceof u.Name) $.assign(u._`${X}.items`, Q);
  }
  function ZB($, X, J, Q) {
    let { gen: Y, schema: W, data: z8, allErrors: G, opts: U, self: H } = $, { RULES: K } = H;
    if (W.$ref && (U.ignoreKeywordsWithRef || !(0, Z4.schemaHasRulesButRef)(W, K))) {
      Y.block(() => TB($, "$ref", K.all.$ref.definition));
      return;
    }
    if (!U.jtd) rv($, X);
    Y.block(() => {
      for (let N of K.rules) V(N);
      V(K.post);
    });
    function V(N) {
      if (!(0, LU.shouldUseGroup)(W, N)) return;
      if (N.type) {
        if (Y.if((0, nQ.checkDataType)(N.type, z8, U.strictNumbers)), PB($, N), X.length === 1 && X[0] === N.type && J) Y.else(), (0, nQ.reportTypeError)($);
        Y.endIf();
      } else PB($, N);
      if (!G) Y.if(u._`${n.default.errors} === ${Q || 0}`);
    }
  }
  function PB($, X) {
    let { gen: J, schema: Q, opts: { useDefaults: Y } } = $;
    if (Y) (0, _v.assignDefaults)($, X.type);
    J.block(() => {
      for (let W of X.rules) if ((0, LU.shouldUseRule)(Q, W)) TB($, W.keyword, W.definition, X.type);
    });
  }
  function rv($, X) {
    if ($.schemaEnv.meta || !$.opts.strictTypes) return;
    if (ov($, X), !$.opts.allowUnionTypes) tv($, X);
    av($, $.dataTypes);
  }
  function ov($, X) {
    if (!X.length) return;
    if (!$.dataTypes.length) {
      $.dataTypes = X;
      return;
    }
    X.forEach((J) => {
      if (!xB($.dataTypes, J)) DU($, `type "${J}" not allowed by context "${$.dataTypes.join(",")}"`);
    }), ev($, X);
  }
  function tv($, X) {
    if (X.length > 1 && !(X.length === 2 && X.includes("null"))) DU($, "use allowUnionTypes to allow union type keyword");
  }
  function av($, X) {
    let J = $.self.RULES.all;
    for (let Q in J) {
      let Y = J[Q];
      if (typeof Y == "object" && (0, LU.shouldUseRule)($.schema, Y)) {
        let { type: W } = Y.definition;
        if (W.length && !W.some((z8) => sv(X, z8))) DU($, `missing type "${W.join(",")}" for keyword "${Q}"`);
      }
    }
  }
  function sv($, X) {
    return $.includes(X) || X === "number" && $.includes("integer");
  }
  function xB($, X) {
    return $.includes(X) || X === "integer" && $.includes("number");
  }
  function ev($, X) {
    let J = [];
    for (let Q of $.dataTypes) if (xB(X, Q)) J.push(Q);
    else if (X.includes("integer") && Q === "number") J.push("integer");
    $.dataTypes = J;
  }
  function DU($, X) {
    let J = $.schemaEnv.baseId + $.errSchemaPath;
    X += ` at "${J}" (strictTypes)`, (0, Z4.checkStrictMode)($, X, $.opts.strictTypes);
  }
  class jU {
    constructor($, X, J) {
      if ((0, c9.validateKeywordUsage)($, X, J), this.gen = $.gen, this.allErrors = $.allErrors, this.keyword = J, this.data = $.data, this.schema = $.schema[J], this.$data = X.$data && $.opts.$data && this.schema && this.schema.$data, this.schemaValue = (0, Z4.schemaRefOrVal)($, this.schema, J, this.$data), this.schemaType = X.schemaType, this.parentSchema = $.schema, this.params = {}, this.it = $, this.def = X, this.$data) this.schemaCode = $.gen.const("vSchema", yB(this.$data, $));
      else if (this.schemaCode = this.schemaValue, !(0, c9.validSchemaType)(this.schema, X.schemaType, X.allowUndefined)) throw Error(`${J} value must be ${JSON.stringify(X.schemaType)}`);
      if ("code" in X ? X.trackErrors : X.errors !== false) this.errsCount = $.gen.const("_errs", n.default.errors);
    }
    result($, X, J) {
      this.failResult((0, u.not)($), X, J);
    }
    failResult($, X, J) {
      if (this.gen.if($), J) J();
      else this.error();
      if (X) {
        if (this.gen.else(), X(), this.allErrors) this.gen.endIf();
      } else if (this.allErrors) this.gen.endIf();
      else this.gen.else();
    }
    pass($, X) {
      this.failResult((0, u.not)($), void 0, X);
    }
    fail($) {
      if ($ === void 0) {
        if (this.error(), !this.allErrors) this.gen.if(false);
        return;
      }
      if (this.gen.if($), this.error(), this.allErrors) this.gen.endIf();
      else this.gen.else();
    }
    fail$data($) {
      if (!this.$data) return this.fail($);
      let { schemaCode: X } = this;
      this.fail(u._`${X} !== undefined && (${(0, u.or)(this.invalid$data(), $)})`);
    }
    error($, X, J) {
      if (X) {
        this.setParams(X), this._error($, J), this.setParams({});
        return;
      }
      this._error($, J);
    }
    _error($, X) {
      ($ ? l9.reportExtraError : l9.reportError)(this, this.def.error, X);
    }
    $dataError() {
      (0, l9.reportError)(this, this.def.$dataError || l9.keyword$DataError);
    }
    reset() {
      if (this.errsCount === void 0) throw Error('add "trackErrors" to keyword definition');
      (0, l9.resetErrorsCount)(this.gen, this.errsCount);
    }
    ok($) {
      if (!this.allErrors) this.gen.if($);
    }
    setParams($, X) {
      if (X) Object.assign(this.params, $);
      else this.params = $;
    }
    block$data($, X, J = u.nil) {
      this.gen.block(() => {
        this.check$data($, J), X();
      });
    }
    check$data($ = u.nil, X = u.nil) {
      if (!this.$data) return;
      let { gen: J, schemaCode: Q, schemaType: Y, def: W } = this;
      if (J.if((0, u.or)(u._`${Q} === undefined`, X)), $ !== u.nil) J.assign($, true);
      if (Y.length || W.validateSchema) {
        if (J.elseIf(this.invalid$data()), this.$dataError(), $ !== u.nil) J.assign($, false);
      }
      J.else();
    }
    invalid$data() {
      let { gen: $, schemaCode: X, schemaType: J, def: Q, it: Y } = this;
      return (0, u.or)(W(), z8());
      function W() {
        if (J.length) {
          if (!(X instanceof u.Name)) throw Error("ajv implementation error");
          let G = Array.isArray(J) ? J : [J];
          return u._`${(0, nQ.checkDataTypes)(G, X, Y.opts.strictNumbers, nQ.DataType.Wrong)}`;
        }
        return u.nil;
      }
      function z8() {
        if (Q.validateSchema) {
          let G = $.scopeValue("validate$data", { ref: Q.validateSchema });
          return u._`!${G}(${X})`;
        }
        return u.nil;
      }
    }
    subschema($, X) {
      let J = (0, qU.getSubschema)(this.it, $);
      (0, qU.extendSubschemaData)(J, this.it, $), (0, qU.extendSubschemaMode)(J, $);
      let Q = { ...this.it, ...J, items: void 0, props: void 0 };
      return uv(Q, X), Q;
    }
    mergeEvaluated($, X) {
      let { it: J, gen: Q } = this;
      if (!J.opts.unevaluated) return;
      if (J.props !== true && $.props !== void 0) J.props = Z4.mergeEvaluated.props(Q, $.props, J.props, X);
      if (J.items !== true && $.items !== void 0) J.items = Z4.mergeEvaluated.items(Q, $.items, J.items, X);
    }
    mergeValidEvaluated($, X) {
      let { it: J, gen: Q } = this;
      if (J.opts.unevaluated && (J.props !== true || J.items !== true)) return Q.if(X, () => this.mergeEvaluated($, u.Name)), true;
    }
  }
  fB.KeywordCxt = jU;
  function TB($, X, J, Q) {
    let Y = new jU($, J, X);
    if ("code" in J) J.code(Y, Q);
    else if (Y.$data && J.validate) (0, c9.funcKeywordCode)(Y, J);
    else if ("macro" in J) (0, c9.macroKeywordCode)(Y, J);
    else if (J.compile || J.validate) (0, c9.funcKeywordCode)(Y, J);
  }
  var $C = /^\/(?:[^~]|~0|~1)*$/, XC = /^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;
  function yB($, { dataLevel: X, dataNames: J, dataPathArr: Q }) {
    let Y, W;
    if ($ === "") return n.default.rootData;
    if ($[0] === "/") {
      if (!$C.test($)) throw Error(`Invalid JSON-pointer: ${$}`);
      Y = $, W = n.default.rootData;
    } else {
      let H = XC.exec($);
      if (!H) throw Error(`Invalid JSON-pointer: ${$}`);
      let K = +H[1];
      if (Y = H[2], Y === "#") {
        if (K >= X) throw Error(U("property/index", K));
        return Q[X - K];
      }
      if (K > X) throw Error(U("data", K));
      if (W = J[X - K], !Y) return W;
    }
    let z8 = W, G = Y.split("/");
    for (let H of G) if (H) W = u._`${W}${(0, u.getProperty)((0, Z4.unescapeJsonPointer)(H))}`, z8 = u._`${z8} && ${W}`;
    return z8;
    function U(H, K) {
      return `Cannot access ${H} ${K} levels up, current level is ${X}`;
    }
  }
  fB.getData = yB;
});
var rQ = k((uB) => {
  Object.defineProperty(uB, "__esModule", { value: true });
  class hB extends Error {
    constructor($) {
      super("validation failed");
      this.errors = $, this.ajv = this.validation = true;
    }
  }
  uB.default = hB;
});
var d9 = k((lB) => {
  Object.defineProperty(lB, "__esModule", { value: true });
  var FU = m9();
  class mB extends Error {
    constructor($, X, J, Q) {
      super(Q || `can't resolve reference ${J} from id ${X}`);
      this.missingRef = (0, FU.resolveUrl)($, X, J), this.missingSchema = (0, FU.normalizeId)((0, FU.getFullPath)($, this.missingRef));
    }
  }
  lB.default = mB;
});
var tQ = k((dB) => {
  Object.defineProperty(dB, "__esModule", { value: true });
  dB.resolveSchema = dB.getCompilingSchema = dB.resolveRef = dB.compileSchema = dB.SchemaEnv = void 0;
  var l6 = a(), zC = rQ(), h1 = b4(), c6 = m9(), cB = Q$(), GC = p9();
  class i9 {
    constructor($) {
      var X;
      this.refs = {}, this.dynamicAnchors = {};
      let J;
      if (typeof $.schema == "object") J = $.schema;
      this.schema = $.schema, this.schemaId = $.schemaId, this.root = $.root || this, this.baseId = (X = $.baseId) !== null && X !== void 0 ? X : (0, c6.normalizeId)(J === null || J === void 0 ? void 0 : J[$.schemaId || "$id"]), this.schemaPath = $.schemaPath, this.localRefs = $.localRefs, this.meta = $.meta, this.$async = J === null || J === void 0 ? void 0 : J.$async, this.refs = {};
    }
  }
  dB.SchemaEnv = i9;
  function AU($) {
    let X = pB.call(this, $);
    if (X) return X;
    let J = (0, c6.getFullPath)(this.opts.uriResolver, $.root.baseId), { es5: Q, lines: Y } = this.opts.code, { ownProperties: W } = this.opts, z8 = new l6.CodeGen(this.scope, { es5: Q, lines: Y, ownProperties: W }), G;
    if ($.$async) G = z8.scopeValue("Error", { ref: zC.default, code: l6._`require("ajv/dist/runtime/validation_error").default` });
    let U = z8.scopeName("validate");
    $.validateName = U;
    let H = { gen: z8, allErrors: this.opts.allErrors, data: h1.default.data, parentData: h1.default.parentData, parentDataProperty: h1.default.parentDataProperty, dataNames: [h1.default.data], dataPathArr: [l6.nil], dataLevel: 0, dataTypes: [], definedProperties: /* @__PURE__ */ new Set(), topSchemaRef: z8.scopeValue("schema", this.opts.code.source === true ? { ref: $.schema, code: (0, l6.stringify)($.schema) } : { ref: $.schema }), validateName: U, ValidationError: G, schema: $.schema, schemaEnv: $, rootId: J, baseId: $.baseId || J, schemaPath: l6.nil, errSchemaPath: $.schemaPath || (this.opts.jtd ? "" : "#"), errorPath: l6._`""`, opts: this.opts, self: this }, K;
    try {
      this._compilations.add($), (0, GC.validateFunctionCode)(H), z8.optimize(this.opts.code.optimize);
      let V = z8.toString();
      if (K = `${z8.scopeRefs(h1.default.scope)}return ${V}`, this.opts.code.process) K = this.opts.code.process(K, $);
      let O = Function(`${h1.default.self}`, `${h1.default.scope}`, K)(this, this.scope.get());
      if (this.scope.value(U, { ref: O }), O.errors = null, O.schema = $.schema, O.schemaEnv = $, $.$async) O.$async = true;
      if (this.opts.code.source === true) O.source = { validateName: U, validateCode: V, scopeValues: z8._values };
      if (this.opts.unevaluated) {
        let { props: w, items: B } = H;
        if (O.evaluated = { props: w instanceof l6.Name ? void 0 : w, items: B instanceof l6.Name ? void 0 : B, dynamicProps: w instanceof l6.Name, dynamicItems: B instanceof l6.Name }, O.source) O.source.evaluated = (0, l6.stringify)(O.evaluated);
      }
      return $.validate = O, $;
    } catch (V) {
      if (delete $.validate, delete $.validateName, K) this.logger.error("Error compiling schema, function code:", K);
      throw V;
    } finally {
      this._compilations.delete($);
    }
  }
  dB.compileSchema = AU;
  function UC($, X, J) {
    var Q;
    J = (0, c6.resolveUrl)(this.opts.uriResolver, X, J);
    let Y = $.refs[J];
    if (Y) return Y;
    let W = VC.call(this, $, J);
    if (W === void 0) {
      let z8 = (Q = $.localRefs) === null || Q === void 0 ? void 0 : Q[J], { schemaId: G } = this.opts;
      if (z8) W = new i9({ schema: z8, schemaId: G, root: $, baseId: X });
    }
    if (W === void 0) return;
    return $.refs[J] = HC.call(this, W);
  }
  dB.resolveRef = UC;
  function HC($) {
    if ((0, c6.inlineRef)($.schema, this.opts.inlineRefs)) return $.schema;
    return $.validate ? $ : AU.call(this, $);
  }
  function pB($) {
    for (let X of this._compilations) if (KC(X, $)) return X;
  }
  dB.getCompilingSchema = pB;
  function KC($, X) {
    return $.schema === X.schema && $.root === X.root && $.baseId === X.baseId;
  }
  function VC($, X) {
    let J;
    while (typeof (J = this.refs[X]) == "string") X = J;
    return J || this.schemas[X] || oQ.call(this, $, X);
  }
  function oQ($, X) {
    let J = this.opts.uriResolver.parse(X), Q = (0, c6._getFullPath)(this.opts.uriResolver, J), Y = (0, c6.getFullPath)(this.opts.uriResolver, $.baseId, void 0);
    if (Object.keys($.schema).length > 0 && Q === Y) return MU.call(this, J, $);
    let W = (0, c6.normalizeId)(Q), z8 = this.refs[W] || this.schemas[W];
    if (typeof z8 == "string") {
      let G = oQ.call(this, $, z8);
      if (typeof (G === null || G === void 0 ? void 0 : G.schema) !== "object") return;
      return MU.call(this, J, G);
    }
    if (typeof (z8 === null || z8 === void 0 ? void 0 : z8.schema) !== "object") return;
    if (!z8.validate) AU.call(this, z8);
    if (W === (0, c6.normalizeId)(X)) {
      let { schema: G } = z8, { schemaId: U } = this.opts, H = G[U];
      if (H) Y = (0, c6.resolveUrl)(this.opts.uriResolver, Y, H);
      return new i9({ schema: G, schemaId: U, root: $, baseId: Y });
    }
    return MU.call(this, J, z8);
  }
  dB.resolveSchema = oQ;
  var NC = /* @__PURE__ */ new Set(["properties", "patternProperties", "enum", "dependencies", "definitions"]);
  function MU($, { baseId: X, schema: J, root: Q }) {
    var Y;
    if (((Y = $.fragment) === null || Y === void 0 ? void 0 : Y[0]) !== "/") return;
    for (let G of $.fragment.slice(1).split("/")) {
      if (typeof J === "boolean") return;
      let U = J[(0, cB.unescapeFragment)(G)];
      if (U === void 0) return;
      J = U;
      let H = typeof J === "object" && J[this.opts.schemaId];
      if (!NC.has(G) && H) X = (0, c6.resolveUrl)(this.opts.uriResolver, X, H);
    }
    let W;
    if (typeof J != "boolean" && J.$ref && !(0, cB.schemaHasRulesButRef)(J, this.RULES)) {
      let G = (0, c6.resolveUrl)(this.opts.uriResolver, X, J.$ref);
      W = oQ.call(this, Q, G);
    }
    let { schemaId: z8 } = this.opts;
    if (W = W || new i9({ schema: J, schemaId: z8, root: Q, baseId: X }), W.schema !== W.root.schema) return W;
    return;
  }
});
var nB = k((Gs, LC) => {
  LC.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: false };
});
var oB = k((Us, rB) => {
  var DC = { 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, a: 10, A: 10, b: 11, B: 11, c: 12, C: 12, d: 13, D: 13, e: 14, E: 14, f: 15, F: 15 };
  rB.exports = { HEX: DC };
});
var Yq = k((Hs, Jq) => {
  var { HEX: jC } = oB(), FC = /^(?:(?: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 eB($) {
    if (Xq($, ".") < 3) return { host: $, isIPV4: false };
    let X = $.match(FC) || [], [J] = X;
    if (J) return { host: AC(J, "."), isIPV4: true };
    else return { host: $, isIPV4: false };
  }
  function IU($, X = false) {
    let J = "", Q = true;
    for (let Y of $) {
      if (jC[Y] === void 0) return;
      if (Y !== "0" && Q === true) Q = false;
      if (!Q) J += Y;
    }
    if (X && J.length === 0) J = "0";
    return J;
  }
  function MC($) {
    let X = 0, J = { error: false, address: "", zone: "" }, Q = [], Y = [], W = false, z8 = false, G = false;
    function U() {
      if (Y.length) {
        if (W === false) {
          let H = IU(Y);
          if (H !== void 0) Q.push(H);
          else return J.error = true, false;
        }
        Y.length = 0;
      }
      return true;
    }
    for (let H = 0; H < $.length; H++) {
      let K = $[H];
      if (K === "[" || K === "]") continue;
      if (K === ":") {
        if (z8 === true) G = true;
        if (!U()) break;
        if (X++, Q.push(":"), X > 7) {
          J.error = true;
          break;
        }
        if (H - 1 >= 0 && $[H - 1] === ":") z8 = true;
        continue;
      } else if (K === "%") {
        if (!U()) break;
        W = true;
      } else {
        Y.push(K);
        continue;
      }
    }
    if (Y.length) if (W) J.zone = Y.join("");
    else if (G) Q.push(Y.join(""));
    else Q.push(IU(Y));
    return J.address = Q.join(""), J;
  }
  function $q($) {
    if (Xq($, ":") < 2) return { host: $, isIPV6: false };
    let X = MC($);
    if (!X.error) {
      let { address: J, address: Q } = X;
      if (X.zone) J += "%" + X.zone, Q += "%25" + X.zone;
      return { host: J, escapedHost: Q, isIPV6: true };
    } else return { host: $, isIPV6: false };
  }
  function AC($, X) {
    let J = "", Q = true, Y = $.length;
    for (let W = 0; W < Y; W++) {
      let z8 = $[W];
      if (z8 === "0" && Q) {
        if (W + 1 <= Y && $[W + 1] === X || W + 1 === Y) J += z8, Q = false;
      } else {
        if (z8 === X) Q = true;
        else Q = false;
        J += z8;
      }
    }
    return J;
  }
  function Xq($, X) {
    let J = 0;
    for (let Q = 0; Q < $.length; Q++) if ($[Q] === X) J++;
    return J;
  }
  var tB = /^\.\.?\//u, aB = /^\/\.(?:\/|$)/u, sB = /^\/\.\.(?:\/|$)/u, IC = /^\/?(?:.|\n)*?(?=\/|$)/u;
  function bC($) {
    let X = [];
    while ($.length) if ($.match(tB)) $ = $.replace(tB, "");
    else if ($.match(aB)) $ = $.replace(aB, "/");
    else if ($.match(sB)) $ = $.replace(sB, "/"), X.pop();
    else if ($ === "." || $ === "..") $ = "";
    else {
      let J = $.match(IC);
      if (J) {
        let Q = J[0];
        $ = $.slice(Q.length), X.push(Q);
      } else throw Error("Unexpected dot segment condition");
    }
    return X.join("");
  }
  function ZC($, X) {
    let J = X !== true ? escape : unescape;
    if ($.scheme !== void 0) $.scheme = J($.scheme);
    if ($.userinfo !== void 0) $.userinfo = J($.userinfo);
    if ($.host !== void 0) $.host = J($.host);
    if ($.path !== void 0) $.path = J($.path);
    if ($.query !== void 0) $.query = J($.query);
    if ($.fragment !== void 0) $.fragment = J($.fragment);
    return $;
  }
  function PC($) {
    let X = [];
    if ($.userinfo !== void 0) X.push($.userinfo), X.push("@");
    if ($.host !== void 0) {
      let J = unescape($.host), Q = eB(J);
      if (Q.isIPV4) J = Q.host;
      else {
        let Y = $q(Q.host);
        if (Y.isIPV6 === true) J = `[${Y.escapedHost}]`;
        else J = $.host;
      }
      X.push(J);
    }
    if (typeof $.port === "number" || typeof $.port === "string") X.push(":"), X.push(String($.port));
    return X.length ? X.join("") : void 0;
  }
  Jq.exports = { recomposeAuthority: PC, normalizeComponentEncoding: ZC, removeDotSegments: bC, normalizeIPv4: eB, normalizeIPv6: $q, stringArrayToHexStripped: IU };
});
var Hq = k((Ks, Uq) => {
  var RC = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu, EC = /([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu;
  function Qq($) {
    return typeof $.secure === "boolean" ? $.secure : String($.scheme).toLowerCase() === "wss";
  }
  function Wq($) {
    if (!$.host) $.error = $.error || "HTTP URIs must have a host.";
    return $;
  }
  function zq($) {
    let X = String($.scheme).toLowerCase() === "https";
    if ($.port === (X ? 443 : 80) || $.port === "") $.port = void 0;
    if (!$.path) $.path = "/";
    return $;
  }
  function SC($) {
    return $.secure = Qq($), $.resourceName = ($.path || "/") + ($.query ? "?" + $.query : ""), $.path = void 0, $.query = void 0, $;
  }
  function vC($) {
    if ($.port === (Qq($) ? 443 : 80) || $.port === "") $.port = void 0;
    if (typeof $.secure === "boolean") $.scheme = $.secure ? "wss" : "ws", $.secure = void 0;
    if ($.resourceName) {
      let [X, J] = $.resourceName.split("?");
      $.path = X && X !== "/" ? X : void 0, $.query = J, $.resourceName = void 0;
    }
    return $.fragment = void 0, $;
  }
  function CC($, X) {
    if (!$.path) return $.error = "URN can not be parsed", $;
    let J = $.path.match(EC);
    if (J) {
      let Q = X.scheme || $.scheme || "urn";
      $.nid = J[1].toLowerCase(), $.nss = J[2];
      let Y = `${Q}:${X.nid || $.nid}`, W = bU[Y];
      if ($.path = void 0, W) $ = W.parse($, X);
    } else $.error = $.error || "URN can not be parsed.";
    return $;
  }
  function kC($, X) {
    let J = X.scheme || $.scheme || "urn", Q = $.nid.toLowerCase(), Y = `${J}:${X.nid || Q}`, W = bU[Y];
    if (W) $ = W.serialize($, X);
    let z8 = $, G = $.nss;
    return z8.path = `${Q || X.nid}:${G}`, X.skipEscape = true, z8;
  }
  function _C($, X) {
    let J = $;
    if (J.uuid = J.nss, J.nss = void 0, !X.tolerant && (!J.uuid || !RC.test(J.uuid))) J.error = J.error || "UUID is not valid.";
    return J;
  }
  function xC($) {
    let X = $;
    return X.nss = ($.uuid || "").toLowerCase(), X;
  }
  var Gq = { scheme: "http", domainHost: true, parse: Wq, serialize: zq }, TC = { scheme: "https", domainHost: Gq.domainHost, parse: Wq, serialize: zq }, aQ = { scheme: "ws", domainHost: true, parse: SC, serialize: vC }, yC = { scheme: "wss", domainHost: aQ.domainHost, parse: aQ.parse, serialize: aQ.serialize }, fC = { scheme: "urn", parse: CC, serialize: kC, skipNormalize: true }, gC = { scheme: "urn:uuid", parse: _C, serialize: xC, skipNormalize: true }, bU = { http: Gq, https: TC, ws: aQ, wss: yC, urn: fC, "urn:uuid": gC };
  Uq.exports = bU;
});
var Vq = k((Vs, eQ) => {
  var { normalizeIPv6: hC, normalizeIPv4: uC, removeDotSegments: n9, recomposeAuthority: mC, normalizeComponentEncoding: sQ } = Yq(), ZU = Hq();
  function lC($, X) {
    if (typeof $ === "string") $ = s6(P4($, X), X);
    else if (typeof $ === "object") $ = P4(s6($, X), X);
    return $;
  }
  function cC($, X, J) {
    let Q = Object.assign({ scheme: "null" }, J), Y = Kq(P4($, Q), P4(X, Q), Q, true);
    return s6(Y, { ...Q, skipEscape: true });
  }
  function Kq($, X, J, Q) {
    let Y = {};
    if (!Q) $ = P4(s6($, J), J), X = P4(s6(X, J), J);
    if (J = J || {}, !J.tolerant && X.scheme) Y.scheme = X.scheme, Y.userinfo = X.userinfo, Y.host = X.host, Y.port = X.port, Y.path = n9(X.path || ""), Y.query = X.query;
    else {
      if (X.userinfo !== void 0 || X.host !== void 0 || X.port !== void 0) Y.userinfo = X.userinfo, Y.host = X.host, Y.port = X.port, Y.path = n9(X.path || ""), Y.query = X.query;
      else {
        if (!X.path) if (Y.path = $.path, X.query !== void 0) Y.query = X.query;
        else Y.query = $.query;
        else {
          if (X.path.charAt(0) === "/") Y.path = n9(X.path);
          else {
            if (($.userinfo !== void 0 || $.host !== void 0 || $.port !== void 0) && !$.path) Y.path = "/" + X.path;
            else if (!$.path) Y.path = X.path;
            else Y.path = $.path.slice(0, $.path.lastIndexOf("/") + 1) + X.path;
            Y.path = n9(Y.path);
          }
          Y.query = X.query;
        }
        Y.userinfo = $.userinfo, Y.host = $.host, Y.port = $.port;
      }
      Y.scheme = $.scheme;
    }
    return Y.fragment = X.fragment, Y;
  }
  function pC($, X, J) {
    if (typeof $ === "string") $ = unescape($), $ = s6(sQ(P4($, J), true), { ...J, skipEscape: true });
    else if (typeof $ === "object") $ = s6(sQ($, true), { ...J, skipEscape: true });
    if (typeof X === "string") X = unescape(X), X = s6(sQ(P4(X, J), true), { ...J, skipEscape: true });
    else if (typeof X === "object") X = s6(sQ(X, true), { ...J, skipEscape: true });
    return $.toLowerCase() === X.toLowerCase();
  }
  function s6($, X) {
    let J = { host: $.host, scheme: $.scheme, userinfo: $.userinfo, port: $.port, path: $.path, query: $.query, nid: $.nid, nss: $.nss, uuid: $.uuid, fragment: $.fragment, reference: $.reference, resourceName: $.resourceName, secure: $.secure, error: "" }, Q = Object.assign({}, X), Y = [], W = ZU[(Q.scheme || J.scheme || "").toLowerCase()];
    if (W && W.serialize) W.serialize(J, Q);
    if (J.path !== void 0) if (!Q.skipEscape) {
      if (J.path = escape(J.path), J.scheme !== void 0) J.path = J.path.split("%3A").join(":");
    } else J.path = unescape(J.path);
    if (Q.reference !== "suffix" && J.scheme) Y.push(J.scheme, ":");
    let z8 = mC(J);
    if (z8 !== void 0) {
      if (Q.reference !== "suffix") Y.push("//");
      if (Y.push(z8), J.path && J.path.charAt(0) !== "/") Y.push("/");
    }
    if (J.path !== void 0) {
      let G = J.path;
      if (!Q.absolutePath && (!W || !W.absolutePath)) G = n9(G);
      if (z8 === void 0) G = G.replace(/^\/\//u, "/%2F");
      Y.push(G);
    }
    if (J.query !== void 0) Y.push("?", J.query);
    if (J.fragment !== void 0) Y.push("#", J.fragment);
    return Y.join("");
  }
  var dC = Array.from({ length: 127 }, ($, X) => /[^!"$&'()*+,\-.;=_`a-z{}~]/u.test(String.fromCharCode(X)));
  function iC($) {
    let X = 0;
    for (let J = 0, Q = $.length; J < Q; ++J) if (X = $.charCodeAt(J), X > 126 || dC[X]) return true;
    return false;
  }
  var nC = /^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;
  function P4($, X) {
    let J = Object.assign({}, X), Q = { scheme: void 0, userinfo: void 0, host: "", port: void 0, path: "", query: void 0, fragment: void 0 }, Y = $.indexOf("%") !== -1, W = false;
    if (J.reference === "suffix") $ = (J.scheme ? J.scheme + ":" : "") + "//" + $;
    let z8 = $.match(nC);
    if (z8) {
      if (Q.scheme = z8[1], Q.userinfo = z8[3], Q.host = z8[4], Q.port = parseInt(z8[5], 10), Q.path = z8[6] || "", Q.query = z8[7], Q.fragment = z8[8], isNaN(Q.port)) Q.port = z8[5];
      if (Q.host) {
        let U = uC(Q.host);
        if (U.isIPV4 === false) {
          let H = hC(U.host);
          Q.host = H.host.toLowerCase(), W = H.isIPV6;
        } else Q.host = U.host, W = true;
      }
      if (Q.scheme === void 0 && Q.userinfo === void 0 && Q.host === void 0 && Q.port === void 0 && Q.query === void 0 && !Q.path) Q.reference = "same-document";
      else if (Q.scheme === void 0) Q.reference = "relative";
      else if (Q.fragment === void 0) Q.reference = "absolute";
      else Q.reference = "uri";
      if (J.reference && J.reference !== "suffix" && J.reference !== Q.reference) Q.error = Q.error || "URI is not a " + J.reference + " reference.";
      let G = ZU[(J.scheme || Q.scheme || "").toLowerCase()];
      if (!J.unicodeSupport && (!G || !G.unicodeSupport)) {
        if (Q.host && (J.domainHost || G && G.domainHost) && W === false && iC(Q.host)) try {
          Q.host = URL.domainToASCII(Q.host.toLowerCase());
        } catch (U) {
          Q.error = Q.error || "Host's domain name can not be converted to ASCII: " + U;
        }
      }
      if (!G || G && !G.skipNormalize) {
        if (Y && Q.scheme !== void 0) Q.scheme = unescape(Q.scheme);
        if (Y && Q.host !== void 0) Q.host = unescape(Q.host);
        if (Q.path) Q.path = escape(unescape(Q.path));
        if (Q.fragment) Q.fragment = encodeURI(decodeURIComponent(Q.fragment));
      }
      if (G && G.parse) G.parse(Q, J);
    } else Q.error = Q.error || "URI can not be parsed.";
    return Q;
  }
  var PU = { SCHEMES: ZU, normalize: lC, resolve: cC, resolveComponents: Kq, equal: pC, serialize: s6, parse: P4 };
  eQ.exports = PU;
  eQ.exports.default = PU;
  eQ.exports.fastUri = PU;
});
var wq = k((Oq) => {
  Object.defineProperty(Oq, "__esModule", { value: true });
  var Nq = Vq();
  Nq.code = 'require("ajv/dist/runtime/uri").default';
  Oq.default = Nq;
});
var Aq = k((R4) => {
  Object.defineProperty(R4, "__esModule", { value: true });
  R4.CodeGen = R4.Name = R4.nil = R4.stringify = R4.str = R4._ = R4.KeywordCxt = void 0;
  var oC = p9();
  Object.defineProperty(R4, "KeywordCxt", { enumerable: true, get: function() {
    return oC.KeywordCxt;
  } });
  var $8 = a();
  Object.defineProperty(R4, "_", { enumerable: true, get: function() {
    return $8._;
  } });
  Object.defineProperty(R4, "str", { enumerable: true, get: function() {
    return $8.str;
  } });
  Object.defineProperty(R4, "stringify", { enumerable: true, get: function() {
    return $8.stringify;
  } });
  Object.defineProperty(R4, "nil", { enumerable: true, get: function() {
    return $8.nil;
  } });
  Object.defineProperty(R4, "Name", { enumerable: true, get: function() {
    return $8.Name;
  } });
  Object.defineProperty(R4, "CodeGen", { enumerable: true, get: function() {
    return $8.CodeGen;
  } });
  var tC = rQ(), jq = d9(), aC = zU(), r9 = tQ(), sC = a(), o9 = m9(), $5 = u9(), EU = Q$(), Bq = nB(), eC = wq(), Fq = ($, X) => new RegExp($, X);
  Fq.code = "new RegExp";
  var $k = ["removeAdditional", "useDefaults", "coerceTypes"], Xk = /* @__PURE__ */ new Set(["validate", "serialize", "parse", "wrapper", "root", "schema", "keyword", "pattern", "formats", "validate$data", "func", "obj", "Error"]), Jk = { 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." }, Yk = { ignoreKeywordsWithRef: "", jsPropertySyntax: "", unicode: '"minLength"/"maxLength" account for unicode characters by default.' }, qq = 200;
  function Qk($) {
    var X, J, Q, Y, W, z8, G, U, H, K, V, N, O, w, B, D, j, A, I, x, T, U$, T$, n$, X4;
    let X6 = $.strict, U1 = (X = $.code) === null || X === void 0 ? void 0 : X.optimize, l1 = U1 === true || U1 === void 0 ? 1 : U1 || 0, J4 = (Q = (J = $.code) === null || J === void 0 ? void 0 : J.regExp) !== null && Q !== void 0 ? Q : Fq, z82 = (Y = $.uriResolver) !== null && Y !== void 0 ? Y : eC.default;
    return { strictSchema: (z8 = (W = $.strictSchema) !== null && W !== void 0 ? W : X6) !== null && z8 !== void 0 ? z8 : true, strictNumbers: (U = (G = $.strictNumbers) !== null && G !== void 0 ? G : X6) !== null && U !== void 0 ? U : true, strictTypes: (K = (H = $.strictTypes) !== null && H !== void 0 ? H : X6) !== null && K !== void 0 ? K : "log", strictTuples: (N = (V = $.strictTuples) !== null && V !== void 0 ? V : X6) !== null && N !== void 0 ? N : "log", strictRequired: (w = (O = $.strictRequired) !== null && O !== void 0 ? O : X6) !== null && w !== void 0 ? w : false, code: $.code ? { ...$.code, optimize: l1, regExp: J4 } : { optimize: l1, regExp: J4 }, loopRequired: (B = $.loopRequired) !== null && B !== void 0 ? B : qq, loopEnum: (D = $.loopEnum) !== null && D !== void 0 ? D : qq, meta: (j = $.meta) !== null && j !== void 0 ? j : true, messages: (A = $.messages) !== null && A !== void 0 ? A : true, inlineRefs: (I = $.inlineRefs) !== null && I !== void 0 ? I : true, schemaId: (x = $.schemaId) !== null && x !== void 0 ? x : "$id", addUsedSchema: (T = $.addUsedSchema) !== null && T !== void 0 ? T : true, validateSchema: (U$ = $.validateSchema) !== null && U$ !== void 0 ? U$ : true, validateFormats: (T$ = $.validateFormats) !== null && T$ !== void 0 ? T$ : true, unicodeRegExp: (n$ = $.unicodeRegExp) !== null && n$ !== void 0 ? n$ : true, int32range: (X4 = $.int32range) !== null && X4 !== void 0 ? X4 : true, uriResolver: z82 };
  }
  class X5 {
    constructor($ = {}) {
      this.schemas = {}, this.refs = {}, this.formats = {}, this._compilations = /* @__PURE__ */ new Set(), this._loading = {}, this._cache = /* @__PURE__ */ new Map(), $ = this.opts = { ...$, ...Qk($) };
      let { es5: X, lines: J } = this.opts.code;
      this.scope = new sC.ValueScope({ scope: {}, prefixes: Xk, es5: X, lines: J }), this.logger = Kk($.logger);
      let Q = $.validateFormats;
      if ($.validateFormats = false, this.RULES = (0, aC.getRules)(), Lq.call(this, Jk, $, "NOT SUPPORTED"), Lq.call(this, Yk, $, "DEPRECATED", "warn"), this._metaOpts = Uk.call(this), $.formats) zk.call(this);
      if (this._addVocabularies(), this._addDefaultMetaSchema(), $.keywords) Gk.call(this, $.keywords);
      if (typeof $.meta == "object") this.addMetaSchema($.meta);
      Wk.call(this), $.validateFormats = Q;
    }
    _addVocabularies() {
      this.addKeyword("$async");
    }
    _addDefaultMetaSchema() {
      let { $data: $, meta: X, schemaId: J } = this.opts, Q = Bq;
      if (J === "id") Q = { ...Bq }, Q.id = Q.$id, delete Q.$id;
      if (X && $) this.addMetaSchema(Q, Q[J], false);
    }
    defaultMeta() {
      let { meta: $, schemaId: X } = this.opts;
      return this.opts.defaultMeta = typeof $ == "object" ? $[X] || $ : void 0;
    }
    validate($, X) {
      let J;
      if (typeof $ == "string") {
        if (J = this.getSchema($), !J) throw Error(`no schema with key or ref "${$}"`);
      } else J = this.compile($);
      let Q = J(X);
      if (!("$async" in J)) this.errors = J.errors;
      return Q;
    }
    compile($, X) {
      let J = this._addSchema($, X);
      return J.validate || this._compileSchemaEnv(J);
    }
    compileAsync($, X) {
      if (typeof this.opts.loadSchema != "function") throw Error("options.loadSchema should be a function");
      let { loadSchema: J } = this.opts;
      return Q.call(this, $, X);
      async function Q(H, K) {
        await Y.call(this, H.$schema);
        let V = this._addSchema(H, K);
        return V.validate || W.call(this, V);
      }
      async function Y(H) {
        if (H && !this.getSchema(H)) await Q.call(this, { $ref: H }, true);
      }
      async function W(H) {
        try {
          return this._compileSchemaEnv(H);
        } catch (K) {
          if (!(K instanceof jq.default)) throw K;
          return z8.call(this, K), await G.call(this, K.missingSchema), W.call(this, H);
        }
      }
      function z8({ missingSchema: H, missingRef: K }) {
        if (this.refs[H]) throw Error(`AnySchema ${H} is loaded but ${K} cannot be resolved`);
      }
      async function G(H) {
        let K = await U.call(this, H);
        if (!this.refs[H]) await Y.call(this, K.$schema);
        if (!this.refs[H]) this.addSchema(K, H, X);
      }
      async function U(H) {
        let K = this._loading[H];
        if (K) return K;
        try {
          return await (this._loading[H] = J(H));
        } finally {
          delete this._loading[H];
        }
      }
    }
    addSchema($, X, J, Q = this.opts.validateSchema) {
      if (Array.isArray($)) {
        for (let W of $) this.addSchema(W, void 0, J, Q);
        return this;
      }
      let Y;
      if (typeof $ === "object") {
        let { schemaId: W } = this.opts;
        if (Y = $[W], Y !== void 0 && typeof Y != "string") throw Error(`schema ${W} must be string`);
      }
      return X = (0, o9.normalizeId)(X || Y), this._checkUnique(X), this.schemas[X] = this._addSchema($, J, X, Q, true), this;
    }
    addMetaSchema($, X, J = this.opts.validateSchema) {
      return this.addSchema($, X, true, J), this;
    }
    validateSchema($, X) {
      if (typeof $ == "boolean") return true;
      let J;
      if (J = $.$schema, J !== void 0 && typeof J != "string") throw Error("$schema must be a string");
      if (J = J || this.opts.defaultMeta || this.defaultMeta(), !J) return this.logger.warn("meta-schema not available"), this.errors = null, true;
      let Q = this.validate(J, $);
      if (!Q && X) {
        let Y = "schema is invalid: " + this.errorsText();
        if (this.opts.validateSchema === "log") this.logger.error(Y);
        else throw Error(Y);
      }
      return Q;
    }
    getSchema($) {
      let X;
      while (typeof (X = Dq.call(this, $)) == "string") $ = X;
      if (X === void 0) {
        let { schemaId: J } = this.opts, Q = new r9.SchemaEnv({ schema: {}, schemaId: J });
        if (X = r9.resolveSchema.call(this, Q, $), !X) return;
        this.refs[$] = X;
      }
      return X.validate || this._compileSchemaEnv(X);
    }
    removeSchema($) {
      if ($ instanceof RegExp) return this._removeAllSchemas(this.schemas, $), this._removeAllSchemas(this.refs, $), this;
      switch (typeof $) {
        case "undefined":
          return this._removeAllSchemas(this.schemas), this._removeAllSchemas(this.refs), this._cache.clear(), this;
        case "string": {
          let X = Dq.call(this, $);
          if (typeof X == "object") this._cache.delete(X.schema);
          return delete this.schemas[$], delete this.refs[$], this;
        }
        case "object": {
          let X = $;
          this._cache.delete(X);
          let J = $[this.opts.schemaId];
          if (J) J = (0, o9.normalizeId)(J), delete this.schemas[J], delete this.refs[J];
          return this;
        }
        default:
          throw Error("ajv.removeSchema: invalid parameter");
      }
    }
    addVocabulary($) {
      for (let X of $) this.addKeyword(X);
      return this;
    }
    addKeyword($, X) {
      let J;
      if (typeof $ == "string") {
        if (J = $, typeof X == "object") this.logger.warn("these parameters are deprecated, see docs for addKeyword"), X.keyword = J;
      } else if (typeof $ == "object" && X === void 0) {
        if (X = $, J = X.keyword, Array.isArray(J) && !J.length) throw Error("addKeywords: keyword must be string or non-empty array");
      } else throw Error("invalid addKeywords parameters");
      if (Nk.call(this, J, X), !X) return (0, EU.eachItem)(J, (Y) => RU.call(this, Y)), this;
      wk.call(this, X);
      let Q = { ...X, type: (0, $5.getJSONTypes)(X.type), schemaType: (0, $5.getJSONTypes)(X.schemaType) };
      return (0, EU.eachItem)(J, Q.type.length === 0 ? (Y) => RU.call(this, Y, Q) : (Y) => Q.type.forEach((W) => RU.call(this, Y, Q, W))), this;
    }
    getKeyword($) {
      let X = this.RULES.all[$];
      return typeof X == "object" ? X.definition : !!X;
    }
    removeKeyword($) {
      let { RULES: X } = this;
      delete X.keywords[$], delete X.all[$];
      for (let J of X.rules) {
        let Q = J.rules.findIndex((Y) => Y.keyword === $);
        if (Q >= 0) J.rules.splice(Q, 1);
      }
      return this;
    }
    addFormat($, X) {
      if (typeof X == "string") X = new RegExp(X);
      return this.formats[$] = X, this;
    }
    errorsText($ = this.errors, { separator: X = ", ", dataVar: J = "data" } = {}) {
      if (!$ || $.length === 0) return "No errors";
      return $.map((Q) => `${J}${Q.instancePath} ${Q.message}`).reduce((Q, Y) => Q + X + Y);
    }
    $dataMetaSchema($, X) {
      let J = this.RULES.all;
      $ = JSON.parse(JSON.stringify($));
      for (let Q of X) {
        let Y = Q.split("/").slice(1), W = $;
        for (let z8 of Y) W = W[z8];
        for (let z8 in J) {
          let G = J[z8];
          if (typeof G != "object") continue;
          let { $data: U } = G.definition, H = W[z8];
          if (U && H) W[z8] = Mq(H);
        }
      }
      return $;
    }
    _removeAllSchemas($, X) {
      for (let J in $) {
        let Q = $[J];
        if (!X || X.test(J)) {
          if (typeof Q == "string") delete $[J];
          else if (Q && !Q.meta) this._cache.delete(Q.schema), delete $[J];
        }
      }
    }
    _addSchema($, X, J, Q = this.opts.validateSchema, Y = this.opts.addUsedSchema) {
      let W, { schemaId: z8 } = this.opts;
      if (typeof $ == "object") W = $[z8];
      else if (this.opts.jtd) throw Error("schema must be object");
      else if (typeof $ != "boolean") throw Error("schema must be object or boolean");
      let G = this._cache.get($);
      if (G !== void 0) return G;
      J = (0, o9.normalizeId)(W || J);
      let U = o9.getSchemaRefs.call(this, $, J);
      if (G = new r9.SchemaEnv({ schema: $, schemaId: z8, meta: X, baseId: J, localRefs: U }), this._cache.set(G.schema, G), Y && !J.startsWith("#")) {
        if (J) this._checkUnique(J);
        this.refs[J] = G;
      }
      if (Q) this.validateSchema($, true);
      return G;
    }
    _checkUnique($) {
      if (this.schemas[$] || this.refs[$]) throw Error(`schema with key or id "${$}" already exists`);
    }
    _compileSchemaEnv($) {
      if ($.meta) this._compileMetaSchema($);
      else r9.compileSchema.call(this, $);
      if (!$.validate) throw Error("ajv implementation error");
      return $.validate;
    }
    _compileMetaSchema($) {
      let X = this.opts;
      this.opts = this._metaOpts;
      try {
        r9.compileSchema.call(this, $);
      } finally {
        this.opts = X;
      }
    }
  }
  X5.ValidationError = tC.default;
  X5.MissingRefError = jq.default;
  R4.default = X5;
  function Lq($, X, J, Q = "error") {
    for (let Y in $) {
      let W = Y;
      if (W in X) this.logger[Q](`${J}: option ${Y}. ${$[W]}`);
    }
  }
  function Dq($) {
    return $ = (0, o9.normalizeId)($), this.schemas[$] || this.refs[$];
  }
  function Wk() {
    let $ = this.opts.schemas;
    if (!$) return;
    if (Array.isArray($)) this.addSchema($);
    else for (let X in $) this.addSchema($[X], X);
  }
  function zk() {
    for (let $ in this.opts.formats) {
      let X = this.opts.formats[$];
      if (X) this.addFormat($, X);
    }
  }
  function Gk($) {
    if (Array.isArray($)) {
      this.addVocabulary($);
      return;
    }
    this.logger.warn("keywords option as map is deprecated, pass array");
    for (let X in $) {
      let J = $[X];
      if (!J.keyword) J.keyword = X;
      this.addKeyword(J);
    }
  }
  function Uk() {
    let $ = { ...this.opts };
    for (let X of $k) delete $[X];
    return $;
  }
  var Hk = { log() {
  }, warn() {
  }, error() {
  } };
  function Kk($) {
    if ($ === false) return Hk;
    if ($ === void 0) return console;
    if ($.log && $.warn && $.error) return $;
    throw Error("logger must implement log, warn and error methods");
  }
  var Vk = /^[a-z_$][a-z0-9_$:-]*$/i;
  function Nk($, X) {
    let { RULES: J } = this;
    if ((0, EU.eachItem)($, (Q) => {
      if (J.keywords[Q]) throw Error(`Keyword ${Q} is already defined`);
      if (!Vk.test(Q)) throw Error(`Keyword ${Q} has invalid name`);
    }), !X) return;
    if (X.$data && !("code" in X || "validate" in X)) throw Error('$data keyword must have "code" or "validate" function');
  }
  function RU($, X, J) {
    var Q;
    let Y = X === null || X === void 0 ? void 0 : X.post;
    if (J && Y) throw Error('keyword with "post" flag cannot have "type"');
    let { RULES: W } = this, z8 = Y ? W.post : W.rules.find(({ type: U }) => U === J);
    if (!z8) z8 = { type: J, rules: [] }, W.rules.push(z8);
    if (W.keywords[$] = true, !X) return;
    let G = { keyword: $, definition: { ...X, type: (0, $5.getJSONTypes)(X.type), schemaType: (0, $5.getJSONTypes)(X.schemaType) } };
    if (X.before) Ok.call(this, z8, G, X.before);
    else z8.rules.push(G);
    W.all[$] = G, (Q = X.implements) === null || Q === void 0 || Q.forEach((U) => this.addKeyword(U));
  }
  function Ok($, X, J) {
    let Q = $.rules.findIndex((Y) => Y.keyword === J);
    if (Q >= 0) $.rules.splice(Q, 0, X);
    else $.rules.push(X), this.logger.warn(`rule ${J} is not defined`);
  }
  function wk($) {
    let { metaSchema: X } = $;
    if (X === void 0) return;
    if ($.$data && this.opts.$data) X = Mq(X);
    $.validateSchema = this.compile(X, true);
  }
  var Bk = { $ref: "https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#" };
  function Mq($) {
    return { anyOf: [$, Bk] };
  }
});
var bq = k((Iq) => {
  Object.defineProperty(Iq, "__esModule", { value: true });
  var Dk = { keyword: "id", code() {
    throw Error('NOT SUPPORTED: keyword "id", use "$id" for schema ID');
  } };
  Iq.default = Dk;
});
var vq = k((Eq) => {
  Object.defineProperty(Eq, "__esModule", { value: true });
  Eq.callRef = Eq.getValidate = void 0;
  var Fk = d9(), Zq = E6(), V6 = a(), X8 = b4(), Pq = tQ(), J5 = Q$(), Mk = { keyword: "$ref", schemaType: "string", code($) {
    let { gen: X, schema: J, it: Q } = $, { baseId: Y, schemaEnv: W, validateName: z8, opts: G, self: U } = Q, { root: H } = W;
    if ((J === "#" || J === "#/") && Y === H.baseId) return V();
    let K = Pq.resolveRef.call(U, H, Y, J);
    if (K === void 0) throw new Fk.default(Q.opts.uriResolver, Y, J);
    if (K instanceof Pq.SchemaEnv) return N(K);
    return O(K);
    function V() {
      if (W === H) return Y5($, z8, W, W.$async);
      let w = X.scopeValue("root", { ref: H });
      return Y5($, V6._`${w}.validate`, H, H.$async);
    }
    function N(w) {
      let B = Rq($, w);
      Y5($, B, w, w.$async);
    }
    function O(w) {
      let B = X.scopeValue("schema", G.code.source === true ? { ref: w, code: (0, V6.stringify)(w) } : { ref: w }), D = X.name("valid"), j = $.subschema({ schema: w, dataTypes: [], schemaPath: V6.nil, topSchemaRef: B, errSchemaPath: J }, D);
      $.mergeEvaluated(j), $.ok(D);
    }
  } };
  function Rq($, X) {
    let { gen: J } = $;
    return X.validate ? J.scopeValue("validate", { ref: X.validate }) : V6._`${J.scopeValue("wrapper", { ref: X })}.validate`;
  }
  Eq.getValidate = Rq;
  function Y5($, X, J, Q) {
    let { gen: Y, it: W } = $, { allErrors: z8, schemaEnv: G, opts: U } = W, H = U.passContext ? X8.default.this : V6.nil;
    if (Q) K();
    else V();
    function K() {
      if (!G.$async) throw Error("async schema referenced by sync schema");
      let w = Y.let("valid");
      Y.try(() => {
        if (Y.code(V6._`await ${(0, Zq.callValidateCode)($, X, H)}`), O(X), !z8) Y.assign(w, true);
      }, (B) => {
        if (Y.if(V6._`!(${B} instanceof ${W.ValidationError})`, () => Y.throw(B)), N(B), !z8) Y.assign(w, false);
      }), $.ok(w);
    }
    function V() {
      $.result((0, Zq.callValidateCode)($, X, H), () => O(X), () => N(X));
    }
    function N(w) {
      let B = V6._`${w}.errors`;
      Y.assign(X8.default.vErrors, V6._`${X8.default.vErrors} === null ? ${B} : ${X8.default.vErrors}.concat(${B})`), Y.assign(X8.default.errors, V6._`${X8.default.vErrors}.length`);
    }
    function O(w) {
      var B;
      if (!W.opts.unevaluated) return;
      let D = (B = J === null || J === void 0 ? void 0 : J.validate) === null || B === void 0 ? void 0 : B.evaluated;
      if (W.props !== true) if (D && !D.dynamicProps) {
        if (D.props !== void 0) W.props = J5.mergeEvaluated.props(Y, D.props, W.props);
      } else {
        let j = Y.var("props", V6._`${w}.evaluated.props`);
        W.props = J5.mergeEvaluated.props(Y, j, W.props, V6.Name);
      }
      if (W.items !== true) if (D && !D.dynamicItems) {
        if (D.items !== void 0) W.items = J5.mergeEvaluated.items(Y, D.items, W.items);
      } else {
        let j = Y.var("items", V6._`${w}.evaluated.items`);
        W.items = J5.mergeEvaluated.items(Y, j, W.items, V6.Name);
      }
    }
  }
  Eq.callRef = Y5;
  Eq.default = Mk;
});
var kq = k((Cq) => {
  Object.defineProperty(Cq, "__esModule", { value: true });
  var bk = bq(), Zk = vq(), Pk = ["$schema", "$id", "$defs", "$vocabulary", { keyword: "$comment" }, "definitions", bk.default, Zk.default];
  Cq.default = Pk;
});
var xq = k((_q) => {
  Object.defineProperty(_q, "__esModule", { value: true });
  var Q5 = a(), Q1 = Q5.operators, W5 = { maximum: { okStr: "<=", ok: Q1.LTE, fail: Q1.GT }, minimum: { okStr: ">=", ok: Q1.GTE, fail: Q1.LT }, exclusiveMaximum: { okStr: "<", ok: Q1.LT, fail: Q1.GTE }, exclusiveMinimum: { okStr: ">", ok: Q1.GT, fail: Q1.LTE } }, Ek = { message: ({ keyword: $, schemaCode: X }) => Q5.str`must be ${W5[$].okStr} ${X}`, params: ({ keyword: $, schemaCode: X }) => Q5._`{comparison: ${W5[$].okStr}, limit: ${X}}` }, Sk = { keyword: Object.keys(W5), type: "number", schemaType: "number", $data: true, error: Ek, code($) {
    let { keyword: X, data: J, schemaCode: Q } = $;
    $.fail$data(Q5._`${J} ${W5[X].fail} ${Q} || isNaN(${J})`);
  } };
  _q.default = Sk;
});
var yq = k((Tq) => {
  Object.defineProperty(Tq, "__esModule", { value: true });
  var t9 = a(), Ck = { message: ({ schemaCode: $ }) => t9.str`must be multiple of ${$}`, params: ({ schemaCode: $ }) => t9._`{multipleOf: ${$}}` }, kk = { keyword: "multipleOf", type: "number", schemaType: "number", $data: true, error: Ck, code($) {
    let { gen: X, data: J, schemaCode: Q, it: Y } = $, W = Y.opts.multipleOfPrecision, z8 = X.let("res"), G = W ? t9._`Math.abs(Math.round(${z8}) - ${z8}) > 1e-${W}` : t9._`${z8} !== parseInt(${z8})`;
    $.fail$data(t9._`(${Q} === 0 || (${z8} = ${J}/${Q}, ${G}))`);
  } };
  Tq.default = kk;
});
var hq = k((gq) => {
  Object.defineProperty(gq, "__esModule", { value: true });
  function fq($) {
    let X = $.length, J = 0, Q = 0, Y;
    while (Q < X) if (J++, Y = $.charCodeAt(Q++), Y >= 55296 && Y <= 56319 && Q < X) {
      if (Y = $.charCodeAt(Q), (Y & 64512) === 56320) Q++;
    }
    return J;
  }
  gq.default = fq;
  fq.code = 'require("ajv/dist/runtime/ucs2length").default';
});
var mq = k((uq) => {
  Object.defineProperty(uq, "__esModule", { value: true });
  var u1 = a(), Tk = Q$(), yk = hq(), fk = { message({ keyword: $, schemaCode: X }) {
    let J = $ === "maxLength" ? "more" : "fewer";
    return u1.str`must NOT have ${J} than ${X} characters`;
  }, params: ({ schemaCode: $ }) => u1._`{limit: ${$}}` }, gk = { keyword: ["maxLength", "minLength"], type: "string", schemaType: "number", $data: true, error: fk, code($) {
    let { keyword: X, data: J, schemaCode: Q, it: Y } = $, W = X === "maxLength" ? u1.operators.GT : u1.operators.LT, z8 = Y.opts.unicode === false ? u1._`${J}.length` : u1._`${(0, Tk.useFunc)($.gen, yk.default)}(${J})`;
    $.fail$data(u1._`${z8} ${W} ${Q}`);
  } };
  uq.default = gk;
});
var cq = k((lq) => {
  Object.defineProperty(lq, "__esModule", { value: true });
  var uk = E6(), mk = Q$(), J8 = a(), lk = { message: ({ schemaCode: $ }) => J8.str`must match pattern "${$}"`, params: ({ schemaCode: $ }) => J8._`{pattern: ${$}}` }, ck = { keyword: "pattern", type: "string", schemaType: "string", $data: true, error: lk, code($) {
    let { gen: X, data: J, $data: Q, schema: Y, schemaCode: W, it: z8 } = $, G = z8.opts.unicodeRegExp ? "u" : "";
    if (Q) {
      let { regExp: U } = z8.opts.code, H = U.code === "new RegExp" ? J8._`new RegExp` : (0, mk.useFunc)(X, U), K = X.let("valid");
      X.try(() => X.assign(K, J8._`${H}(${W}, ${G}).test(${J})`), () => X.assign(K, false)), $.fail$data(J8._`!${K}`);
    } else {
      let U = (0, uk.usePattern)($, Y);
      $.fail$data(J8._`!${U}.test(${J})`);
    }
  } };
  lq.default = ck;
});
var dq = k((pq) => {
  Object.defineProperty(pq, "__esModule", { value: true });
  var a9 = a(), dk = { message({ keyword: $, schemaCode: X }) {
    let J = $ === "maxProperties" ? "more" : "fewer";
    return a9.str`must NOT have ${J} than ${X} properties`;
  }, params: ({ schemaCode: $ }) => a9._`{limit: ${$}}` }, ik = { keyword: ["maxProperties", "minProperties"], type: "object", schemaType: "number", $data: true, error: dk, code($) {
    let { keyword: X, data: J, schemaCode: Q } = $, Y = X === "maxProperties" ? a9.operators.GT : a9.operators.LT;
    $.fail$data(a9._`Object.keys(${J}).length ${Y} ${Q}`);
  } };
  pq.default = ik;
});
var nq = k((iq) => {
  Object.defineProperty(iq, "__esModule", { value: true });
  var s9 = E6(), e9 = a(), rk = Q$(), ok = { message: ({ params: { missingProperty: $ } }) => e9.str`must have required property '${$}'`, params: ({ params: { missingProperty: $ } }) => e9._`{missingProperty: ${$}}` }, tk = { keyword: "required", type: "object", schemaType: "array", $data: true, error: ok, code($) {
    let { gen: X, schema: J, schemaCode: Q, data: Y, $data: W, it: z8 } = $, { opts: G } = z8;
    if (!W && J.length === 0) return;
    let U = J.length >= G.loopRequired;
    if (z8.allErrors) H();
    else K();
    if (G.strictRequired) {
      let O = $.parentSchema.properties, { definedProperties: w } = $.it;
      for (let B of J) if ((O === null || O === void 0 ? void 0 : O[B]) === void 0 && !w.has(B)) {
        let D = z8.schemaEnv.baseId + z8.errSchemaPath, j = `required property "${B}" is not defined at "${D}" (strictRequired)`;
        (0, rk.checkStrictMode)(z8, j, z8.opts.strictRequired);
      }
    }
    function H() {
      if (U || W) $.block$data(e9.nil, V);
      else for (let O of J) (0, s9.checkReportMissingProp)($, O);
    }
    function K() {
      let O = X.let("missing");
      if (U || W) {
        let w = X.let("valid", true);
        $.block$data(w, () => N(O, w)), $.ok(w);
      } else X.if((0, s9.checkMissingProp)($, J, O)), (0, s9.reportMissingProp)($, O), X.else();
    }
    function V() {
      X.forOf("prop", Q, (O) => {
        $.setParams({ missingProperty: O }), X.if((0, s9.noPropertyInData)(X, Y, O, G.ownProperties), () => $.error());
      });
    }
    function N(O, w) {
      $.setParams({ missingProperty: O }), X.forOf(O, Q, () => {
        X.assign(w, (0, s9.propertyInData)(X, Y, O, G.ownProperties)), X.if((0, e9.not)(w), () => {
          $.error(), X.break();
        });
      }, e9.nil);
    }
  } };
  iq.default = tk;
});
var oq = k((rq) => {
  Object.defineProperty(rq, "__esModule", { value: true });
  var $J = a(), sk = { message({ keyword: $, schemaCode: X }) {
    let J = $ === "maxItems" ? "more" : "fewer";
    return $J.str`must NOT have ${J} than ${X} items`;
  }, params: ({ schemaCode: $ }) => $J._`{limit: ${$}}` }, ek = { keyword: ["maxItems", "minItems"], type: "array", schemaType: "number", $data: true, error: sk, code($) {
    let { keyword: X, data: J, schemaCode: Q } = $, Y = X === "maxItems" ? $J.operators.GT : $J.operators.LT;
    $.fail$data($J._`${J}.length ${Y} ${Q}`);
  } };
  rq.default = ek;
});
var z5 = k((aq) => {
  Object.defineProperty(aq, "__esModule", { value: true });
  var tq = wU();
  tq.code = 'require("ajv/dist/runtime/equal").default';
  aq.default = tq;
});
var eq = k((sq) => {
  Object.defineProperty(sq, "__esModule", { value: true });
  var SU = u9(), m$ = a(), J_ = Q$(), Y_ = z5(), Q_ = { message: ({ params: { i: $, j: X } }) => m$.str`must NOT have duplicate items (items ## ${X} and ${$} are identical)`, params: ({ params: { i: $, j: X } }) => m$._`{i: ${$}, j: ${X}}` }, W_ = { keyword: "uniqueItems", type: "array", schemaType: "boolean", $data: true, error: Q_, code($) {
    let { gen: X, data: J, $data: Q, schema: Y, parentSchema: W, schemaCode: z8, it: G } = $;
    if (!Q && !Y) return;
    let U = X.let("valid"), H = W.items ? (0, SU.getSchemaTypes)(W.items) : [];
    $.block$data(U, K, m$._`${z8} === false`), $.ok(U);
    function K() {
      let w = X.let("i", m$._`${J}.length`), B = X.let("j");
      $.setParams({ i: w, j: B }), X.assign(U, true), X.if(m$._`${w} > 1`, () => (V() ? N : O)(w, B));
    }
    function V() {
      return H.length > 0 && !H.some((w) => w === "object" || w === "array");
    }
    function N(w, B) {
      let D = X.name("item"), j = (0, SU.checkDataTypes)(H, D, G.opts.strictNumbers, SU.DataType.Wrong), A = X.const("indices", m$._`{}`);
      X.for(m$._`;${w}--;`, () => {
        if (X.let(D, m$._`${J}[${w}]`), X.if(j, m$._`continue`), H.length > 1) X.if(m$._`typeof ${D} == "string"`, m$._`${D} += "_"`);
        X.if(m$._`typeof ${A}[${D}] == "number"`, () => {
          X.assign(B, m$._`${A}[${D}]`), $.error(), X.assign(U, false).break();
        }).code(m$._`${A}[${D}] = ${w}`);
      });
    }
    function O(w, B) {
      let D = (0, J_.useFunc)(X, Y_.default), j = X.name("outer");
      X.label(j).for(m$._`;${w}--;`, () => X.for(m$._`${B} = ${w}; ${B}--;`, () => X.if(m$._`${D}(${J}[${w}], ${J}[${B}])`, () => {
        $.error(), X.assign(U, false).break(j);
      })));
    }
  } };
  sq.default = W_;
});
var XL = k(($L) => {
  Object.defineProperty($L, "__esModule", { value: true });
  var vU = a(), G_ = Q$(), U_ = z5(), H_ = { message: "must be equal to constant", params: ({ schemaCode: $ }) => vU._`{allowedValue: ${$}}` }, K_ = { keyword: "const", $data: true, error: H_, code($) {
    let { gen: X, data: J, $data: Q, schemaCode: Y, schema: W } = $;
    if (Q || W && typeof W == "object") $.fail$data(vU._`!${(0, G_.useFunc)(X, U_.default)}(${J}, ${Y})`);
    else $.fail(vU._`${W} !== ${J}`);
  } };
  $L.default = K_;
});
var YL = k((JL) => {
  Object.defineProperty(JL, "__esModule", { value: true });
  var XJ = a(), N_ = Q$(), O_ = z5(), w_ = { message: "must be equal to one of the allowed values", params: ({ schemaCode: $ }) => XJ._`{allowedValues: ${$}}` }, B_ = { keyword: "enum", schemaType: "array", $data: true, error: w_, code($) {
    let { gen: X, data: J, $data: Q, schema: Y, schemaCode: W, it: z8 } = $;
    if (!Q && Y.length === 0) throw Error("enum must have non-empty array");
    let G = Y.length >= z8.opts.loopEnum, U, H = () => U !== null && U !== void 0 ? U : U = (0, N_.useFunc)(X, O_.default), K;
    if (G || Q) K = X.let("valid"), $.block$data(K, V);
    else {
      if (!Array.isArray(Y)) throw Error("ajv implementation error");
      let O = X.const("vSchema", W);
      K = (0, XJ.or)(...Y.map((w, B) => N(O, B)));
    }
    $.pass(K);
    function V() {
      X.assign(K, false), X.forOf("v", W, (O) => X.if(XJ._`${H()}(${J}, ${O})`, () => X.assign(K, true).break()));
    }
    function N(O, w) {
      let B = Y[w];
      return typeof B === "object" && B !== null ? XJ._`${H()}(${J}, ${O}[${w}])` : XJ._`${J} === ${B}`;
    }
  } };
  JL.default = B_;
});
var WL = k((QL) => {
  Object.defineProperty(QL, "__esModule", { value: true });
  var L_ = xq(), D_ = yq(), j_ = mq(), F_ = cq(), M_ = dq(), A_ = nq(), I_ = oq(), b_ = eq(), Z_ = XL(), P_ = YL(), R_ = [L_.default, D_.default, j_.default, F_.default, M_.default, A_.default, I_.default, b_.default, { keyword: "type", schemaType: ["string", "array"] }, { keyword: "nullable", schemaType: "boolean" }, Z_.default, P_.default];
  QL.default = R_;
});
var kU = k((GL) => {
  Object.defineProperty(GL, "__esModule", { value: true });
  GL.validateAdditionalItems = void 0;
  var m1 = a(), CU = Q$(), S_ = { message: ({ params: { len: $ } }) => m1.str`must NOT have more than ${$} items`, params: ({ params: { len: $ } }) => m1._`{limit: ${$}}` }, v_ = { keyword: "additionalItems", type: "array", schemaType: ["boolean", "object"], before: "uniqueItems", error: S_, code($) {
    let { parentSchema: X, it: J } = $, { items: Q } = X;
    if (!Array.isArray(Q)) {
      (0, CU.checkStrictMode)(J, '"additionalItems" is ignored when "items" is not an array of schemas');
      return;
    }
    zL($, Q);
  } };
  function zL($, X) {
    let { gen: J, schema: Q, data: Y, keyword: W, it: z8 } = $;
    z8.items = true;
    let G = J.const("len", m1._`${Y}.length`);
    if (Q === false) $.setParams({ len: X.length }), $.pass(m1._`${G} <= ${X.length}`);
    else if (typeof Q == "object" && !(0, CU.alwaysValidSchema)(z8, Q)) {
      let H = J.var("valid", m1._`${G} <= ${X.length}`);
      J.if((0, m1.not)(H), () => U(H)), $.ok(H);
    }
    function U(H) {
      J.forRange("i", X.length, G, (K) => {
        if ($.subschema({ keyword: W, dataProp: K, dataPropType: CU.Type.Num }, H), !z8.allErrors) J.if((0, m1.not)(H), () => J.break());
      });
    }
  }
  GL.validateAdditionalItems = zL;
  GL.default = v_;
});
var _U = k((VL) => {
  Object.defineProperty(VL, "__esModule", { value: true });
  VL.validateTuple = void 0;
  var HL = a(), G5 = Q$(), k_ = E6(), __ = { keyword: "items", type: "array", schemaType: ["object", "array", "boolean"], before: "uniqueItems", code($) {
    let { schema: X, it: J } = $;
    if (Array.isArray(X)) return KL($, "additionalItems", X);
    if (J.items = true, (0, G5.alwaysValidSchema)(J, X)) return;
    $.ok((0, k_.validateArray)($));
  } };
  function KL($, X, J = $.schema) {
    let { gen: Q, parentSchema: Y, data: W, keyword: z8, it: G } = $;
    if (K(Y), G.opts.unevaluated && J.length && G.items !== true) G.items = G5.mergeEvaluated.items(Q, J.length, G.items);
    let U = Q.name("valid"), H = Q.const("len", HL._`${W}.length`);
    J.forEach((V, N) => {
      if ((0, G5.alwaysValidSchema)(G, V)) return;
      Q.if(HL._`${H} > ${N}`, () => $.subschema({ keyword: z8, schemaProp: N, dataProp: N }, U)), $.ok(U);
    });
    function K(V) {
      let { opts: N, errSchemaPath: O } = G, w = J.length, B = w === V.minItems && (w === V.maxItems || V[X] === false);
      if (N.strictTuples && !B) {
        let D = `"${z8}" is ${w}-tuple, but minItems or maxItems/${X} are not specified or different at path "${O}"`;
        (0, G5.checkStrictMode)(G, D, N.strictTuples);
      }
    }
  }
  VL.validateTuple = KL;
  VL.default = __;
});
var wL = k((OL) => {
  Object.defineProperty(OL, "__esModule", { value: true });
  var T_ = _U(), y_ = { keyword: "prefixItems", type: "array", schemaType: ["array"], before: "uniqueItems", code: ($) => (0, T_.validateTuple)($, "items") };
  OL.default = y_;
});
var LL = k((qL) => {
  Object.defineProperty(qL, "__esModule", { value: true });
  var BL = a(), g_ = Q$(), h_ = E6(), u_ = kU(), m_ = { message: ({ params: { len: $ } }) => BL.str`must NOT have more than ${$} items`, params: ({ params: { len: $ } }) => BL._`{limit: ${$}}` }, l_ = { keyword: "items", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", error: m_, code($) {
    let { schema: X, parentSchema: J, it: Q } = $, { prefixItems: Y } = J;
    if (Q.items = true, (0, g_.alwaysValidSchema)(Q, X)) return;
    if (Y) (0, u_.validateAdditionalItems)($, Y);
    else $.ok((0, h_.validateArray)($));
  } };
  qL.default = l_;
});
var jL = k((DL) => {
  Object.defineProperty(DL, "__esModule", { value: true });
  var S6 = a(), U5 = Q$(), p_ = { message: ({ params: { min: $, max: X } }) => X === void 0 ? S6.str`must contain at least ${$} valid item(s)` : S6.str`must contain at least ${$} and no more than ${X} valid item(s)`, params: ({ params: { min: $, max: X } }) => X === void 0 ? S6._`{minContains: ${$}}` : S6._`{minContains: ${$}, maxContains: ${X}}` }, d_ = { keyword: "contains", type: "array", schemaType: ["object", "boolean"], before: "uniqueItems", trackErrors: true, error: p_, code($) {
    let { gen: X, schema: J, parentSchema: Q, data: Y, it: W } = $, z8, G, { minContains: U, maxContains: H } = Q;
    if (W.opts.next) z8 = U === void 0 ? 1 : U, G = H;
    else z8 = 1;
    let K = X.const("len", S6._`${Y}.length`);
    if ($.setParams({ min: z8, max: G }), G === void 0 && z8 === 0) {
      (0, U5.checkStrictMode)(W, '"minContains" == 0 without "maxContains": "contains" keyword ignored');
      return;
    }
    if (G !== void 0 && z8 > G) {
      (0, U5.checkStrictMode)(W, '"minContains" > "maxContains" is always invalid'), $.fail();
      return;
    }
    if ((0, U5.alwaysValidSchema)(W, J)) {
      let B = S6._`${K} >= ${z8}`;
      if (G !== void 0) B = S6._`${B} && ${K} <= ${G}`;
      $.pass(B);
      return;
    }
    W.items = true;
    let V = X.name("valid");
    if (G === void 0 && z8 === 1) O(V, () => X.if(V, () => X.break()));
    else if (z8 === 0) {
      if (X.let(V, true), G !== void 0) X.if(S6._`${Y}.length > 0`, N);
    } else X.let(V, false), N();
    $.result(V, () => $.reset());
    function N() {
      let B = X.name("_valid"), D = X.let("count", 0);
      O(B, () => X.if(B, () => w(D)));
    }
    function O(B, D) {
      X.forRange("i", 0, K, (j) => {
        $.subschema({ keyword: "contains", dataProp: j, dataPropType: U5.Type.Num, compositeRule: true }, B), D();
      });
    }
    function w(B) {
      if (X.code(S6._`${B}++`), G === void 0) X.if(S6._`${B} >= ${z8}`, () => X.assign(V, true).break());
      else if (X.if(S6._`${B} > ${G}`, () => X.assign(V, false).break()), z8 === 1) X.assign(V, true);
      else X.if(S6._`${B} >= ${z8}`, () => X.assign(V, true));
    }
  } };
  DL.default = d_;
});
var ZL = k((AL) => {
  Object.defineProperty(AL, "__esModule", { value: true });
  AL.validateSchemaDeps = AL.validatePropertyDeps = AL.error = void 0;
  var xU = a(), n_ = Q$(), JJ = E6();
  AL.error = { message: ({ params: { property: $, depsCount: X, deps: J } }) => {
    let Q = X === 1 ? "property" : "properties";
    return xU.str`must have ${Q} ${J} when property ${$} is present`;
  }, params: ({ params: { property: $, depsCount: X, deps: J, missingProperty: Q } }) => xU._`{property: ${$},
    missingProperty: ${Q},
    depsCount: ${X},
    deps: ${J}}` };
  var r_ = { keyword: "dependencies", type: "object", schemaType: "object", error: AL.error, code($) {
    let [X, J] = o_($);
    FL($, X), ML($, J);
  } };
  function o_({ schema: $ }) {
    let X = {}, J = {};
    for (let Q in $) {
      if (Q === "__proto__") continue;
      let Y = Array.isArray($[Q]) ? X : J;
      Y[Q] = $[Q];
    }
    return [X, J];
  }
  function FL($, X = $.schema) {
    let { gen: J, data: Q, it: Y } = $;
    if (Object.keys(X).length === 0) return;
    let W = J.let("missing");
    for (let z8 in X) {
      let G = X[z8];
      if (G.length === 0) continue;
      let U = (0, JJ.propertyInData)(J, Q, z8, Y.opts.ownProperties);
      if ($.setParams({ property: z8, depsCount: G.length, deps: G.join(", ") }), Y.allErrors) J.if(U, () => {
        for (let H of G) (0, JJ.checkReportMissingProp)($, H);
      });
      else J.if(xU._`${U} && (${(0, JJ.checkMissingProp)($, G, W)})`), (0, JJ.reportMissingProp)($, W), J.else();
    }
  }
  AL.validatePropertyDeps = FL;
  function ML($, X = $.schema) {
    let { gen: J, data: Q, keyword: Y, it: W } = $, z8 = J.name("valid");
    for (let G in X) {
      if ((0, n_.alwaysValidSchema)(W, X[G])) continue;
      J.if((0, JJ.propertyInData)(J, Q, G, W.opts.ownProperties), () => {
        let U = $.subschema({ keyword: Y, schemaProp: G }, z8);
        $.mergeValidEvaluated(U, z8);
      }, () => J.var(z8, true)), $.ok(z8);
    }
  }
  AL.validateSchemaDeps = ML;
  AL.default = r_;
});
var EL = k((RL) => {
  Object.defineProperty(RL, "__esModule", { value: true });
  var PL = a(), s_ = Q$(), e_ = { message: "property name must be valid", params: ({ params: $ }) => PL._`{propertyName: ${$.propertyName}}` }, $x = { keyword: "propertyNames", type: "object", schemaType: ["object", "boolean"], error: e_, code($) {
    let { gen: X, schema: J, data: Q, it: Y } = $;
    if ((0, s_.alwaysValidSchema)(Y, J)) return;
    let W = X.name("valid");
    X.forIn("key", Q, (z8) => {
      $.setParams({ propertyName: z8 }), $.subschema({ keyword: "propertyNames", data: z8, dataTypes: ["string"], propertyName: z8, compositeRule: true }, W), X.if((0, PL.not)(W), () => {
        if ($.error(true), !Y.allErrors) X.break();
      });
    }), $.ok(W);
  } };
  RL.default = $x;
});
var TU = k((SL) => {
  Object.defineProperty(SL, "__esModule", { value: true });
  var H5 = E6(), p6 = a(), Jx = b4(), K5 = Q$(), Yx = { message: "must NOT have additional properties", params: ({ params: $ }) => p6._`{additionalProperty: ${$.additionalProperty}}` }, Qx = { keyword: "additionalProperties", type: ["object"], schemaType: ["boolean", "object"], allowUndefined: true, trackErrors: true, error: Yx, code($) {
    let { gen: X, schema: J, parentSchema: Q, data: Y, errsCount: W, it: z8 } = $;
    if (!W) throw Error("ajv implementation error");
    let { allErrors: G, opts: U } = z8;
    if (z8.props = true, U.removeAdditional !== "all" && (0, K5.alwaysValidSchema)(z8, J)) return;
    let H = (0, H5.allSchemaProperties)(Q.properties), K = (0, H5.allSchemaProperties)(Q.patternProperties);
    V(), $.ok(p6._`${W} === ${Jx.default.errors}`);
    function V() {
      X.forIn("key", Y, (D) => {
        if (!H.length && !K.length) w(D);
        else X.if(N(D), () => w(D));
      });
    }
    function N(D) {
      let j;
      if (H.length > 8) {
        let A = (0, K5.schemaRefOrVal)(z8, Q.properties, "properties");
        j = (0, H5.isOwnProperty)(X, A, D);
      } else if (H.length) j = (0, p6.or)(...H.map((A) => p6._`${D} === ${A}`));
      else j = p6.nil;
      if (K.length) j = (0, p6.or)(j, ...K.map((A) => p6._`${(0, H5.usePattern)($, A)}.test(${D})`));
      return (0, p6.not)(j);
    }
    function O(D) {
      X.code(p6._`delete ${Y}[${D}]`);
    }
    function w(D) {
      if (U.removeAdditional === "all" || U.removeAdditional && J === false) {
        O(D);
        return;
      }
      if (J === false) {
        if ($.setParams({ additionalProperty: D }), $.error(), !G) X.break();
        return;
      }
      if (typeof J == "object" && !(0, K5.alwaysValidSchema)(z8, J)) {
        let j = X.name("valid");
        if (U.removeAdditional === "failing") B(D, j, false), X.if((0, p6.not)(j), () => {
          $.reset(), O(D);
        });
        else if (B(D, j), !G) X.if((0, p6.not)(j), () => X.break());
      }
    }
    function B(D, j, A) {
      let I = { keyword: "additionalProperties", dataProp: D, dataPropType: K5.Type.Str };
      if (A === false) Object.assign(I, { compositeRule: true, createErrors: false, allErrors: false });
      $.subschema(I, j);
    }
  } };
  SL.default = Qx;
});
var _L = k((kL) => {
  Object.defineProperty(kL, "__esModule", { value: true });
  var zx = p9(), vL = E6(), yU = Q$(), CL = TU(), Gx = { keyword: "properties", type: "object", schemaType: "object", code($) {
    let { gen: X, schema: J, parentSchema: Q, data: Y, it: W } = $;
    if (W.opts.removeAdditional === "all" && Q.additionalProperties === void 0) CL.default.code(new zx.KeywordCxt(W, CL.default, "additionalProperties"));
    let z8 = (0, vL.allSchemaProperties)(J);
    for (let V of z8) W.definedProperties.add(V);
    if (W.opts.unevaluated && z8.length && W.props !== true) W.props = yU.mergeEvaluated.props(X, (0, yU.toHash)(z8), W.props);
    let G = z8.filter((V) => !(0, yU.alwaysValidSchema)(W, J[V]));
    if (G.length === 0) return;
    let U = X.name("valid");
    for (let V of G) {
      if (H(V)) K(V);
      else {
        if (X.if((0, vL.propertyInData)(X, Y, V, W.opts.ownProperties)), K(V), !W.allErrors) X.else().var(U, true);
        X.endIf();
      }
      $.it.definedProperties.add(V), $.ok(U);
    }
    function H(V) {
      return W.opts.useDefaults && !W.compositeRule && J[V].default !== void 0;
    }
    function K(V) {
      $.subschema({ keyword: "properties", schemaProp: V, dataProp: V }, U);
    }
  } };
  kL.default = Gx;
});
var gL = k((fL) => {
  Object.defineProperty(fL, "__esModule", { value: true });
  var xL = E6(), V5 = a(), TL = Q$(), yL = Q$(), Hx = { keyword: "patternProperties", type: "object", schemaType: "object", code($) {
    let { gen: X, schema: J, data: Q, parentSchema: Y, it: W } = $, { opts: z8 } = W, G = (0, xL.allSchemaProperties)(J), U = G.filter((B) => (0, TL.alwaysValidSchema)(W, J[B]));
    if (G.length === 0 || U.length === G.length && (!W.opts.unevaluated || W.props === true)) return;
    let H = z8.strictSchema && !z8.allowMatchingProperties && Y.properties, K = X.name("valid");
    if (W.props !== true && !(W.props instanceof V5.Name)) W.props = (0, yL.evaluatedPropsToName)(X, W.props);
    let { props: V } = W;
    N();
    function N() {
      for (let B of G) {
        if (H) O(B);
        if (W.allErrors) w(B);
        else X.var(K, true), w(B), X.if(K);
      }
    }
    function O(B) {
      for (let D in H) if (new RegExp(B).test(D)) (0, TL.checkStrictMode)(W, `property ${D} matches pattern ${B} (use allowMatchingProperties)`);
    }
    function w(B) {
      X.forIn("key", Q, (D) => {
        X.if(V5._`${(0, xL.usePattern)($, B)}.test(${D})`, () => {
          let j = U.includes(B);
          if (!j) $.subschema({ keyword: "patternProperties", schemaProp: B, dataProp: D, dataPropType: yL.Type.Str }, K);
          if (W.opts.unevaluated && V !== true) X.assign(V5._`${V}[${D}]`, true);
          else if (!j && !W.allErrors) X.if((0, V5.not)(K), () => X.break());
        });
      });
    }
  } };
  fL.default = Hx;
});
var uL = k((hL) => {
  Object.defineProperty(hL, "__esModule", { value: true });
  var Vx = Q$(), Nx = { keyword: "not", schemaType: ["object", "boolean"], trackErrors: true, code($) {
    let { gen: X, schema: J, it: Q } = $;
    if ((0, Vx.alwaysValidSchema)(Q, J)) {
      $.fail();
      return;
    }
    let Y = X.name("valid");
    $.subschema({ keyword: "not", compositeRule: true, createErrors: false, allErrors: false }, Y), $.failResult(Y, () => $.reset(), () => $.error());
  }, error: { message: "must NOT be valid" } };
  hL.default = Nx;
});
var lL = k((mL) => {
  Object.defineProperty(mL, "__esModule", { value: true });
  var wx = E6(), Bx = { keyword: "anyOf", schemaType: "array", trackErrors: true, code: wx.validateUnion, error: { message: "must match a schema in anyOf" } };
  mL.default = Bx;
});
var pL = k((cL) => {
  Object.defineProperty(cL, "__esModule", { value: true });
  var N5 = a(), Lx = Q$(), Dx = { message: "must match exactly one schema in oneOf", params: ({ params: $ }) => N5._`{passingSchemas: ${$.passing}}` }, jx = { keyword: "oneOf", schemaType: "array", trackErrors: true, error: Dx, code($) {
    let { gen: X, schema: J, parentSchema: Q, it: Y } = $;
    if (!Array.isArray(J)) throw Error("ajv implementation error");
    if (Y.opts.discriminator && Q.discriminator) return;
    let W = J, z8 = X.let("valid", false), G = X.let("passing", null), U = X.name("_valid");
    $.setParams({ passing: G }), X.block(H), $.result(z8, () => $.reset(), () => $.error(true));
    function H() {
      W.forEach((K, V) => {
        let N;
        if ((0, Lx.alwaysValidSchema)(Y, K)) X.var(U, true);
        else N = $.subschema({ keyword: "oneOf", schemaProp: V, compositeRule: true }, U);
        if (V > 0) X.if(N5._`${U} && ${z8}`).assign(z8, false).assign(G, N5._`[${G}, ${V}]`).else();
        X.if(U, () => {
          if (X.assign(z8, true), X.assign(G, V), N) $.mergeEvaluated(N, N5.Name);
        });
      });
    }
  } };
  cL.default = jx;
});
var iL = k((dL) => {
  Object.defineProperty(dL, "__esModule", { value: true });
  var Mx = Q$(), Ax = { keyword: "allOf", schemaType: "array", code($) {
    let { gen: X, schema: J, it: Q } = $;
    if (!Array.isArray(J)) throw Error("ajv implementation error");
    let Y = X.name("valid");
    J.forEach((W, z8) => {
      if ((0, Mx.alwaysValidSchema)(Q, W)) return;
      let G = $.subschema({ keyword: "allOf", schemaProp: z8 }, Y);
      $.ok(Y), $.mergeEvaluated(G);
    });
  } };
  dL.default = Ax;
});
var tL = k((oL) => {
  Object.defineProperty(oL, "__esModule", { value: true });
  var O5 = a(), rL = Q$(), bx = { message: ({ params: $ }) => O5.str`must match "${$.ifClause}" schema`, params: ({ params: $ }) => O5._`{failingKeyword: ${$.ifClause}}` }, Zx = { keyword: "if", schemaType: ["object", "boolean"], trackErrors: true, error: bx, code($) {
    let { gen: X, parentSchema: J, it: Q } = $;
    if (J.then === void 0 && J.else === void 0) (0, rL.checkStrictMode)(Q, '"if" without "then" and "else" is ignored');
    let Y = nL(Q, "then"), W = nL(Q, "else");
    if (!Y && !W) return;
    let z8 = X.let("valid", true), G = X.name("_valid");
    if (U(), $.reset(), Y && W) {
      let K = X.let("ifClause");
      $.setParams({ ifClause: K }), X.if(G, H("then", K), H("else", K));
    } else if (Y) X.if(G, H("then"));
    else X.if((0, O5.not)(G), H("else"));
    $.pass(z8, () => $.error(true));
    function U() {
      let K = $.subschema({ keyword: "if", compositeRule: true, createErrors: false, allErrors: false }, G);
      $.mergeEvaluated(K);
    }
    function H(K, V) {
      return () => {
        let N = $.subschema({ keyword: K }, G);
        if (X.assign(z8, G), $.mergeValidEvaluated(N, z8), V) X.assign(V, O5._`${K}`);
        else $.setParams({ ifClause: K });
      };
    }
  } };
  function nL($, X) {
    let J = $.schema[X];
    return J !== void 0 && !(0, rL.alwaysValidSchema)($, J);
  }
  oL.default = Zx;
});
var sL = k((aL) => {
  Object.defineProperty(aL, "__esModule", { value: true });
  var Rx = Q$(), Ex = { keyword: ["then", "else"], schemaType: ["object", "boolean"], code({ keyword: $, parentSchema: X, it: J }) {
    if (X.if === void 0) (0, Rx.checkStrictMode)(J, `"${$}" without "if" is ignored`);
  } };
  aL.default = Ex;
});
var $D = k((eL) => {
  Object.defineProperty(eL, "__esModule", { value: true });
  var vx = kU(), Cx = wL(), kx = _U(), _x = LL(), xx = jL(), Tx = ZL(), yx = EL(), fx = TU(), gx = _L(), hx = gL(), ux = uL(), mx = lL(), lx = pL(), cx = iL(), px = tL(), dx = sL();
  function ix($ = false) {
    let X = [ux.default, mx.default, lx.default, cx.default, px.default, dx.default, yx.default, fx.default, Tx.default, gx.default, hx.default];
    if ($) X.push(Cx.default, _x.default);
    else X.push(vx.default, kx.default);
    return X.push(xx.default), X;
  }
  eL.default = ix;
});
var JD = k((XD) => {
  Object.defineProperty(XD, "__esModule", { value: true });
  var S$ = a(), rx = { message: ({ schemaCode: $ }) => S$.str`must match format "${$}"`, params: ({ schemaCode: $ }) => S$._`{format: ${$}}` }, ox = { keyword: "format", type: ["number", "string"], schemaType: "string", $data: true, error: rx, code($, X) {
    let { gen: J, data: Q, $data: Y, schema: W, schemaCode: z8, it: G } = $, { opts: U, errSchemaPath: H, schemaEnv: K, self: V } = G;
    if (!U.validateFormats) return;
    if (Y) N();
    else O();
    function N() {
      let w = J.scopeValue("formats", { ref: V.formats, code: U.code.formats }), B = J.const("fDef", S$._`${w}[${z8}]`), D = J.let("fType"), j = J.let("format");
      J.if(S$._`typeof ${B} == "object" && !(${B} instanceof RegExp)`, () => J.assign(D, S$._`${B}.type || "string"`).assign(j, S$._`${B}.validate`), () => J.assign(D, S$._`"string"`).assign(j, B)), $.fail$data((0, S$.or)(A(), I()));
      function A() {
        if (U.strictSchema === false) return S$.nil;
        return S$._`${z8} && !${j}`;
      }
      function I() {
        let x = K.$async ? S$._`(${B}.async ? await ${j}(${Q}) : ${j}(${Q}))` : S$._`${j}(${Q})`, T = S$._`(typeof ${j} == "function" ? ${x} : ${j}.test(${Q}))`;
        return S$._`${j} && ${j} !== true && ${D} === ${X} && !${T}`;
      }
    }
    function O() {
      let w = V.formats[W];
      if (!w) {
        A();
        return;
      }
      if (w === true) return;
      let [B, D, j] = I(w);
      if (B === X) $.pass(x());
      function A() {
        if (U.strictSchema === false) {
          V.logger.warn(T());
          return;
        }
        throw Error(T());
        function T() {
          return `unknown format "${W}" ignored in schema at path "${H}"`;
        }
      }
      function I(T) {
        let U$ = T instanceof RegExp ? (0, S$.regexpCode)(T) : U.code.formats ? S$._`${U.code.formats}${(0, S$.getProperty)(W)}` : void 0, T$ = J.scopeValue("formats", { key: W, ref: T, code: U$ });
        if (typeof T == "object" && !(T instanceof RegExp)) return [T.type || "string", T.validate, S$._`${T$}.validate`];
        return ["string", T, T$];
      }
      function x() {
        if (typeof w == "object" && !(w instanceof RegExp) && w.async) {
          if (!K.$async) throw Error("async format in sync schema");
          return S$._`await ${j}(${Q})`;
        }
        return typeof D == "function" ? S$._`${j}(${Q})` : S$._`${j}.test(${Q})`;
      }
    }
  } };
  XD.default = ox;
});
var QD = k((YD) => {
  Object.defineProperty(YD, "__esModule", { value: true });
  var ax = JD(), sx = [ax.default];
  YD.default = sx;
});
var GD = k((WD) => {
  Object.defineProperty(WD, "__esModule", { value: true });
  WD.contentVocabulary = WD.metadataVocabulary = void 0;
  WD.metadataVocabulary = ["title", "description", "default", "deprecated", "readOnly", "writeOnly", "examples"];
  WD.contentVocabulary = ["contentMediaType", "contentEncoding", "contentSchema"];
});
var KD = k((HD) => {
  Object.defineProperty(HD, "__esModule", { value: true });
  var XT = kq(), JT = WL(), YT = $D(), QT = QD(), UD = GD(), WT = [XT.default, JT.default, (0, YT.default)(), QT.default, UD.metadataVocabulary, UD.contentVocabulary];
  HD.default = WT;
});
var wD = k((ND) => {
  Object.defineProperty(ND, "__esModule", { value: true });
  ND.DiscrError = void 0;
  var VD;
  (function($) {
    $.Tag = "tag", $.Mapping = "mapping";
  })(VD || (ND.DiscrError = VD = {}));
});
var LD = k((qD) => {
  Object.defineProperty(qD, "__esModule", { value: true });
  var Y8 = a(), fU = wD(), BD = tQ(), GT = d9(), UT = Q$(), HT = { message: ({ params: { discrError: $, tagName: X } }) => $ === fU.DiscrError.Tag ? `tag "${X}" must be string` : `value of tag "${X}" must be in oneOf`, params: ({ params: { discrError: $, tag: X, tagName: J } }) => Y8._`{error: ${$}, tag: ${J}, tagValue: ${X}}` }, KT = { keyword: "discriminator", type: "object", schemaType: "object", error: HT, code($) {
    let { gen: X, data: J, schema: Q, parentSchema: Y, it: W } = $, { oneOf: z8 } = Y;
    if (!W.opts.discriminator) throw Error("discriminator: requires discriminator option");
    let G = Q.propertyName;
    if (typeof G != "string") throw Error("discriminator: requires propertyName");
    if (Q.mapping) throw Error("discriminator: mapping is not supported");
    if (!z8) throw Error("discriminator: requires oneOf keyword");
    let U = X.let("valid", false), H = X.const("tag", Y8._`${J}${(0, Y8.getProperty)(G)}`);
    X.if(Y8._`typeof ${H} == "string"`, () => K(), () => $.error(false, { discrError: fU.DiscrError.Tag, tag: H, tagName: G })), $.ok(U);
    function K() {
      let O = N();
      X.if(false);
      for (let w in O) X.elseIf(Y8._`${H} === ${w}`), X.assign(U, V(O[w]));
      X.else(), $.error(false, { discrError: fU.DiscrError.Mapping, tag: H, tagName: G }), X.endIf();
    }
    function V(O) {
      let w = X.name("valid"), B = $.subschema({ keyword: "oneOf", schemaProp: O }, w);
      return $.mergeEvaluated(B, Y8.Name), w;
    }
    function N() {
      var O;
      let w = {}, B = j(Y), D = true;
      for (let x = 0; x < z8.length; x++) {
        let T = z8[x];
        if ((T === null || T === void 0 ? void 0 : T.$ref) && !(0, UT.schemaHasRulesButRef)(T, W.self.RULES)) {
          let T$ = T.$ref;
          if (T = BD.resolveRef.call(W.self, W.schemaEnv.root, W.baseId, T$), T instanceof BD.SchemaEnv) T = T.schema;
          if (T === void 0) throw new GT.default(W.opts.uriResolver, W.baseId, T$);
        }
        let U$ = (O = T === null || T === void 0 ? void 0 : T.properties) === null || O === void 0 ? void 0 : O[G];
        if (typeof U$ != "object") throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${G}"`);
        D = D && (B || j(T)), A(U$, x);
      }
      if (!D) throw Error(`discriminator: "${G}" must be required`);
      return w;
      function j({ required: x }) {
        return Array.isArray(x) && x.includes(G);
      }
      function A(x, T) {
        if (x.const) I(x.const, T);
        else if (x.enum) for (let U$ of x.enum) I(U$, T);
        else throw Error(`discriminator: "properties/${G}" must have "const" or "enum"`);
      }
      function I(x, T) {
        if (typeof x != "string" || x in w) throw Error(`discriminator: "${G}" values must be unique strings`);
        w[x] = T;
      }
    }
  } };
  qD.default = KT;
});
var DD = k((We, NT) => {
  NT.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: true, 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: true, readOnly: { type: "boolean", default: false }, examples: { type: "array", items: true }, 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: true }, maxItems: { $ref: "#/definitions/nonNegativeInteger" }, minItems: { $ref: "#/definitions/nonNegativeIntegerDefault0" }, uniqueItems: { type: "boolean", default: false }, 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: true, enum: { type: "array", items: true, minItems: 1, uniqueItems: true }, type: { anyOf: [{ $ref: "#/definitions/simpleTypes" }, { type: "array", items: { $ref: "#/definitions/simpleTypes" }, minItems: 1, uniqueItems: true }] }, 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: true };
});
var hU = k((N6, gU) => {
  Object.defineProperty(N6, "__esModule", { value: true });
  N6.MissingRefError = N6.ValidationError = N6.CodeGen = N6.Name = N6.nil = N6.stringify = N6.str = N6._ = N6.KeywordCxt = N6.Ajv = void 0;
  var OT = Aq(), wT = KD(), BT = LD(), jD = DD(), qT = ["/properties"], w5 = "http://json-schema.org/draft-07/schema";
  class YJ extends OT.default {
    _addVocabularies() {
      if (super._addVocabularies(), wT.default.forEach(($) => this.addVocabulary($)), this.opts.discriminator) this.addKeyword(BT.default);
    }
    _addDefaultMetaSchema() {
      if (super._addDefaultMetaSchema(), !this.opts.meta) return;
      let $ = this.opts.$data ? this.$dataMetaSchema(jD, qT) : jD;
      this.addMetaSchema($, w5, false), this.refs["http://json-schema.org/schema"] = w5;
    }
    defaultMeta() {
      return this.opts.defaultMeta = super.defaultMeta() || (this.getSchema(w5) ? w5 : void 0);
    }
  }
  N6.Ajv = YJ;
  gU.exports = N6 = YJ;
  gU.exports.Ajv = YJ;
  Object.defineProperty(N6, "__esModule", { value: true });
  N6.default = YJ;
  var LT = p9();
  Object.defineProperty(N6, "KeywordCxt", { enumerable: true, get: function() {
    return LT.KeywordCxt;
  } });
  var Q8 = a();
  Object.defineProperty(N6, "_", { enumerable: true, get: function() {
    return Q8._;
  } });
  Object.defineProperty(N6, "str", { enumerable: true, get: function() {
    return Q8.str;
  } });
  Object.defineProperty(N6, "stringify", { enumerable: true, get: function() {
    return Q8.stringify;
  } });
  Object.defineProperty(N6, "nil", { enumerable: true, get: function() {
    return Q8.nil;
  } });
  Object.defineProperty(N6, "Name", { enumerable: true, get: function() {
    return Q8.Name;
  } });
  Object.defineProperty(N6, "CodeGen", { enumerable: true, get: function() {
    return Q8.CodeGen;
  } });
  var DT = rQ();
  Object.defineProperty(N6, "ValidationError", { enumerable: true, get: function() {
    return DT.default;
  } });
  var jT = d9();
  Object.defineProperty(N6, "MissingRefError", { enumerable: true, get: function() {
    return jT.default;
  } });
});
var SD = k((RD) => {
  Object.defineProperty(RD, "__esModule", { value: true });
  RD.formatNames = RD.fastFormats = RD.fullFormats = void 0;
  function e6($, X) {
    return { validate: $, compare: X };
  }
  RD.fullFormats = { date: e6(ID, cU), time: e6(mU(true), pU), "date-time": e6(FD(true), ZD), "iso-time": e6(mU(), bD), "iso-date-time": e6(FD(), PD), duration: /^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/, uri: RT, "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: xT, 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: ET, int32: { type: "number", validate: CT }, int64: { type: "number", validate: kT }, float: { type: "number", validate: AD }, double: { type: "number", validate: AD }, password: true, binary: true };
  RD.fastFormats = { ...RD.fullFormats, date: e6(/^\d\d\d\d-[0-1]\d-[0-3]\d$/, cU), time: e6(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i, pU), "date-time": e6(/^\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, ZD), "iso-time": e6(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i, bD), "iso-date-time": e6(/^\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, PD), 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 };
  RD.formatNames = Object.keys(RD.fullFormats);
  function AT($) {
    return $ % 4 === 0 && ($ % 100 !== 0 || $ % 400 === 0);
  }
  var IT = /^(\d\d\d\d)-(\d\d)-(\d\d)$/, bT = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
  function ID($) {
    let X = IT.exec($);
    if (!X) return false;
    let J = +X[1], Q = +X[2], Y = +X[3];
    return Q >= 1 && Q <= 12 && Y >= 1 && Y <= (Q === 2 && AT(J) ? 29 : bT[Q]);
  }
  function cU($, X) {
    if (!($ && X)) return;
    if ($ > X) return 1;
    if ($ < X) return -1;
    return 0;
  }
  var uU = /^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;
  function mU($) {
    return function(J) {
      let Q = uU.exec(J);
      if (!Q) return false;
      let Y = +Q[1], W = +Q[2], z8 = +Q[3], G = Q[4], U = Q[5] === "-" ? -1 : 1, H = +(Q[6] || 0), K = +(Q[7] || 0);
      if (H > 23 || K > 59 || $ && !G) return false;
      if (Y <= 23 && W <= 59 && z8 < 60) return true;
      let V = W - K * U, N = Y - H * U - (V < 0 ? 1 : 0);
      return (N === 23 || N === -1) && (V === 59 || V === -1) && z8 < 61;
    };
  }
  function pU($, X) {
    if (!($ && X)) return;
    let J = (/* @__PURE__ */ new Date("2020-01-01T" + $)).valueOf(), Q = (/* @__PURE__ */ new Date("2020-01-01T" + X)).valueOf();
    if (!(J && Q)) return;
    return J - Q;
  }
  function bD($, X) {
    if (!($ && X)) return;
    let J = uU.exec($), Q = uU.exec(X);
    if (!(J && Q)) return;
    if ($ = J[1] + J[2] + J[3], X = Q[1] + Q[2] + Q[3], $ > X) return 1;
    if ($ < X) return -1;
    return 0;
  }
  var lU = /t|\s/i;
  function FD($) {
    let X = mU($);
    return function(Q) {
      let Y = Q.split(lU);
      return Y.length === 2 && ID(Y[0]) && X(Y[1]);
    };
  }
  function ZD($, X) {
    if (!($ && X)) return;
    let J = new Date($).valueOf(), Q = new Date(X).valueOf();
    if (!(J && Q)) return;
    return J - Q;
  }
  function PD($, X) {
    if (!($ && X)) return;
    let [J, Q] = $.split(lU), [Y, W] = X.split(lU), z8 = cU(J, Y);
    if (z8 === void 0) return;
    return z8 || pU(Q, W);
  }
  var ZT = /\/|:/, PT = /^(?:[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 RT($) {
    return ZT.test($) && PT.test($);
  }
  var MD = /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;
  function ET($) {
    return MD.lastIndex = 0, MD.test($);
  }
  var ST = -2147483648, vT = 2147483647;
  function CT($) {
    return Number.isInteger($) && $ <= vT && $ >= ST;
  }
  function kT($) {
    return Number.isInteger($);
  }
  function AD() {
    return true;
  }
  var _T = /[^\\]\\Z/;
  function xT($) {
    if (_T.test($)) return false;
    try {
      return new RegExp($), true;
    } catch (X) {
      return false;
    }
  }
});
var CD = k((vD) => {
  Object.defineProperty(vD, "__esModule", { value: true });
  vD.formatLimitDefinition = void 0;
  var yT = hU(), d6 = a(), W1 = d6.operators, B5 = { formatMaximum: { okStr: "<=", ok: W1.LTE, fail: W1.GT }, formatMinimum: { okStr: ">=", ok: W1.GTE, fail: W1.LT }, formatExclusiveMaximum: { okStr: "<", ok: W1.LT, fail: W1.GTE }, formatExclusiveMinimum: { okStr: ">", ok: W1.GT, fail: W1.LTE } }, fT = { message: ({ keyword: $, schemaCode: X }) => d6.str`should be ${B5[$].okStr} ${X}`, params: ({ keyword: $, schemaCode: X }) => d6._`{comparison: ${B5[$].okStr}, limit: ${X}}` };
  vD.formatLimitDefinition = { keyword: Object.keys(B5), type: "string", schemaType: "string", $data: true, error: fT, code($) {
    let { gen: X, data: J, schemaCode: Q, keyword: Y, it: W } = $, { opts: z8, self: G } = W;
    if (!z8.validateFormats) return;
    let U = new yT.KeywordCxt(W, G.RULES.all.format.definition, "format");
    if (U.$data) H();
    else K();
    function H() {
      let N = X.scopeValue("formats", { ref: G.formats, code: z8.code.formats }), O = X.const("fmt", d6._`${N}[${U.schemaCode}]`);
      $.fail$data((0, d6.or)(d6._`typeof ${O} != "object"`, d6._`${O} instanceof RegExp`, d6._`typeof ${O}.compare != "function"`, V(O)));
    }
    function K() {
      let N = U.schema, O = G.formats[N];
      if (!O || O === true) return;
      if (typeof O != "object" || O instanceof RegExp || typeof O.compare != "function") throw Error(`"${Y}": format "${N}" does not define "compare" function`);
      let w = X.scopeValue("formats", { key: N, ref: O, code: z8.code.formats ? d6._`${z8.code.formats}${(0, d6.getProperty)(N)}` : void 0 });
      $.fail$data(V(w));
    }
    function V(N) {
      return d6._`${N}.compare(${J}, ${Q}) ${B5[Y].fail} 0`;
    }
  }, dependencies: ["format"] };
  var gT = ($) => {
    return $.addKeyword(vD.formatLimitDefinition), $;
  };
  vD.default = gT;
});
var TD = k((QJ, xD) => {
  Object.defineProperty(QJ, "__esModule", { value: true });
  var W8 = SD(), uT = CD(), nU = a(), kD = new nU.Name("fullFormats"), mT = new nU.Name("fastFormats"), rU = ($, X = { keywords: true }) => {
    if (Array.isArray(X)) return _D($, X, W8.fullFormats, kD), $;
    let [J, Q] = X.mode === "fast" ? [W8.fastFormats, mT] : [W8.fullFormats, kD], Y = X.formats || W8.formatNames;
    if (_D($, Y, J, Q), X.keywords) (0, uT.default)($);
    return $;
  };
  rU.get = ($, X = "full") => {
    let Q = (X === "fast" ? W8.fastFormats : W8.fullFormats)[$];
    if (!Q) throw Error(`Unknown format "${$}"`);
    return Q;
  };
  function _D($, X, J, Q) {
    var Y, W;
    (Y = (W = $.opts.code).formats) !== null && Y !== void 0 || (W.formats = nU._`require("ajv-formats/dist/formats").${Q}`);
    for (let z8 of X) $.addFormat(z8, J[z8]);
  }
  xD.exports = QJ = rU;
  Object.defineProperty(QJ, "__esModule", { value: true });
  QJ.default = rU;
});
var xj = 50;
function d1($ = xj) {
  let X = new AbortController();
  return (0, import_events.setMaxListeners)($, X.signal), X;
}
function LH($, X, J) {
  return new Promise((Q, Y) => {
    var _a3, _b2;
    if (X == null ? void 0 : X.aborted) {
      if ((J == null ? void 0 : J.throwOnAbort) || (J == null ? void 0 : J.abortError)) Y((_b2 = (_a3 = J.abortError) == null ? void 0 : _a3.call(J)) != null ? _b2 : Error("aborted"));
      else Q();
      return;
    }
    let W = setTimeout((G, U, H) => {
      G == null ? void 0 : G.removeEventListener("abort", U), H();
    }, $, X, z8, Q);
    function z8() {
      var _a4, _b3;
      if (clearTimeout(W), (J == null ? void 0 : J.throwOnAbort) || (J == null ? void 0 : J.abortError)) Y((_b3 = (_a4 = J.abortError) == null ? void 0 : _a4.call(J)) != null ? _b3 : Error("aborted"));
      else Q();
    }
    if (X == null ? void 0 : X.addEventListener("abort", z8, { once: true }), J == null ? void 0 : J.unref) W.unref();
  });
}
function Tj($, X) {
  $(Error(X));
}
function K1($, X, J) {
  let Q, Y = new Promise((W, z8) => {
    var _a3;
    if (Q = setTimeout(Tj, X, z8, J), typeof Q === "object") (_a3 = Q.unref) == null ? void 0 : _a3.call(Q);
  });
  return Promise.race([$, Y]).finally(() => {
    if (Q !== void 0) clearTimeout(Q);
  });
}
var J6 = class extends Error {
};
function i1() {
  return process.versions.bun !== void 0;
}
function r$($) {
  if (!$) return false;
  if (typeof $ === "boolean") return $;
  let X = String($).toLowerCase().trim();
  return ["1", "true", "yes", "on"].includes(X);
}
function n1() {
  let $ = /* @__PURE__ */ new Set();
  return { subscribe(X) {
    return $.add(X), () => {
      $.delete(X);
    };
  }, emit(...X) {
    let J;
    for (let Q of $) try {
      Q(...X);
    } catch (Y) {
      (J != null ? J : J = []).push(Y);
    }
    if (J) throw J.length === 1 ? J[0] : AggregateError(J, "Signal listener(s) threw");
  }, clear() {
    $.clear();
  } };
}
var uj = typeof global == "object" && global && global.Object === Object && global;
var DH = uj;
var mj = typeof self == "object" && self && self.Object === Object && self;
var lj = DH || mj || Function("return this")();
var r1 = lj;
var cj = r1.Symbol;
var o1 = cj;
var jH = Object.prototype;
var pj = jH.hasOwnProperty;
var dj = jH.toString;
var O8 = o1 ? o1.toStringTag : void 0;
function ij($) {
  var X = pj.call($, O8), J = $[O8];
  try {
    $[O8] = void 0;
    var Q = true;
  } catch (W) {
  }
  var Y = dj.call($);
  if (Q) if (X) $[O8] = J;
  else delete $[O8];
  return Y;
}
var FH = ij;
var nj = Object.prototype;
var rj = nj.toString;
function oj($) {
  return rj.call($);
}
var MH = oj;
var tj = "[object Null]";
var aj = "[object Undefined]";
var AH = o1 ? o1.toStringTag : void 0;
function sj($) {
  if ($ == null) return $ === void 0 ? aj : tj;
  return AH && AH in Object($) ? FH($) : MH($);
}
var IH = sj;
function ej($) {
  var X = typeof $;
  return $ != null && (X == "object" || X == "function");
}
var UJ = ej;
var $F = "[object AsyncFunction]";
var XF = "[object Function]";
var JF = "[object GeneratorFunction]";
var YF = "[object Proxy]";
function QF($) {
  if (!UJ($)) return false;
  var X = IH($);
  return X == XF || X == JF || X == $F || X == YF;
}
var bH = QF;
var WF = r1["__core-js_shared__"];
var HJ = WF;
var ZH = (function() {
  var $ = /[^.]+$/.exec(HJ && HJ.keys && HJ.keys.IE_PROTO || "");
  return $ ? "Symbol(src)_1." + $ : "";
})();
function zF($) {
  return !!ZH && ZH in $;
}
var PH = zF;
var GF = Function.prototype;
var UF = GF.toString;
function HF($) {
  if ($ != null) {
    try {
      return UF.call($);
    } catch (X) {
    }
    try {
      return $ + "";
    } catch (X) {
    }
  }
  return "";
}
var RH = HF;
var KF = /[\\^$.*+?()[\]{}|]/g;
var VF = /^\[object .+?Constructor\]$/;
var NF = Function.prototype;
var OF = Object.prototype;
var wF = NF.toString;
var BF = OF.hasOwnProperty;
var qF = RegExp("^" + wF.call(BF).replace(KF, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$");
function LF($) {
  if (!UJ($) || PH($)) return false;
  var X = bH($) ? qF : VF;
  return X.test(RH($));
}
var EH = LF;
function DF($, X) {
  return $ == null ? void 0 : $[X];
}
var SH = DF;
function jF($, X) {
  var J = SH($, X);
  return EH(J) ? J : void 0;
}
var KJ = jF;
var FF = KJ(Object, "create");
var W4 = FF;
function MF() {
  this.__data__ = W4 ? W4(null) : {}, this.size = 0;
}
var vH = MF;
function AF($) {
  var X = this.has($) && delete this.__data__[$];
  return this.size -= X ? 1 : 0, X;
}
var CH = AF;
var IF = "__lodash_hash_undefined__";
var bF = Object.prototype;
var ZF = bF.hasOwnProperty;
function PF($) {
  var X = this.__data__;
  if (W4) {
    var J = X[$];
    return J === IF ? void 0 : J;
  }
  return ZF.call(X, $) ? X[$] : void 0;
}
var kH = PF;
var RF = Object.prototype;
var EF = RF.hasOwnProperty;
function SF($) {
  var X = this.__data__;
  return W4 ? X[$] !== void 0 : EF.call(X, $);
}
var _H = SF;
var vF = "__lodash_hash_undefined__";
function CF($, X) {
  var J = this.__data__;
  return this.size += this.has($) ? 0 : 1, J[$] = W4 && X === void 0 ? vF : X, this;
}
var xH = CF;
function t1($) {
  var X = -1, J = $ == null ? 0 : $.length;
  this.clear();
  while (++X < J) {
    var Q = $[X];
    this.set(Q[0], Q[1]);
  }
}
t1.prototype.clear = vH;
t1.prototype.delete = CH;
t1.prototype.get = kH;
t1.prototype.has = _H;
t1.prototype.set = xH;
var A5 = t1;
function kF() {
  this.__data__ = [], this.size = 0;
}
var TH = kF;
function _F($, X) {
  return $ === X || $ !== $ && X !== X;
}
var yH = _F;
function xF($, X) {
  var J = $.length;
  while (J--) if (yH($[J][0], X)) return J;
  return -1;
}
var E4 = xF;
var TF = Array.prototype;
var yF = TF.splice;
function fF($) {
  var X = this.__data__, J = E4(X, $);
  if (J < 0) return false;
  var Q = X.length - 1;
  if (J == Q) X.pop();
  else yF.call(X, J, 1);
  return --this.size, true;
}
var fH = fF;
function gF($) {
  var X = this.__data__, J = E4(X, $);
  return J < 0 ? void 0 : X[J][1];
}
var gH = gF;
function hF($) {
  return E4(this.__data__, $) > -1;
}
var hH = hF;
function uF($, X) {
  var J = this.__data__, Q = E4(J, $);
  if (Q < 0) ++this.size, J.push([$, X]);
  else J[Q][1] = X;
  return this;
}
var uH = uF;
function a1($) {
  var X = -1, J = $ == null ? 0 : $.length;
  this.clear();
  while (++X < J) {
    var Q = $[X];
    this.set(Q[0], Q[1]);
  }
}
a1.prototype.clear = TH;
a1.prototype.delete = fH;
a1.prototype.get = gH;
a1.prototype.has = hH;
a1.prototype.set = uH;
var mH = a1;
var mF = KJ(r1, "Map");
var lH = mF;
function lF() {
  this.size = 0, this.__data__ = { hash: new A5(), map: new (lH || mH)(), string: new A5() };
}
var cH = lF;
function cF($) {
  var X = typeof $;
  return X == "string" || X == "number" || X == "symbol" || X == "boolean" ? $ !== "__proto__" : $ === null;
}
var pH = cF;
function pF($, X) {
  var J = $.__data__;
  return pH(X) ? J[typeof X == "string" ? "string" : "hash"] : J.map;
}
var S4 = pF;
function dF($) {
  var X = S4(this, $).delete($);
  return this.size -= X ? 1 : 0, X;
}
var dH = dF;
function iF($) {
  return S4(this, $).get($);
}
var iH = iF;
function nF($) {
  return S4(this, $).has($);
}
var nH = nF;
function rF($, X) {
  var J = S4(this, $), Q = J.size;
  return J.set($, X), this.size += J.size == Q ? 0 : 1, this;
}
var rH = rF;
function s1($) {
  var X = -1, J = $ == null ? 0 : $.length;
  this.clear();
  while (++X < J) {
    var Q = $[X];
    this.set(Q[0], Q[1]);
  }
}
s1.prototype.clear = cH;
s1.prototype.delete = dH;
s1.prototype.get = iH;
s1.prototype.has = nH;
s1.prototype.set = rH;
var I5 = s1;
var oF = "Expected a function";
function b5($, X) {
  if (typeof $ != "function" || X != null && typeof X != "function") throw TypeError(oF);
  var J = function() {
    var Q = arguments, Y = X ? X.apply(this, Q) : Q[0], W = J.cache;
    if (W.has(Y)) return W.get(Y);
    var z8 = $.apply(this, Q);
    return J.cache = W.set(Y, z8) || W, z8;
  };
  return J.cache = new (b5.Cache || I5)(), J;
}
b5.Cache = I5;
var C6 = b5;
var v4 = C6(() => {
  var _a3;
  return ((_a3 = process.env.CLAUDE_CONFIG_DIR) != null ? _a3 : (0, import_path2.join)((0, import_os2.homedir)(), ".claude")).normalize("NFC");
}, () => process.env.CLAUDE_CONFIG_DIR);
function v($, X, J, Q, Y) {
  if (Q === "m") throw TypeError("Private method is not writable");
  if (Q === "a" && !Y) throw TypeError("Private accessor was defined without a setter");
  if (typeof X === "function" ? $ !== X || !Y : !X.has($)) throw TypeError("Cannot write private member to an object whose class did not declare it");
  return Q === "a" ? Y.call($, J) : Y ? Y.value = J : X.set($, J), J;
}
function L($, X, J, Q) {
  if (J === "a" && !Q) throw TypeError("Private accessor was defined without a getter");
  if (typeof X === "function" ? $ !== X || !Q : !X.has($)) throw TypeError("Cannot read private member from an object whose class did not declare it");
  return J === "m" ? Q : J === "a" ? Q.call($) : Q ? Q.value : X.get($);
}
var Z5 = function() {
  let { crypto: $ } = globalThis;
  if ($ == null ? void 0 : $.randomUUID) return Z5 = $.randomUUID.bind($), $.randomUUID();
  let X = new Uint8Array(1), J = $ ? () => $.getRandomValues(X)[0] : () => Math.random() * 255 & 255;
  return "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (Q) => (+Q ^ J() & 15 >> +Q / 4).toString(16));
};
function z4($) {
  return typeof $ === "object" && $ !== null && ("name" in $ && $.name === "AbortError" || "message" in $ && String($.message).includes("FetchRequestCanceledException"));
}
var w8 = ($) => {
  if ($ instanceof Error) return $;
  if (typeof $ === "object" && $ !== null) {
    try {
      if (Object.prototype.toString.call($) === "[object Error]") {
        let X = Error($.message, $.cause ? { cause: $.cause } : {});
        if ($.stack) X.stack = $.stack;
        if ($.cause && !X.cause) X.cause = $.cause;
        if ($.name) X.name = $.name;
        return X;
      }
    } catch (e2) {
    }
    try {
      return Error(JSON.stringify($));
    } catch (e2) {
    }
  }
  return Error($);
};
var y = class extends Error {
};
var C$ = class _C$ extends y {
  constructor($, X, J, Q, Y) {
    super(`${_C$.makeMessage($, X, J)}`);
    this.status = $, this.headers = Q, this.requestID = Q == null ? void 0 : Q.get("request-id"), this.error = X, this.type = Y != null ? Y : null;
  }
  static makeMessage($, X, J) {
    let Q = (X == null ? void 0 : X.message) ? typeof X.message === "string" ? X.message : JSON.stringify(X.message) : X ? JSON.stringify(X) : J;
    if ($ && Q) return `${$} ${Q}`;
    if ($) return `${$} status code (no body)`;
    if (Q) return Q;
    return "(no status code or body)";
  }
  static generate($, X, J, Q) {
    var _a3;
    if (!$ || !Q) return new V1({ message: J, cause: w8(X) });
    let Y = X, W = (_a3 = Y == null ? void 0 : Y.error) == null ? void 0 : _a3.type;
    if ($ === 400) return new q8($, Y, J, Q, W);
    if ($ === 401) return new L8($, Y, J, Q, W);
    if ($ === 403) return new D8($, Y, J, Q, W);
    if ($ === 404) return new j8($, Y, J, Q, W);
    if ($ === 409) return new F8($, Y, J, Q, W);
    if ($ === 422) return new M8($, Y, J, Q, W);
    if ($ === 429) return new A8($, Y, J, Q, W);
    if ($ >= 500) return new I8($, Y, J, Q, W);
    return new _C$($, Y, J, Q, W);
  }
};
var g$ = class extends C$ {
  constructor({ message: $ } = {}) {
    super(void 0, void 0, $ || "Request was aborted.", void 0);
  }
};
var V1 = class extends C$ {
  constructor({ message: $, cause: X }) {
    super(void 0, void 0, $ || "Connection error.", void 0);
    if (X) this.cause = X;
  }
};
var B8 = class extends V1 {
  constructor({ message: $ } = {}) {
    super({ message: $ != null ? $ : "Request timed out." });
  }
};
var q8 = class extends C$ {
};
var L8 = class extends C$ {
};
var D8 = class extends C$ {
};
var j8 = class extends C$ {
};
var F8 = class extends C$ {
};
var M8 = class extends C$ {
};
var A8 = class extends C$ {
};
var I8 = class extends C$ {
};
var eF = /^[a-z][a-z0-9+.-]*:/i;
var oH = ($) => {
  return eF.test($);
};
var P5 = ($) => (P5 = Array.isArray, P5($));
var R5 = P5;
function VJ($) {
  if (typeof $ !== "object") return {};
  return $ != null ? $ : {};
}
function E5($) {
  if (!$) return true;
  for (let X in $) return false;
  return true;
}
function tH($, X) {
  return Object.prototype.hasOwnProperty.call($, X);
}
var aH = ($, X) => {
  if (typeof X !== "number" || !Number.isInteger(X)) throw new y(`${$} must be an integer`);
  if (X < 0) throw new y(`${$} must be a positive integer`);
  return X;
};
var NJ = ($) => {
  try {
    return JSON.parse($);
  } catch (X) {
    return;
  }
};
var sH = ($) => new Promise((X) => setTimeout(X, $));
var C4 = "0.81.0";
var JK = () => {
  return typeof window < "u" && typeof window.document < "u" && typeof navigator < "u";
};
function $M() {
  if (typeof Deno < "u" && Deno.build != null) return "deno";
  if (typeof EdgeRuntime < "u") return "edge";
  if (Object.prototype.toString.call(typeof globalThis.process < "u" ? globalThis.process : 0) === "[object process]") return "node";
  return "unknown";
}
var XM = () => {
  var _a3, _b2, _c, _d2, _e;
  let $ = $M();
  if ($ === "deno") return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": C4, "X-Stainless-OS": $K(Deno.build.os), "X-Stainless-Arch": eH(Deno.build.arch), "X-Stainless-Runtime": "deno", "X-Stainless-Runtime-Version": typeof Deno.version === "string" ? Deno.version : (_b2 = (_a3 = Deno.version) == null ? void 0 : _a3.deno) != null ? _b2 : "unknown" };
  if (typeof EdgeRuntime < "u") return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": C4, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": `other:${EdgeRuntime}`, "X-Stainless-Runtime": "edge", "X-Stainless-Runtime-Version": globalThis.process.version };
  if ($ === "node") return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": C4, "X-Stainless-OS": $K((_c = globalThis.process.platform) != null ? _c : "unknown"), "X-Stainless-Arch": eH((_d2 = globalThis.process.arch) != null ? _d2 : "unknown"), "X-Stainless-Runtime": "node", "X-Stainless-Runtime-Version": (_e = globalThis.process.version) != null ? _e : "unknown" };
  let X = JM();
  if (X) return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": C4, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": "unknown", "X-Stainless-Runtime": `browser:${X.browser}`, "X-Stainless-Runtime-Version": X.version };
  return { "X-Stainless-Lang": "js", "X-Stainless-Package-Version": C4, "X-Stainless-OS": "Unknown", "X-Stainless-Arch": "unknown", "X-Stainless-Runtime": "unknown", "X-Stainless-Runtime-Version": "unknown" };
};
function JM() {
  if (typeof navigator > "u" || !navigator) return null;
  let $ = [{ key: "edge", pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie", pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "ie", pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "chrome", pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "firefox", pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, { key: "safari", pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }];
  for (let { key: X, pattern: J } of $) {
    let Q = J.exec(navigator.userAgent);
    if (Q) {
      let Y = Q[1] || 0, W = Q[2] || 0, z8 = Q[3] || 0;
      return { browser: X, version: `${Y}.${W}.${z8}` };
    }
  }
  return null;
}
var eH = ($) => {
  if ($ === "x32") return "x32";
  if ($ === "x86_64" || $ === "x64") return "x64";
  if ($ === "arm") return "arm";
  if ($ === "aarch64" || $ === "arm64") return "arm64";
  if ($) return `other:${$}`;
  return "unknown";
};
var $K = ($) => {
  if ($ = $.toLowerCase(), $.includes("ios")) return "iOS";
  if ($ === "android") return "Android";
  if ($ === "darwin") return "MacOS";
  if ($ === "win32") return "Windows";
  if ($ === "freebsd") return "FreeBSD";
  if ($ === "openbsd") return "OpenBSD";
  if ($ === "linux") return "Linux";
  if ($) return `Other:${$}`;
  return "Unknown";
};
var XK;
var YK = () => {
  return XK != null ? XK : XK = XM();
};
function QK() {
  if (typeof fetch < "u") return fetch;
  throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`");
}
function S5(...$) {
  let X = globalThis.ReadableStream;
  if (typeof X > "u") throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");
  return new X(...$);
}
function OJ($) {
  let X = Symbol.asyncIterator in $ ? $[Symbol.asyncIterator]() : $[Symbol.iterator]();
  return S5({ start() {
  }, async pull(J) {
    let { done: Q, value: Y } = await X.next();
    if (Q) J.close();
    else J.enqueue(Y);
  }, async cancel() {
    var _a3;
    await ((_a3 = X.return) == null ? void 0 : _a3.call(X));
  } });
}
function b8($) {
  if ($[Symbol.asyncIterator]) return $;
  let X = $.getReader();
  return { async next() {
    try {
      let J = await X.read();
      if (J == null ? void 0 : J.done) X.releaseLock();
      return J;
    } catch (J) {
      throw X.releaseLock(), J;
    }
  }, async return() {
    let J = X.cancel();
    return X.releaseLock(), await J, { done: true, value: void 0 };
  }, [Symbol.asyncIterator]() {
    return this;
  } };
}
async function WK($) {
  var _a3, _b2;
  if ($ === null || typeof $ !== "object") return;
  if ($[Symbol.asyncIterator]) {
    await ((_b2 = (_a3 = $[Symbol.asyncIterator]()).return) == null ? void 0 : _b2.call(_a3));
    return;
  }
  let X = $.getReader(), J = X.cancel();
  X.releaseLock(), await J;
}
var zK = ({ headers: $, body: X }) => {
  return { bodyHeaders: { "content-type": "application/json" }, body: JSON.stringify(X) };
};
function GK($) {
  return Object.entries($).filter(([X, J]) => typeof J < "u").map(([X, J]) => {
    if (typeof J === "string" || typeof J === "number" || typeof J === "boolean") return `${encodeURIComponent(X)}=${encodeURIComponent(J)}`;
    if (J === null) return `${encodeURIComponent(X)}=`;
    throw new y(`Cannot stringify type ${typeof J}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`);
  }).join("&");
}
function KK($) {
  let X = 0;
  for (let Y of $) X += Y.length;
  let J = new Uint8Array(X), Q = 0;
  for (let Y of $) J.set(Y, Q), Q += Y.length;
  return J;
}
var UK;
function Z8($) {
  let X;
  return (UK != null ? UK : (X = new globalThis.TextEncoder(), UK = X.encode.bind(X)))($);
}
var HK;
function v5($) {
  let X;
  return (HK != null ? HK : (X = new globalThis.TextDecoder(), HK = X.decode.bind(X)))($);
}
var O6;
var w6;
var k4 = class {
  constructor() {
    O6.set(this, void 0), w6.set(this, void 0), v(this, O6, new Uint8Array(), "f"), v(this, w6, null, "f");
  }
  decode($) {
    if ($ == null) return [];
    let X = $ instanceof ArrayBuffer ? new Uint8Array($) : typeof $ === "string" ? Z8($) : $;
    v(this, O6, KK([L(this, O6, "f"), X]), "f");
    let J = [], Q;
    while ((Q = WM(L(this, O6, "f"), L(this, w6, "f"))) != null) {
      if (Q.carriage && L(this, w6, "f") == null) {
        v(this, w6, Q.index, "f");
        continue;
      }
      if (L(this, w6, "f") != null && (Q.index !== L(this, w6, "f") + 1 || Q.carriage)) {
        J.push(v5(L(this, O6, "f").subarray(0, L(this, w6, "f") - 1))), v(this, O6, L(this, O6, "f").subarray(L(this, w6, "f")), "f"), v(this, w6, null, "f");
        continue;
      }
      let Y = L(this, w6, "f") !== null ? Q.preceding - 1 : Q.preceding, W = v5(L(this, O6, "f").subarray(0, Y));
      J.push(W), v(this, O6, L(this, O6, "f").subarray(Q.index), "f"), v(this, w6, null, "f");
    }
    return J;
  }
  flush() {
    if (!L(this, O6, "f").length) return [];
    return this.decode(`
`);
  }
};
O6 = /* @__PURE__ */ new WeakMap(), w6 = /* @__PURE__ */ new WeakMap();
k4.NEWLINE_CHARS = /* @__PURE__ */ new Set([`
`, "\r"]);
k4.NEWLINE_REGEXP = /\r\n|[\n\r]/g;
function WM($, X) {
  for (let Y = X != null ? X : 0; Y < $.length; Y++) {
    if ($[Y] === 10) return { preceding: Y, index: Y + 1, carriage: false };
    if ($[Y] === 13) return { preceding: Y, index: Y + 1, carriage: true };
  }
  return null;
}
function VK($) {
  for (let Q = 0; Q < $.length - 1; Q++) {
    if ($[Q] === 10 && $[Q + 1] === 10) return Q + 2;
    if ($[Q] === 13 && $[Q + 1] === 13) return Q + 2;
    if ($[Q] === 13 && $[Q + 1] === 10 && Q + 3 < $.length && $[Q + 2] === 13 && $[Q + 3] === 10) return Q + 4;
  }
  return -1;
}
var BJ = { off: 0, error: 200, warn: 300, info: 400, debug: 500 };
var C5 = ($, X, J) => {
  if (!$) return;
  if (tH(BJ, $)) return $;
  y$(J).warn(`${X} was set to ${JSON.stringify($)}, expected one of ${JSON.stringify(Object.keys(BJ))}`);
  return;
};
function P8() {
}
function wJ($, X, J) {
  if (!X || BJ[$] > BJ[J]) return P8;
  else return X[$].bind(X);
}
var zM = { error: P8, warn: P8, info: P8, debug: P8 };
var NK = /* @__PURE__ */ new WeakMap();
function y$($) {
  var _a3;
  let X = $.logger, J = (_a3 = $.logLevel) != null ? _a3 : "off";
  if (!X) return zM;
  let Q = NK.get(X);
  if (Q && Q[0] === J) return Q[1];
  let Y = { error: wJ("error", X, J), warn: wJ("warn", X, J), info: wJ("info", X, J), debug: wJ("debug", X, J) };
  return NK.set(X, [J, Y]), Y;
}
var G4 = ($) => {
  if ($.options) $.options = { ...$.options }, delete $.options.headers;
  if ($.headers) $.headers = Object.fromEntries(($.headers instanceof Headers ? [...$.headers] : Object.entries($.headers)).map(([X, J]) => [X, X.toLowerCase() === "x-api-key" || X.toLowerCase() === "authorization" || X.toLowerCase() === "cookie" || X.toLowerCase() === "set-cookie" ? "***" : J]));
  if ("retryOfRequestLogID" in $) {
    if ($.retryOfRequestLogID) $.retryOf = $.retryOfRequestLogID;
    delete $.retryOfRequestLogID;
  }
  return $;
};
var R8;
var B6 = class _B6 {
  constructor($, X, J) {
    this.iterator = $, R8.set(this, void 0), this.controller = X, v(this, R8, J, "f");
  }
  static fromSSEResponse($, X, J) {
    let Q = false, Y = J ? y$(J) : console;
    async function* W() {
      var _a3, _b2;
      if (Q) throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      Q = true;
      let z8 = false;
      try {
        for await (let G of GM($, X)) {
          if (G.event === "completion") try {
            yield JSON.parse(G.data);
          } catch (U) {
            throw Y.error("Could not parse message into JSON:", G.data), Y.error("From chunk:", G.raw), U;
          }
          if (G.event === "message_start" || G.event === "message_delta" || G.event === "message_stop" || G.event === "content_block_start" || G.event === "content_block_delta" || G.event === "content_block_stop") try {
            yield JSON.parse(G.data);
          } catch (U) {
            throw Y.error("Could not parse message into JSON:", G.data), Y.error("From chunk:", G.raw), U;
          }
          if (G.event === "ping") continue;
          if (G.event === "error") {
            let U = (_a3 = NJ(G.data)) != null ? _a3 : G.data, H = (_b2 = U == null ? void 0 : U.error) == null ? void 0 : _b2.type;
            throw new C$(void 0, U, void 0, $.headers, H);
          }
        }
        z8 = true;
      } catch (G) {
        if (z4(G)) return;
        throw G;
      } finally {
        if (!z8) X.abort();
      }
    }
    return new _B6(W, X, J);
  }
  static fromReadableStream($, X, J) {
    let Q = false;
    async function* Y() {
      let z8 = new k4(), G = b8($);
      for await (let U of G) for (let H of z8.decode(U)) yield H;
      for (let U of z8.flush()) yield U;
    }
    async function* W() {
      if (Q) throw new y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");
      Q = true;
      let z8 = false;
      try {
        for await (let G of Y()) {
          if (z8) continue;
          if (G) yield JSON.parse(G);
        }
        z8 = true;
      } catch (G) {
        if (z4(G)) return;
        throw G;
      } finally {
        if (!z8) X.abort();
      }
    }
    return new _B6(W, X, J);
  }
  [(R8 = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
    return this.iterator();
  }
  tee() {
    let $ = [], X = [], J = this.iterator(), Q = (Y) => {
      return { next: () => {
        if (Y.length === 0) {
          let W = J.next();
          $.push(W), X.push(W);
        }
        return Y.shift();
      } };
    };
    return [new _B6(() => Q($), this.controller, L(this, R8, "f")), new _B6(() => Q(X), this.controller, L(this, R8, "f"))];
  }
  toReadableStream() {
    let $ = this, X;
    return S5({ async start() {
      X = $[Symbol.asyncIterator]();
    }, async pull(J) {
      try {
        let { value: Q, done: Y } = await X.next();
        if (Y) return J.close();
        let W = Z8(JSON.stringify(Q) + `
`);
        J.enqueue(W);
      } catch (Q) {
        J.error(Q);
      }
    }, async cancel() {
      var _a3;
      await ((_a3 = X.return) == null ? void 0 : _a3.call(X));
    } });
  }
};
async function* GM($, X) {
  if (!$.body) {
    if (X.abort(), typeof globalThis.navigator < "u" && globalThis.navigator.product === "ReactNative") throw new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");
    throw new y("Attempted to iterate over a response with no body");
  }
  let J = new OK(), Q = new k4(), Y = b8($.body);
  for await (let W of UM(Y)) for (let z8 of Q.decode(W)) {
    let G = J.decode(z8);
    if (G) yield G;
  }
  for (let W of Q.flush()) {
    let z8 = J.decode(W);
    if (z8) yield z8;
  }
}
async function* UM($) {
  let X = new Uint8Array();
  for await (let J of $) {
    if (J == null) continue;
    let Q = J instanceof ArrayBuffer ? new Uint8Array(J) : typeof J === "string" ? Z8(J) : J, Y = new Uint8Array(X.length + Q.length);
    Y.set(X), Y.set(Q, X.length), X = Y;
    let W;
    while ((W = VK(X)) !== -1) yield X.slice(0, W), X = X.slice(W);
  }
  if (X.length > 0) yield X;
}
var OK = class {
  constructor() {
    this.event = null, this.data = [], this.chunks = [];
  }
  decode($) {
    if ($.endsWith("\r")) $ = $.substring(0, $.length - 1);
    if (!$) {
      if (!this.event && !this.data.length) return null;
      let Y = { event: this.event, data: this.data.join(`
`), raw: this.chunks };
      return this.event = null, this.data = [], this.chunks = [], Y;
    }
    if (this.chunks.push($), $.startsWith(":")) return null;
    let [X, J, Q] = HM($, ":");
    if (Q.startsWith(" ")) Q = Q.substring(1);
    if (X === "event") this.event = Q;
    else if (X === "data") this.data.push(Q);
    return null;
  }
};
function HM($, X) {
  let J = $.indexOf(X);
  if (J !== -1) return [$.substring(0, J), X, $.substring(J + X.length)];
  return [$, "", ""];
}
async function qJ($, X) {
  let { response: J, requestLogID: Q, retryOfRequestLogID: Y, startTime: W } = X, z8 = await (async () => {
    var _a3, _b2;
    if (X.options.stream) {
      if (y$($).debug("response", J.status, J.url, J.headers, J.body), X.options.__streamClass) return X.options.__streamClass.fromSSEResponse(J, X.controller);
      return B6.fromSSEResponse(J, X.controller);
    }
    if (J.status === 204) return null;
    if (X.options.__binaryResponse) return J;
    let U = (_b2 = (_a3 = J.headers.get("content-type")) == null ? void 0 : _a3.split(";")[0]) == null ? void 0 : _b2.trim();
    if ((U == null ? void 0 : U.includes("application/json")) || (U == null ? void 0 : U.endsWith("+json"))) {
      if (J.headers.get("content-length") === "0") return;
      let N = await J.json();
      return k5(N, J);
    }
    return await J.text();
  })();
  return y$($).debug(`[${Q}] response parsed`, G4({ retryOfRequestLogID: Y, url: J.url, status: J.status, body: z8, durationMs: Date.now() - W })), z8;
}
function k5($, X) {
  if (!$ || typeof $ !== "object" || Array.isArray($)) return $;
  return Object.defineProperty($, "_request_id", { value: X.headers.get("request-id"), enumerable: false });
}
var E8;
var N1 = class _N1 extends Promise {
  constructor($, X, J = qJ) {
    super((Q) => {
      Q(null);
    });
    this.responsePromise = X, this.parseResponse = J, E8.set(this, void 0), v(this, E8, $, "f");
  }
  _thenUnwrap($) {
    return new _N1(L(this, E8, "f"), this.responsePromise, async (X, J) => k5($(await this.parseResponse(X, J), J), J.response));
  }
  asResponse() {
    return this.responsePromise.then(($) => $.response);
  }
  async withResponse() {
    let [$, X] = await Promise.all([this.parse(), this.asResponse()]);
    return { data: $, response: X, request_id: X.headers.get("request-id") };
  }
  parse() {
    if (!this.parsedPromise) this.parsedPromise = this.responsePromise.then(($) => this.parseResponse(L(this, E8, "f"), $));
    return this.parsedPromise;
  }
  then($, X) {
    return this.parse().then($, X);
  }
  catch($) {
    return this.parse().catch($);
  }
  finally($) {
    return this.parse().finally($);
  }
};
E8 = /* @__PURE__ */ new WeakMap();
var LJ;
var _5 = class {
  constructor($, X, J, Q) {
    LJ.set(this, void 0), v(this, LJ, $, "f"), this.options = Q, this.response = X, this.body = J;
  }
  hasNextPage() {
    if (!this.getPaginatedItems().length) return false;
    return this.nextPageRequestOptions() != null;
  }
  async getNextPage() {
    let $ = this.nextPageRequestOptions();
    if (!$) throw new y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");
    return await L(this, LJ, "f").requestAPIList(this.constructor, $);
  }
  async *iterPages() {
    let $ = this;
    yield $;
    while ($.hasNextPage()) $ = await $.getNextPage(), yield $;
  }
  async *[(LJ = /* @__PURE__ */ new WeakMap(), Symbol.asyncIterator)]() {
    for await (let $ of this.iterPages()) for (let X of $.getPaginatedItems()) yield X;
  }
};
var DJ = class extends N1 {
  constructor($, X, J) {
    super($, X, async (Q, Y) => new J(Q, Y.response, await qJ(Q, Y), Y.options));
  }
  async *[Symbol.asyncIterator]() {
    let $ = await this;
    for await (let X of $) yield X;
  }
};
var k6 = class extends _5 {
  constructor($, X, J, Q) {
    super($, X, J, Q);
    this.data = J.data || [], this.has_more = J.has_more || false, this.first_id = J.first_id || null, this.last_id = J.last_id || null;
  }
  getPaginatedItems() {
    var _a3;
    return (_a3 = this.data) != null ? _a3 : [];
  }
  hasNextPage() {
    if (this.has_more === false) return false;
    return super.hasNextPage();
  }
  nextPageRequestOptions() {
    var _a3;
    if ((_a3 = this.options.query) == null ? void 0 : _a3.before_id) {
      let X = this.first_id;
      if (!X) return null;
      return { ...this.options, query: { ...VJ(this.options.query), before_id: X } };
    }
    let $ = this.last_id;
    if (!$) return null;
    return { ...this.options, query: { ...VJ(this.options.query), after_id: $ } };
  }
};
var S8 = class extends _5 {
  constructor($, X, J, Q) {
    super($, X, J, Q);
    this.data = J.data || [], this.has_more = J.has_more || false, this.next_page = J.next_page || null;
  }
  getPaginatedItems() {
    var _a3;
    return (_a3 = this.data) != null ? _a3 : [];
  }
  hasNextPage() {
    if (this.has_more === false) return false;
    return super.hasNextPage();
  }
  nextPageRequestOptions() {
    let $ = this.next_page;
    if (!$) return null;
    return { ...this.options, query: { ...VJ(this.options.query), page: $ } };
  }
};
var T5 = () => {
  var _a3;
  if (typeof File > "u") {
    let { process: $ } = globalThis, X = typeof ((_a3 = $ == null ? void 0 : $.versions) == null ? void 0 : _a3.node) === "string" && parseInt($.versions.node.split(".")) < 20;
    throw Error("`File` is not defined as a global, which is required for file uploads." + (X ? " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." : ""));
  }
};
function O1($, X, J) {
  return T5(), new File($, X != null ? X : "unknown_file", J);
}
function v8($, X) {
  let J = typeof $ === "object" && $ !== null && ("name" in $ && $.name && String($.name) || "url" in $ && $.url && String($.url) || "filename" in $ && $.filename && String($.filename) || "path" in $ && $.path && String($.path)) || "";
  return X ? J.split(/[\\/]/).pop() || void 0 : J;
}
var y5 = ($) => $ != null && typeof $ === "object" && typeof $[Symbol.asyncIterator] === "function";
var e1 = async ($, X, J = true) => {
  return { ...$, body: await NM($.body, X, J) };
};
var wK = /* @__PURE__ */ new WeakMap();
function VM($) {
  let X = typeof $ === "function" ? $ : $.fetch, J = wK.get(X);
  if (J) return J;
  let Q = (async () => {
    try {
      let Y = "Response" in X ? X.Response : (await X("data:,")).constructor, W = new FormData();
      if (W.toString() === await new Y(W).text()) return false;
      return true;
    } catch (e2) {
      return true;
    }
  })();
  return wK.set(X, Q), Q;
}
var NM = async ($, X, J = true) => {
  if (!await VM(X)) throw TypeError("The provided fetch function does not support file uploads with the current global FormData class.");
  let Q = new FormData();
  return await Promise.all(Object.entries($ || {}).map(([Y, W]) => x5(Q, Y, W, J))), Q;
};
var OM = ($) => $ instanceof Blob && "name" in $;
var x5 = async ($, X, J, Q) => {
  if (J === void 0) return;
  if (J == null) throw TypeError(`Received null for "${X}"; to pass null in FormData, you must use the string 'null'`);
  if (typeof J === "string" || typeof J === "number" || typeof J === "boolean") $.append(X, String(J));
  else if (J instanceof Response) {
    let Y = {}, W = J.headers.get("Content-Type");
    if (W) Y = { type: W };
    $.append(X, O1([await J.blob()], v8(J, Q), Y));
  } else if (y5(J)) $.append(X, O1([await new Response(OJ(J)).blob()], v8(J, Q)));
  else if (OM(J)) $.append(X, O1([J], v8(J, Q), { type: J.type }));
  else if (Array.isArray(J)) await Promise.all(J.map((Y) => x5($, X + "[]", Y, Q)));
  else if (typeof J === "object") await Promise.all(Object.entries(J).map(([Y, W]) => x5($, `${X}[${Y}]`, W, Q)));
  else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${J} instead`);
};
var BK = ($) => $ != null && typeof $ === "object" && typeof $.size === "number" && typeof $.type === "string" && typeof $.text === "function" && typeof $.slice === "function" && typeof $.arrayBuffer === "function";
var wM = ($) => $ != null && typeof $ === "object" && typeof $.name === "string" && typeof $.lastModified === "number" && BK($);
var BM = ($) => $ != null && typeof $ === "object" && typeof $.url === "string" && typeof $.blob === "function";
async function jJ($, X, J) {
  if (T5(), $ = await $, X || (X = v8($, true)), wM($)) {
    if ($ instanceof File && X == null && J == null) return $;
    return O1([await $.arrayBuffer()], X != null ? X : $.name, { type: $.type, lastModified: $.lastModified, ...J });
  }
  if (BM($)) {
    let Y = await $.blob();
    return X || (X = new URL($.url).pathname.split(/[\\/]/).pop()), O1(await f5(Y), X, J);
  }
  let Q = await f5($);
  if (!(J == null ? void 0 : J.type)) {
    let Y = Q.find((W) => typeof W === "object" && "type" in W && W.type);
    if (typeof Y === "string") J = { ...J, type: Y };
  }
  return O1(Q, X, J);
}
async function f5($) {
  var _a3;
  let X = [];
  if (typeof $ === "string" || ArrayBuffer.isView($) || $ instanceof ArrayBuffer) X.push($);
  else if (BK($)) X.push($ instanceof Blob ? $ : await $.arrayBuffer());
  else if (y5($)) for await (let J of $) X.push(...await f5(J));
  else {
    let J = (_a3 = $ == null ? void 0 : $.constructor) == null ? void 0 : _a3.name;
    throw Error(`Unexpected data type: ${typeof $}${J ? `; constructor: ${J}` : ""}${qM($)}`);
  }
  return X;
}
function qM($) {
  if (typeof $ !== "object" || $ === null) return "";
  return `; props: [${Object.getOwnPropertyNames($).map((J) => `"${J}"`).join(", ")}]`;
}
var b$ = class {
  constructor($) {
    this._client = $;
  }
};
var qK = /* @__PURE__ */ Symbol.for("brand.privateNullableHeaders");
function* DM($) {
  if (!$) return;
  if (qK in $) {
    let { values: Q, nulls: Y } = $;
    yield* Q.entries();
    for (let W of Y) yield [W, null];
    return;
  }
  let X = false, J;
  if ($ instanceof Headers) J = $.entries();
  else if (R5($)) J = $;
  else X = true, J = Object.entries($ != null ? $ : {});
  for (let Q of J) {
    let Y = Q[0];
    if (typeof Y !== "string") throw TypeError("expected header name to be a string");
    let W = R5(Q[1]) ? Q[1] : [Q[1]], z8 = false;
    for (let G of W) {
      if (G === void 0) continue;
      if (X && !z8) z8 = true, yield [Y, null];
      yield [Y, G];
    }
  }
}
var i = ($) => {
  let X = new Headers(), J = /* @__PURE__ */ new Set();
  for (let Q of $) {
    let Y = /* @__PURE__ */ new Set();
    for (let [W, z8] of DM(Q)) {
      let G = W.toLowerCase();
      if (!Y.has(G)) X.delete(W), Y.add(G);
      if (z8 === null) X.delete(W), J.add(G);
      else X.append(W, z8), J.delete(G);
    }
  }
  return { [qK]: true, values: X, nulls: J };
};
var C8 = /* @__PURE__ */ Symbol("anthropic.sdk.stainlessHelper");
function FJ($) {
  return typeof $ === "object" && $ !== null && C8 in $;
}
function g5($, X) {
  let J = /* @__PURE__ */ new Set();
  if ($) {
    for (let Q of $) if (FJ(Q)) J.add(Q[C8]);
  }
  if (X) for (let Q of X) {
    if (FJ(Q)) J.add(Q[C8]);
    if (Array.isArray(Q.content)) {
      for (let Y of Q.content) if (FJ(Y)) J.add(Y[C8]);
    }
  }
  return Array.from(J);
}
function MJ($, X) {
  let J = g5($, X);
  if (J.length === 0) return {};
  return { "x-stainless-helper": J.join(", ") };
}
function LK($) {
  if (FJ($)) return { "x-stainless-helper": $[C8] };
  return {};
}
function jK($) {
  return $.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent);
}
var DK = Object.freeze(/* @__PURE__ */ Object.create(null));
var jM = ($ = jK) => function(J, ...Q) {
  if (J.length === 1) return J[0];
  let Y = false, W = [], z8 = J.reduce((K, V, N) => {
    var _a3, _b2, _c;
    if (/[?#]/.test(V)) Y = true;
    let O = Q[N], w = (Y ? encodeURIComponent : $)("" + O);
    if (N !== Q.length && (O == null || typeof O === "object" && O.toString === ((_c = Object.getPrototypeOf((_b2 = Object.getPrototypeOf((_a3 = O.hasOwnProperty) != null ? _a3 : DK)) != null ? _b2 : DK)) == null ? void 0 : _c.toString))) w = O + "", W.push({ start: K.length + V.length, length: w.length, error: `Value of type ${Object.prototype.toString.call(O).slice(8, -1)} is not a valid path parameter` });
    return K + V + (N === Q.length ? "" : w);
  }, ""), G = z8.split(/[?#]/, 1)[0], U = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi, H;
  while ((H = U.exec(G)) !== null) W.push({ start: H.index, length: H[0].length, error: `Value "${H[0]}" can't be safely passed as a path parameter` });
  if (W.sort((K, V) => K.start - V.start), W.length > 0) {
    let K = 0, V = W.reduce((N, O) => {
      let w = " ".repeat(O.start - K), B = "^".repeat(O.length);
      return K = O.start + O.length, N + w + B;
    }, "");
    throw new y(`Path parameters result in path with invalid segments:
${W.map((N) => N.error).join(`
`)}
${z8}
${V}`);
  }
  return z8;
};
var M$ = jM(jK);
var k8 = class extends b$ {
  list($ = {}, X) {
    let { betas: J, ...Q } = $ != null ? $ : {};
    return this._client.getAPIList("/v1/files", k6, { query: Q, ...X, headers: i([{ "anthropic-beta": [...J != null ? J : [], "files-api-2025-04-14"].toString() }, X == null ? void 0 : X.headers]) });
  }
  delete($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.delete(M$`/v1/files/${$}`, { ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "files-api-2025-04-14"].toString() }, J == null ? void 0 : J.headers]) });
  }
  download($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.get(M$`/v1/files/${$}/content`, { ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "files-api-2025-04-14"].toString(), Accept: "application/binary" }, J == null ? void 0 : J.headers]), __binaryResponse: true });
  }
  retrieveMetadata($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.get(M$`/v1/files/${$}`, { ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "files-api-2025-04-14"].toString() }, J == null ? void 0 : J.headers]) });
  }
  upload($, X) {
    let { betas: J, ...Q } = $;
    return this._client.post("/v1/files", e1({ body: Q, ...X, headers: i([{ "anthropic-beta": [...J != null ? J : [], "files-api-2025-04-14"].toString() }, LK(Q.file), X == null ? void 0 : X.headers]) }, this._client));
  }
};
var _8 = class extends b$ {
  retrieve($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.get(M$`/v1/models/${$}?beta=true`, { ...J, headers: i([{ ...(Q == null ? void 0 : Q.toString()) != null ? { "anthropic-beta": Q == null ? void 0 : Q.toString() } : void 0 }, J == null ? void 0 : J.headers]) });
  }
  list($ = {}, X) {
    let { betas: J, ...Q } = $ != null ? $ : {};
    return this._client.getAPIList("/v1/models?beta=true", k6, { query: Q, ...X, headers: i([{ ...(J == null ? void 0 : J.toString()) != null ? { "anthropic-beta": J == null ? void 0 : J.toString() } : void 0 }, X == null ? void 0 : X.headers]) });
  }
};
var AJ = { "claude-opus-4-20250514": 8192, "claude-opus-4-0": 8192, "claude-4-opus-20250514": 8192, "anthropic.claude-opus-4-20250514-v1:0": 8192, "claude-opus-4@20250514": 8192, "claude-opus-4-1-20250805": 8192, "anthropic.claude-opus-4-1-20250805-v1:0": 8192, "claude-opus-4-1@20250805": 8192 };
function FK($) {
  var _a3, _b2;
  return (_b2 = $ == null ? void 0 : $.output_format) != null ? _b2 : (_a3 = $ == null ? void 0 : $.output_config) == null ? void 0 : _a3.format;
}
function h5($, X, J) {
  let Q = FK(X);
  if (!X || !("parse" in (Q != null ? Q : {}))) return { ...$, content: $.content.map((Y) => {
    if (Y.type === "text") {
      let W = Object.defineProperty({ ...Y }, "parsed_output", { value: null, enumerable: false });
      return Object.defineProperty(W, "parsed", { get() {
        return J.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."), null;
      }, enumerable: false });
    }
    return Y;
  }), parsed_output: null };
  return u5($, X, J);
}
function u5($, X, J) {
  let Q = null, Y = $.content.map((W) => {
    if (W.type === "text") {
      let z8 = AM(X, W.text);
      if (Q === null) Q = z8;
      let G = Object.defineProperty({ ...W }, "parsed_output", { value: z8, enumerable: false });
      return Object.defineProperty(G, "parsed", { get() {
        return J.logger.warn("The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead."), z8;
      }, enumerable: false });
    }
    return W;
  });
  return { ...$, content: Y, parsed_output: Q };
}
function AM($, X) {
  let J = FK($);
  if ((J == null ? void 0 : J.type) !== "json_schema") return null;
  try {
    if ("parse" in J) return J.parse(X);
    return JSON.parse(X);
  } catch (Q) {
    throw new y(`Failed to parse structured output: ${Q}`);
  }
}
var IM = ($) => {
  let X = 0, J = [];
  while (X < $.length) {
    let Q = $[X];
    if (Q === "\\") {
      X++;
      continue;
    }
    if (Q === "{") {
      J.push({ type: "brace", value: "{" }), X++;
      continue;
    }
    if (Q === "}") {
      J.push({ type: "brace", value: "}" }), X++;
      continue;
    }
    if (Q === "[") {
      J.push({ type: "paren", value: "[" }), X++;
      continue;
    }
    if (Q === "]") {
      J.push({ type: "paren", value: "]" }), X++;
      continue;
    }
    if (Q === ":") {
      J.push({ type: "separator", value: ":" }), X++;
      continue;
    }
    if (Q === ",") {
      J.push({ type: "delimiter", value: "," }), X++;
      continue;
    }
    if (Q === '"') {
      let G = "", U = false;
      Q = $[++X];
      while (Q !== '"') {
        if (X === $.length) {
          U = true;
          break;
        }
        if (Q === "\\") {
          if (X++, X === $.length) {
            U = true;
            break;
          }
          G += Q + $[X], Q = $[++X];
        } else G += Q, Q = $[++X];
      }
      if (Q = $[++X], !U) J.push({ type: "string", value: G });
      continue;
    }
    if (Q && /\s/.test(Q)) {
      X++;
      continue;
    }
    let W = /[0-9]/;
    if (Q && W.test(Q) || Q === "-" || Q === ".") {
      let G = "";
      if (Q === "-") G += Q, Q = $[++X];
      while (Q && W.test(Q) || Q === ".") G += Q, Q = $[++X];
      J.push({ type: "number", value: G });
      continue;
    }
    let z8 = /[a-z]/i;
    if (Q && z8.test(Q)) {
      let G = "";
      while (Q && z8.test(Q)) {
        if (X === $.length) break;
        G += Q, Q = $[++X];
      }
      if (G == "true" || G == "false" || G === "null") J.push({ type: "name", value: G });
      else {
        X++;
        continue;
      }
      continue;
    }
    X++;
  }
  return J;
};
var $0 = ($) => {
  if ($.length === 0) return $;
  let X = $[$.length - 1];
  switch (X.type) {
    case "separator":
      return $ = $.slice(0, $.length - 1), $0($);
      break;
    case "number":
      let J = X.value[X.value.length - 1];
      if (J === "." || J === "-") return $ = $.slice(0, $.length - 1), $0($);
    case "string":
      let Q = $[$.length - 2];
      if ((Q == null ? void 0 : Q.type) === "delimiter") return $ = $.slice(0, $.length - 1), $0($);
      else if ((Q == null ? void 0 : Q.type) === "brace" && Q.value === "{") return $ = $.slice(0, $.length - 1), $0($);
      break;
    case "delimiter":
      return $ = $.slice(0, $.length - 1), $0($);
      break;
  }
  return $;
};
var bM = ($) => {
  let X = [];
  if ($.map((J) => {
    if (J.type === "brace") if (J.value === "{") X.push("}");
    else X.splice(X.lastIndexOf("}"), 1);
    if (J.type === "paren") if (J.value === "[") X.push("]");
    else X.splice(X.lastIndexOf("]"), 1);
  }), X.length > 0) X.reverse().map((J) => {
    if (J === "}") $.push({ type: "brace", value: "}" });
    else if (J === "]") $.push({ type: "paren", value: "]" });
  });
  return $;
};
var ZM = ($) => {
  let X = "";
  return $.map((J) => {
    switch (J.type) {
      case "string":
        X += '"' + J.value + '"';
        break;
      default:
        X += J.value;
        break;
    }
  }), X;
};
var IJ = ($) => JSON.parse(ZM(bM($0(IM($)))));
var M6;
var _4;
var X0;
var x8;
var bJ;
var T8;
var y8;
var ZJ;
var f8;
var U4;
var g8;
var PJ;
var RJ;
var w1;
var EJ;
var SJ;
var h8;
var m5;
var MK;
var vJ;
var l5;
var c5;
var p5;
var AK;
var IK = "__json_buf";
function bK($) {
  return $.type === "tool_use" || $.type === "server_tool_use" || $.type === "mcp_tool_use";
}
var u8 = class _u8 {
  constructor($, X) {
    var _a3;
    M6.add(this), this.messages = [], this.receivedMessages = [], _4.set(this, void 0), X0.set(this, null), this.controller = new AbortController(), x8.set(this, void 0), bJ.set(this, () => {
    }), T8.set(this, () => {
    }), y8.set(this, void 0), ZJ.set(this, () => {
    }), f8.set(this, () => {
    }), U4.set(this, {}), g8.set(this, false), PJ.set(this, false), RJ.set(this, false), w1.set(this, false), EJ.set(this, void 0), SJ.set(this, void 0), h8.set(this, void 0), vJ.set(this, (J) => {
      if (v(this, PJ, true, "f"), z4(J)) J = new g$();
      if (J instanceof g$) return v(this, RJ, true, "f"), this._emit("abort", J);
      if (J instanceof y) return this._emit("error", J);
      if (J instanceof Error) {
        let Q = new y(J.message);
        return Q.cause = J, this._emit("error", Q);
      }
      return this._emit("error", new y(String(J)));
    }), v(this, x8, new Promise((J, Q) => {
      v(this, bJ, J, "f"), v(this, T8, Q, "f");
    }), "f"), v(this, y8, new Promise((J, Q) => {
      v(this, ZJ, J, "f"), v(this, f8, Q, "f");
    }), "f"), L(this, x8, "f").catch(() => {
    }), L(this, y8, "f").catch(() => {
    }), v(this, X0, $, "f"), v(this, h8, (_a3 = X == null ? void 0 : X.logger) != null ? _a3 : console, "f");
  }
  get response() {
    return L(this, EJ, "f");
  }
  get request_id() {
    return L(this, SJ, "f");
  }
  async withResponse() {
    v(this, w1, true, "f");
    let $ = await L(this, x8, "f");
    if (!$) throw Error("Could not resolve a `Response` object");
    return { data: this, response: $, request_id: $.headers.get("request-id") };
  }
  static fromReadableStream($) {
    let X = new _u8(null);
    return X._run(() => X._fromReadableStream($)), X;
  }
  static createMessage($, X, J, { logger: Q } = {}) {
    let Y = new _u8(X, { logger: Q });
    for (let W of X.messages) Y._addMessageParam(W);
    return v(Y, X0, { ...X, stream: true }, "f"), Y._run(() => Y._createMessage($, { ...X, stream: true }, { ...J, headers: { ...J == null ? void 0 : J.headers, "X-Stainless-Helper-Method": "stream" } })), Y;
  }
  _run($) {
    $().then(() => {
      this._emitFinal(), this._emit("end");
    }, L(this, vJ, "f"));
  }
  _addMessageParam($) {
    this.messages.push($);
  }
  _addMessage($, X = true) {
    if (this.receivedMessages.push($), X) this._emit("message", $);
  }
  async _createMessage($, X, J) {
    var _a3;
    let Q = J == null ? void 0 : J.signal, Y;
    if (Q) {
      if (Q.aborted) this.controller.abort();
      Y = this.controller.abort.bind(this.controller), Q.addEventListener("abort", Y);
    }
    try {
      L(this, M6, "m", l5).call(this);
      let { response: W, data: z8 } = await $.create({ ...X, stream: true }, { ...J, signal: this.controller.signal }).withResponse();
      this._connected(W);
      for await (let G of z8) L(this, M6, "m", c5).call(this, G);
      if ((_a3 = z8.controller.signal) == null ? void 0 : _a3.aborted) throw new g$();
      L(this, M6, "m", p5).call(this);
    } finally {
      if (Q && Y) Q.removeEventListener("abort", Y);
    }
  }
  _connected($) {
    if (this.ended) return;
    v(this, EJ, $, "f"), v(this, SJ, $ == null ? void 0 : $.headers.get("request-id"), "f"), L(this, bJ, "f").call(this, $), this._emit("connect");
  }
  get ended() {
    return L(this, g8, "f");
  }
  get errored() {
    return L(this, PJ, "f");
  }
  get aborted() {
    return L(this, RJ, "f");
  }
  abort() {
    this.controller.abort();
  }
  on($, X) {
    return (L(this, U4, "f")[$] || (L(this, U4, "f")[$] = [])).push({ listener: X }), this;
  }
  off($, X) {
    let J = L(this, U4, "f")[$];
    if (!J) return this;
    let Q = J.findIndex((Y) => Y.listener === X);
    if (Q >= 0) J.splice(Q, 1);
    return this;
  }
  once($, X) {
    return (L(this, U4, "f")[$] || (L(this, U4, "f")[$] = [])).push({ listener: X, once: true }), this;
  }
  emitted($) {
    return new Promise((X, J) => {
      if (v(this, w1, true, "f"), $ !== "error") this.once("error", J);
      this.once($, X);
    });
  }
  async done() {
    v(this, w1, true, "f"), await L(this, y8, "f");
  }
  get currentMessage() {
    return L(this, _4, "f");
  }
  async finalMessage() {
    return await this.done(), L(this, M6, "m", m5).call(this);
  }
  async finalText() {
    return await this.done(), L(this, M6, "m", MK).call(this);
  }
  _emit($, ...X) {
    if (L(this, g8, "f")) return;
    if ($ === "end") v(this, g8, true, "f"), L(this, ZJ, "f").call(this);
    let J = L(this, U4, "f")[$];
    if (J) L(this, U4, "f")[$] = J.filter((Q) => !Q.once), J.forEach(({ listener: Q }) => Q(...X));
    if ($ === "abort") {
      let Q = X[0];
      if (!L(this, w1, "f") && !(J == null ? void 0 : J.length)) Promise.reject(Q);
      L(this, T8, "f").call(this, Q), L(this, f8, "f").call(this, Q), this._emit("end");
      return;
    }
    if ($ === "error") {
      let Q = X[0];
      if (!L(this, w1, "f") && !(J == null ? void 0 : J.length)) Promise.reject(Q);
      L(this, T8, "f").call(this, Q), L(this, f8, "f").call(this, Q), this._emit("end");
    }
  }
  _emitFinal() {
    if (this.receivedMessages.at(-1)) this._emit("finalMessage", L(this, M6, "m", m5).call(this));
  }
  async _fromReadableStream($, X) {
    var _a3;
    let J = X == null ? void 0 : X.signal, Q;
    if (J) {
      if (J.aborted) this.controller.abort();
      Q = this.controller.abort.bind(this.controller), J.addEventListener("abort", Q);
    }
    try {
      L(this, M6, "m", l5).call(this), this._connected(null);
      let Y = B6.fromReadableStream($, this.controller);
      for await (let W of Y) L(this, M6, "m", c5).call(this, W);
      if ((_a3 = Y.controller.signal) == null ? void 0 : _a3.aborted) throw new g$();
      L(this, M6, "m", p5).call(this);
    } finally {
      if (J && Q) J.removeEventListener("abort", Q);
    }
  }
  [(_4 = /* @__PURE__ */ new WeakMap(), X0 = /* @__PURE__ */ new WeakMap(), x8 = /* @__PURE__ */ new WeakMap(), bJ = /* @__PURE__ */ new WeakMap(), T8 = /* @__PURE__ */ new WeakMap(), y8 = /* @__PURE__ */ new WeakMap(), ZJ = /* @__PURE__ */ new WeakMap(), f8 = /* @__PURE__ */ new WeakMap(), U4 = /* @__PURE__ */ new WeakMap(), g8 = /* @__PURE__ */ new WeakMap(), PJ = /* @__PURE__ */ new WeakMap(), RJ = /* @__PURE__ */ new WeakMap(), w1 = /* @__PURE__ */ new WeakMap(), EJ = /* @__PURE__ */ new WeakMap(), SJ = /* @__PURE__ */ new WeakMap(), h8 = /* @__PURE__ */ new WeakMap(), vJ = /* @__PURE__ */ new WeakMap(), M6 = /* @__PURE__ */ new WeakSet(), m5 = function() {
    if (this.receivedMessages.length === 0) throw new y("stream ended without producing a Message with role=assistant");
    return this.receivedMessages.at(-1);
  }, MK = function() {
    if (this.receivedMessages.length === 0) throw new y("stream ended without producing a Message with role=assistant");
    let X = this.receivedMessages.at(-1).content.filter((J) => J.type === "text").map((J) => J.text);
    if (X.length === 0) throw new y("stream ended without producing a content block with type=text");
    return X.join(" ");
  }, l5 = function() {
    if (this.ended) return;
    v(this, _4, void 0, "f");
  }, c5 = function(X) {
    var _a3;
    if (this.ended) return;
    let J = L(this, M6, "m", AK).call(this, X);
    switch (this._emit("streamEvent", X, J), X.type) {
      case "content_block_delta": {
        let Q = J.content.at(-1);
        switch (X.delta.type) {
          case "text_delta": {
            if (Q.type === "text") this._emit("text", X.delta.text, Q.text || "");
            break;
          }
          case "citations_delta": {
            if (Q.type === "text") this._emit("citation", X.delta.citation, (_a3 = Q.citations) != null ? _a3 : []);
            break;
          }
          case "input_json_delta": {
            if (bK(Q) && Q.input) this._emit("inputJson", X.delta.partial_json, Q.input);
            break;
          }
          case "thinking_delta": {
            if (Q.type === "thinking") this._emit("thinking", X.delta.thinking, Q.thinking);
            break;
          }
          case "signature_delta": {
            if (Q.type === "thinking") this._emit("signature", Q.signature);
            break;
          }
          case "compaction_delta": {
            if (Q.type === "compaction" && Q.content) this._emit("compaction", Q.content);
            break;
          }
          default:
            ZK(X.delta);
        }
        break;
      }
      case "message_stop": {
        this._addMessageParam(J), this._addMessage(h5(J, L(this, X0, "f"), { logger: L(this, h8, "f") }), true);
        break;
      }
      case "content_block_stop": {
        this._emit("contentBlock", J.content.at(-1));
        break;
      }
      case "message_start": {
        v(this, _4, J, "f");
        break;
      }
      case "content_block_start":
      case "message_delta":
        break;
    }
  }, p5 = function() {
    if (this.ended) throw new y("stream has ended, this shouldn't happen");
    let X = L(this, _4, "f");
    if (!X) throw new y("request ended without sending any chunks");
    return v(this, _4, void 0, "f"), h5(X, L(this, X0, "f"), { logger: L(this, h8, "f") });
  }, AK = function(X) {
    var _a3;
    let J = L(this, _4, "f");
    if (X.type === "message_start") {
      if (J) throw new y(`Unexpected event order, got ${X.type} before receiving "message_stop"`);
      return X.message;
    }
    if (!J) throw new y(`Unexpected event order, got ${X.type} before "message_start"`);
    switch (X.type) {
      case "message_stop":
        return J;
      case "message_delta":
        if (J.container = X.delta.container, J.stop_reason = X.delta.stop_reason, J.stop_sequence = X.delta.stop_sequence, J.usage.output_tokens = X.usage.output_tokens, J.context_management = X.context_management, X.usage.input_tokens != null) J.usage.input_tokens = X.usage.input_tokens;
        if (X.usage.cache_creation_input_tokens != null) J.usage.cache_creation_input_tokens = X.usage.cache_creation_input_tokens;
        if (X.usage.cache_read_input_tokens != null) J.usage.cache_read_input_tokens = X.usage.cache_read_input_tokens;
        if (X.usage.server_tool_use != null) J.usage.server_tool_use = X.usage.server_tool_use;
        if (X.usage.iterations != null) J.usage.iterations = X.usage.iterations;
        return J;
      case "content_block_start":
        return J.content.push(X.content_block), J;
      case "content_block_delta": {
        let Q = J.content.at(X.index);
        switch (X.delta.type) {
          case "text_delta": {
            if ((Q == null ? void 0 : Q.type) === "text") J.content[X.index] = { ...Q, text: (Q.text || "") + X.delta.text };
            break;
          }
          case "citations_delta": {
            if ((Q == null ? void 0 : Q.type) === "text") J.content[X.index] = { ...Q, citations: [...(_a3 = Q.citations) != null ? _a3 : [], X.delta.citation] };
            break;
          }
          case "input_json_delta": {
            if (Q && bK(Q)) {
              let Y = Q[IK] || "";
              Y += X.delta.partial_json;
              let W = { ...Q };
              if (Object.defineProperty(W, IK, { value: Y, enumerable: false, writable: true }), Y) try {
                W.input = IJ(Y);
              } catch (z8) {
                let G = new y(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${z8}. JSON: ${Y}`);
                L(this, vJ, "f").call(this, G);
              }
              J.content[X.index] = W;
            }
            break;
          }
          case "thinking_delta": {
            if ((Q == null ? void 0 : Q.type) === "thinking") J.content[X.index] = { ...Q, thinking: Q.thinking + X.delta.thinking };
            break;
          }
          case "signature_delta": {
            if ((Q == null ? void 0 : Q.type) === "thinking") J.content[X.index] = { ...Q, signature: X.delta.signature };
            break;
          }
          case "compaction_delta": {
            if ((Q == null ? void 0 : Q.type) === "compaction") J.content[X.index] = { ...Q, content: (Q.content || "") + X.delta.content };
            break;
          }
          default:
            ZK(X.delta);
        }
        return J;
      }
      case "content_block_stop":
        return J;
    }
  }, Symbol.asyncIterator)]() {
    let $ = [], X = [], J = false;
    return this.on("streamEvent", (Q) => {
      let Y = X.shift();
      if (Y) Y.resolve(Q);
      else $.push(Q);
    }), this.on("end", () => {
      J = true;
      for (let Q of X) Q.resolve(void 0);
      X.length = 0;
    }), this.on("abort", (Q) => {
      J = true;
      for (let Y of X) Y.reject(Q);
      X.length = 0;
    }), this.on("error", (Q) => {
      J = true;
      for (let Y of X) Y.reject(Q);
      X.length = 0;
    }), { next: async () => {
      if (!$.length) {
        if (J) return { value: void 0, done: true };
        return new Promise((Y, W) => X.push({ resolve: Y, reject: W })).then((Y) => Y ? { value: Y, done: false } : { value: void 0, done: true });
      }
      return { value: $.shift(), done: false };
    }, return: async () => {
      return this.abort(), { value: void 0, done: true };
    } };
  }
  toReadableStream() {
    return new B6(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream();
  }
};
function ZK($) {
}
var J0 = class extends Error {
  constructor($) {
    let X = typeof $ === "string" ? $ : $.map((J) => {
      if (J.type === "text") return J.text;
      return `[${J.type}]`;
    }).join(" ");
    super(X);
    this.name = "ToolError", this.content = $;
  }
};
var PK = 1e5;
var RK = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include:
1. Task Overview
The user's core request and success criteria
Any clarifications or constraints they specified
2. Current State
What has been completed so far
Files created, modified, or analyzed (with paths if relevant)
Key outputs or artifacts produced
3. Important Discoveries
Technical constraints or requirements uncovered
Decisions made and their rationale
Errors encountered and how they were resolved
What approaches were tried that didn't work (and why)
4. Next Steps
Specific actions needed to complete the task
Any blockers or open questions to resolve
Priority order if multiple steps remain
5. Context to Preserve
User preferences or style requirements
Domain-specific details that aren't obvious
Any promises made to the user
Be concise but complete\u2014err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task.
Wrap your summary in <summary></summary> tags.`;
var m8;
var Y0;
var B1;
var k$;
var l8;
var q6;
var H4;
var x4;
var c8;
var EK;
var d5;
function SK() {
  let $, X;
  return { promise: new Promise((Q, Y) => {
    $ = Q, X = Y;
  }), resolve: $, reject: X };
}
var p8 = class {
  constructor($, X, J) {
    m8.add(this), this.client = $, Y0.set(this, false), B1.set(this, false), k$.set(this, void 0), l8.set(this, void 0), q6.set(this, void 0), H4.set(this, void 0), x4.set(this, void 0), c8.set(this, 0), v(this, k$, { params: { ...X, messages: structuredClone(X.messages) } }, "f");
    let Y = ["BetaToolRunner", ...g5(X.tools, X.messages)].join(", ");
    v(this, l8, { ...J, headers: i([{ "x-stainless-helper": Y }, J == null ? void 0 : J.headers]) }, "f"), v(this, x4, SK(), "f");
  }
  async *[(Y0 = /* @__PURE__ */ new WeakMap(), B1 = /* @__PURE__ */ new WeakMap(), k$ = /* @__PURE__ */ new WeakMap(), l8 = /* @__PURE__ */ new WeakMap(), q6 = /* @__PURE__ */ new WeakMap(), H4 = /* @__PURE__ */ new WeakMap(), x4 = /* @__PURE__ */ new WeakMap(), c8 = /* @__PURE__ */ new WeakMap(), m8 = /* @__PURE__ */ new WeakSet(), EK = async function() {
    var _a3, _b2, _c, _d2, _e, _f;
    let X = L(this, k$, "f").params.compactionControl;
    if (!X || !X.enabled) return false;
    let J = 0;
    if (L(this, q6, "f") !== void 0) try {
      let U = await L(this, q6, "f");
      J = U.usage.input_tokens + ((_a3 = U.usage.cache_creation_input_tokens) != null ? _a3 : 0) + ((_b2 = U.usage.cache_read_input_tokens) != null ? _b2 : 0) + U.usage.output_tokens;
    } catch (e2) {
      return false;
    }
    let Q = (_c = X.contextTokenThreshold) != null ? _c : PK;
    if (J < Q) return false;
    let Y = (_d2 = X.model) != null ? _d2 : L(this, k$, "f").params.model, W = (_e = X.summaryPrompt) != null ? _e : RK, z8 = L(this, k$, "f").params.messages;
    if (z8[z8.length - 1].role === "assistant") {
      let U = z8[z8.length - 1];
      if (Array.isArray(U.content)) {
        let H = U.content.filter((K) => K.type !== "tool_use");
        if (H.length === 0) z8.pop();
        else U.content = H;
      }
    }
    let G = await this.client.beta.messages.create({ model: Y, messages: [...z8, { role: "user", content: [{ type: "text", text: W }] }], max_tokens: L(this, k$, "f").params.max_tokens }, { headers: { "x-stainless-helper": "compaction" } });
    if (((_f = G.content[0]) == null ? void 0 : _f.type) !== "text") throw new y("Expected text response for compaction");
    return L(this, k$, "f").params.messages = [{ role: "user", content: G.content }], true;
  }, Symbol.asyncIterator)]() {
    var $;
    if (L(this, Y0, "f")) throw new y("Cannot iterate over a consumed stream");
    v(this, Y0, true, "f"), v(this, B1, true, "f"), v(this, H4, void 0, "f");
    try {
      while (true) {
        let X;
        try {
          if (L(this, k$, "f").params.max_iterations && L(this, c8, "f") >= L(this, k$, "f").params.max_iterations) break;
          v(this, B1, false, "f"), v(this, H4, void 0, "f"), v(this, c8, ($ = L(this, c8, "f"), $++, $), "f"), v(this, q6, void 0, "f");
          let { max_iterations: J, compactionControl: Q, ...Y } = L(this, k$, "f").params;
          if (Y.stream) X = this.client.beta.messages.stream({ ...Y }, L(this, l8, "f")), v(this, q6, X.finalMessage(), "f"), L(this, q6, "f").catch(() => {
          }), yield X;
          else v(this, q6, this.client.beta.messages.create({ ...Y, stream: false }, L(this, l8, "f")), "f"), yield L(this, q6, "f");
          if (!await L(this, m8, "m", EK).call(this)) {
            if (!L(this, B1, "f")) {
              let { role: G, content: U } = await L(this, q6, "f");
              L(this, k$, "f").params.messages.push({ role: G, content: U });
            }
            let z8 = await L(this, m8, "m", d5).call(this, L(this, k$, "f").params.messages.at(-1));
            if (z8) L(this, k$, "f").params.messages.push(z8);
            else if (!L(this, B1, "f")) break;
          }
        } finally {
          if (X) X.abort();
        }
      }
      if (!L(this, q6, "f")) throw new y("ToolRunner concluded without a message from the server");
      L(this, x4, "f").resolve(await L(this, q6, "f"));
    } catch (X) {
      throw v(this, Y0, false, "f"), L(this, x4, "f").promise.catch(() => {
      }), L(this, x4, "f").reject(X), v(this, x4, SK(), "f"), X;
    }
  }
  setMessagesParams($) {
    if (typeof $ === "function") L(this, k$, "f").params = $(L(this, k$, "f").params);
    else L(this, k$, "f").params = $;
    v(this, B1, true, "f"), v(this, H4, void 0, "f");
  }
  async generateToolResponse() {
    var _a3;
    let $ = (_a3 = await L(this, q6, "f")) != null ? _a3 : this.params.messages.at(-1);
    if (!$) return null;
    return L(this, m8, "m", d5).call(this, $);
  }
  done() {
    return L(this, x4, "f").promise;
  }
  async runUntilDone() {
    if (!L(this, Y0, "f")) for await (let $ of this) ;
    return this.done();
  }
  get params() {
    return L(this, k$, "f").params;
  }
  pushMessages(...$) {
    this.setMessagesParams((X) => ({ ...X, messages: [...X.messages, ...$] }));
  }
  then($, X) {
    return this.runUntilDone().then($, X);
  }
};
d5 = async function(X) {
  if (L(this, H4, "f") !== void 0) return L(this, H4, "f");
  return v(this, H4, PM(L(this, k$, "f").params, X), "f"), L(this, H4, "f");
};
async function PM($, X = $.messages.at(-1)) {
  if (!X || X.role !== "assistant" || !X.content || typeof X.content === "string") return null;
  let J = X.content.filter((Y) => Y.type === "tool_use");
  if (J.length === 0) return null;
  return { role: "user", content: await Promise.all(J.map(async (Y) => {
    let W = $.tools.find((z8) => ("name" in z8 ? z8.name : z8.mcp_server_name) === Y.name);
    if (!W || !("run" in W)) return { type: "tool_result", tool_use_id: Y.id, content: `Error: Tool '${Y.name}' not found`, is_error: true };
    try {
      let z8 = Y.input;
      if ("parse" in W && W.parse) z8 = W.parse(z8);
      let G = await W.run(z8);
      return { type: "tool_result", tool_use_id: Y.id, content: G };
    } catch (z8) {
      return { type: "tool_result", tool_use_id: Y.id, content: z8 instanceof J0 ? z8.content : `Error: ${z8 instanceof Error ? z8.message : String(z8)}`, is_error: true };
    }
  })) };
}
var Q0 = class _Q0 {
  constructor($, X) {
    this.iterator = $, this.controller = X;
  }
  async *decoder() {
    let $ = new k4();
    for await (let X of this.iterator) for (let J of $.decode(X)) yield JSON.parse(J);
    for (let X of $.flush()) yield JSON.parse(X);
  }
  [Symbol.asyncIterator]() {
    return this.decoder();
  }
  static fromResponse($, X) {
    if (!$.body) {
      if (X.abort(), typeof globalThis.navigator < "u" && globalThis.navigator.product === "ReactNative") throw new y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");
      throw new y("Attempted to iterate over a response with no body");
    }
    return new _Q0(b8($.body), X);
  }
};
var d8 = class extends b$ {
  create($, X) {
    let { betas: J, ...Q } = $;
    return this._client.post("/v1/messages/batches?beta=true", { body: Q, ...X, headers: i([{ "anthropic-beta": [...J != null ? J : [], "message-batches-2024-09-24"].toString() }, X == null ? void 0 : X.headers]) });
  }
  retrieve($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.get(M$`/v1/messages/batches/${$}?beta=true`, { ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "message-batches-2024-09-24"].toString() }, J == null ? void 0 : J.headers]) });
  }
  list($ = {}, X) {
    let { betas: J, ...Q } = $ != null ? $ : {};
    return this._client.getAPIList("/v1/messages/batches?beta=true", k6, { query: Q, ...X, headers: i([{ "anthropic-beta": [...J != null ? J : [], "message-batches-2024-09-24"].toString() }, X == null ? void 0 : X.headers]) });
  }
  delete($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.delete(M$`/v1/messages/batches/${$}?beta=true`, { ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "message-batches-2024-09-24"].toString() }, J == null ? void 0 : J.headers]) });
  }
  cancel($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.post(M$`/v1/messages/batches/${$}/cancel?beta=true`, { ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "message-batches-2024-09-24"].toString() }, J == null ? void 0 : J.headers]) });
  }
  async results($, X = {}, J) {
    let Q = await this.retrieve($);
    if (!Q.results_url) throw new y(`No batch \`results_url\`; Has it finished processing? ${Q.processing_status} - ${Q.id}`);
    let { betas: Y } = X != null ? X : {};
    return this._client.get(Q.results_url, { ...J, headers: i([{ "anthropic-beta": [...Y != null ? Y : [], "message-batches-2024-09-24"].toString(), Accept: "application/binary" }, J == null ? void 0 : J.headers]), stream: true, __binaryResponse: true })._thenUnwrap((W, z8) => Q0.fromResponse(z8.response, z8.controller));
  }
};
var vK = { "claude-1.3": "November 6th, 2024", "claude-1.3-100k": "November 6th, 2024", "claude-instant-1.1": "November 6th, 2024", "claude-instant-1.1-100k": "November 6th, 2024", "claude-instant-1.2": "November 6th, 2024", "claude-3-sonnet-20240229": "July 21st, 2025", "claude-3-opus-20240229": "January 5th, 2026", "claude-2.1": "July 21st, 2025", "claude-2.0": "July 21st, 2025", "claude-3-7-sonnet-latest": "February 19th, 2026", "claude-3-7-sonnet-20250219": "February 19th, 2026" };
var EM = ["claude-opus-4-6"];
var T4 = class extends b$ {
  constructor() {
    super(...arguments);
    this.batches = new d8(this._client);
  }
  create($, X) {
    var _a3, _b2;
    let J = CK($), { betas: Q, ...Y } = J;
    if (Y.model in vK) console.warn(`The model '${Y.model}' is deprecated and will reach end-of-life on ${vK[Y.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
    if (Y.model in EM && Y.thinking && Y.thinking.type === "enabled") console.warn(`Using Claude with ${Y.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
    let W = this._client._options.timeout;
    if (!Y.stream && W == null) {
      let G = (_a3 = AJ[Y.model]) != null ? _a3 : void 0;
      W = this._client.calculateNonstreamingTimeout(Y.max_tokens, G);
    }
    let z8 = MJ(Y.tools, Y.messages);
    return this._client.post("/v1/messages?beta=true", { body: Y, timeout: W != null ? W : 6e5, ...X, headers: i([{ ...(Q == null ? void 0 : Q.toString()) != null ? { "anthropic-beta": Q == null ? void 0 : Q.toString() } : void 0 }, z8, X == null ? void 0 : X.headers]), stream: (_b2 = J.stream) != null ? _b2 : false });
  }
  parse($, X) {
    var _a3;
    return X = { ...X, headers: i([{ "anthropic-beta": [...(_a3 = $.betas) != null ? _a3 : [], "structured-outputs-2025-12-15"].toString() }, X == null ? void 0 : X.headers]) }, this.create($, X).then((J) => {
      var _a4;
      return u5(J, $, { logger: (_a4 = this._client.logger) != null ? _a4 : console });
    });
  }
  stream($, X) {
    return u8.createMessage(this, $, X);
  }
  countTokens($, X) {
    let J = CK($), { betas: Q, ...Y } = J;
    return this._client.post("/v1/messages/count_tokens?beta=true", { body: Y, ...X, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "token-counting-2024-11-01"].toString() }, X == null ? void 0 : X.headers]) });
  }
  toolRunner($, X) {
    return new p8(this._client, $, X);
  }
};
function CK($) {
  var _a3;
  if (!$.output_format) return $;
  if ((_a3 = $.output_config) == null ? void 0 : _a3.format) throw new y("Both output_format and output_config.format were provided. Please use only output_config.format (output_format is deprecated).");
  let { output_format: X, ...J } = $;
  return { ...J, output_config: { ...$.output_config, format: X } };
}
T4.Batches = d8;
T4.BetaToolRunner = p8;
T4.ToolError = J0;
var i8 = class extends b$ {
  create($, X = {}, J) {
    let { betas: Q, ...Y } = X != null ? X : {};
    return this._client.post(M$`/v1/skills/${$}/versions?beta=true`, e1({ body: Y, ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "skills-2025-10-02"].toString() }, J == null ? void 0 : J.headers]) }, this._client));
  }
  retrieve($, X, J) {
    let { skill_id: Q, betas: Y } = X;
    return this._client.get(M$`/v1/skills/${Q}/versions/${$}?beta=true`, { ...J, headers: i([{ "anthropic-beta": [...Y != null ? Y : [], "skills-2025-10-02"].toString() }, J == null ? void 0 : J.headers]) });
  }
  list($, X = {}, J) {
    let { betas: Q, ...Y } = X != null ? X : {};
    return this._client.getAPIList(M$`/v1/skills/${$}/versions?beta=true`, S8, { query: Y, ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "skills-2025-10-02"].toString() }, J == null ? void 0 : J.headers]) });
  }
  delete($, X, J) {
    let { skill_id: Q, betas: Y } = X;
    return this._client.delete(M$`/v1/skills/${Q}/versions/${$}?beta=true`, { ...J, headers: i([{ "anthropic-beta": [...Y != null ? Y : [], "skills-2025-10-02"].toString() }, J == null ? void 0 : J.headers]) });
  }
};
var W0 = class extends b$ {
  constructor() {
    super(...arguments);
    this.versions = new i8(this._client);
  }
  create($ = {}, X) {
    let { betas: J, ...Q } = $ != null ? $ : {};
    return this._client.post("/v1/skills?beta=true", e1({ body: Q, ...X, headers: i([{ "anthropic-beta": [...J != null ? J : [], "skills-2025-10-02"].toString() }, X == null ? void 0 : X.headers]) }, this._client, false));
  }
  retrieve($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.get(M$`/v1/skills/${$}?beta=true`, { ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "skills-2025-10-02"].toString() }, J == null ? void 0 : J.headers]) });
  }
  list($ = {}, X) {
    let { betas: J, ...Q } = $ != null ? $ : {};
    return this._client.getAPIList("/v1/skills?beta=true", S8, { query: Q, ...X, headers: i([{ "anthropic-beta": [...J != null ? J : [], "skills-2025-10-02"].toString() }, X == null ? void 0 : X.headers]) });
  }
  delete($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.delete(M$`/v1/skills/${$}?beta=true`, { ...J, headers: i([{ "anthropic-beta": [...Q != null ? Q : [], "skills-2025-10-02"].toString() }, J == null ? void 0 : J.headers]) });
  }
};
W0.Versions = i8;
var r6 = class extends b$ {
  constructor() {
    super(...arguments);
    this.models = new _8(this._client), this.messages = new T4(this._client), this.files = new k8(this._client), this.skills = new W0(this._client);
  }
};
r6.Models = _8;
r6.Messages = T4;
r6.Files = k8;
r6.Skills = W0;
var z0 = class extends b$ {
  create($, X) {
    var _a3, _b2;
    let { betas: J, ...Q } = $;
    return this._client.post("/v1/complete", { body: Q, timeout: (_a3 = this._client._options.timeout) != null ? _a3 : 6e5, ...X, headers: i([{ ...(J == null ? void 0 : J.toString()) != null ? { "anthropic-beta": J == null ? void 0 : J.toString() } : void 0 }, X == null ? void 0 : X.headers]), stream: (_b2 = $.stream) != null ? _b2 : false });
  }
};
function kK($) {
  var _a3;
  return (_a3 = $ == null ? void 0 : $.output_config) == null ? void 0 : _a3.format;
}
function i5($, X, J) {
  let Q = kK(X);
  if (!X || !("parse" in (Q != null ? Q : {}))) return { ...$, content: $.content.map((Y) => {
    if (Y.type === "text") return Object.defineProperty({ ...Y }, "parsed_output", { value: null, enumerable: false });
    return Y;
  }), parsed_output: null };
  return n5($, X, J);
}
function n5($, X, J) {
  let Q = null, Y = $.content.map((W) => {
    if (W.type === "text") {
      let z8 = kM(X, W.text);
      if (Q === null) Q = z8;
      return Object.defineProperty({ ...W }, "parsed_output", { value: z8, enumerable: false });
    }
    return W;
  });
  return { ...$, content: Y, parsed_output: Q };
}
function kM($, X) {
  let J = kK($);
  if ((J == null ? void 0 : J.type) !== "json_schema") return null;
  try {
    if ("parse" in J) return J.parse(X);
    return JSON.parse(X);
  } catch (Q) {
    throw new y(`Failed to parse structured output: ${Q}`);
  }
}
var A6;
var y4;
var G0;
var n8;
var CJ;
var r8;
var o8;
var kJ;
var t8;
var K4;
var a8;
var _J;
var xJ;
var q1;
var TJ;
var yJ;
var s8;
var r5;
var _K;
var o5;
var t5;
var a5;
var s5;
var xK;
var TK = "__json_buf";
function yK($) {
  return $.type === "tool_use" || $.type === "server_tool_use";
}
var e8 = class _e8 {
  constructor($, X) {
    var _a3;
    A6.add(this), this.messages = [], this.receivedMessages = [], y4.set(this, void 0), G0.set(this, null), this.controller = new AbortController(), n8.set(this, void 0), CJ.set(this, () => {
    }), r8.set(this, () => {
    }), o8.set(this, void 0), kJ.set(this, () => {
    }), t8.set(this, () => {
    }), K4.set(this, {}), a8.set(this, false), _J.set(this, false), xJ.set(this, false), q1.set(this, false), TJ.set(this, void 0), yJ.set(this, void 0), s8.set(this, void 0), o5.set(this, (J) => {
      if (v(this, _J, true, "f"), z4(J)) J = new g$();
      if (J instanceof g$) return v(this, xJ, true, "f"), this._emit("abort", J);
      if (J instanceof y) return this._emit("error", J);
      if (J instanceof Error) {
        let Q = new y(J.message);
        return Q.cause = J, this._emit("error", Q);
      }
      return this._emit("error", new y(String(J)));
    }), v(this, n8, new Promise((J, Q) => {
      v(this, CJ, J, "f"), v(this, r8, Q, "f");
    }), "f"), v(this, o8, new Promise((J, Q) => {
      v(this, kJ, J, "f"), v(this, t8, Q, "f");
    }), "f"), L(this, n8, "f").catch(() => {
    }), L(this, o8, "f").catch(() => {
    }), v(this, G0, $, "f"), v(this, s8, (_a3 = X == null ? void 0 : X.logger) != null ? _a3 : console, "f");
  }
  get response() {
    return L(this, TJ, "f");
  }
  get request_id() {
    return L(this, yJ, "f");
  }
  async withResponse() {
    v(this, q1, true, "f");
    let $ = await L(this, n8, "f");
    if (!$) throw Error("Could not resolve a `Response` object");
    return { data: this, response: $, request_id: $.headers.get("request-id") };
  }
  static fromReadableStream($) {
    let X = new _e8(null);
    return X._run(() => X._fromReadableStream($)), X;
  }
  static createMessage($, X, J, { logger: Q } = {}) {
    let Y = new _e8(X, { logger: Q });
    for (let W of X.messages) Y._addMessageParam(W);
    return v(Y, G0, { ...X, stream: true }, "f"), Y._run(() => Y._createMessage($, { ...X, stream: true }, { ...J, headers: { ...J == null ? void 0 : J.headers, "X-Stainless-Helper-Method": "stream" } })), Y;
  }
  _run($) {
    $().then(() => {
      this._emitFinal(), this._emit("end");
    }, L(this, o5, "f"));
  }
  _addMessageParam($) {
    this.messages.push($);
  }
  _addMessage($, X = true) {
    if (this.receivedMessages.push($), X) this._emit("message", $);
  }
  async _createMessage($, X, J) {
    var _a3;
    let Q = J == null ? void 0 : J.signal, Y;
    if (Q) {
      if (Q.aborted) this.controller.abort();
      Y = this.controller.abort.bind(this.controller), Q.addEventListener("abort", Y);
    }
    try {
      L(this, A6, "m", t5).call(this);
      let { response: W, data: z8 } = await $.create({ ...X, stream: true }, { ...J, signal: this.controller.signal }).withResponse();
      this._connected(W);
      for await (let G of z8) L(this, A6, "m", a5).call(this, G);
      if ((_a3 = z8.controller.signal) == null ? void 0 : _a3.aborted) throw new g$();
      L(this, A6, "m", s5).call(this);
    } finally {
      if (Q && Y) Q.removeEventListener("abort", Y);
    }
  }
  _connected($) {
    if (this.ended) return;
    v(this, TJ, $, "f"), v(this, yJ, $ == null ? void 0 : $.headers.get("request-id"), "f"), L(this, CJ, "f").call(this, $), this._emit("connect");
  }
  get ended() {
    return L(this, a8, "f");
  }
  get errored() {
    return L(this, _J, "f");
  }
  get aborted() {
    return L(this, xJ, "f");
  }
  abort() {
    this.controller.abort();
  }
  on($, X) {
    return (L(this, K4, "f")[$] || (L(this, K4, "f")[$] = [])).push({ listener: X }), this;
  }
  off($, X) {
    let J = L(this, K4, "f")[$];
    if (!J) return this;
    let Q = J.findIndex((Y) => Y.listener === X);
    if (Q >= 0) J.splice(Q, 1);
    return this;
  }
  once($, X) {
    return (L(this, K4, "f")[$] || (L(this, K4, "f")[$] = [])).push({ listener: X, once: true }), this;
  }
  emitted($) {
    return new Promise((X, J) => {
      if (v(this, q1, true, "f"), $ !== "error") this.once("error", J);
      this.once($, X);
    });
  }
  async done() {
    v(this, q1, true, "f"), await L(this, o8, "f");
  }
  get currentMessage() {
    return L(this, y4, "f");
  }
  async finalMessage() {
    return await this.done(), L(this, A6, "m", r5).call(this);
  }
  async finalText() {
    return await this.done(), L(this, A6, "m", _K).call(this);
  }
  _emit($, ...X) {
    if (L(this, a8, "f")) return;
    if ($ === "end") v(this, a8, true, "f"), L(this, kJ, "f").call(this);
    let J = L(this, K4, "f")[$];
    if (J) L(this, K4, "f")[$] = J.filter((Q) => !Q.once), J.forEach(({ listener: Q }) => Q(...X));
    if ($ === "abort") {
      let Q = X[0];
      if (!L(this, q1, "f") && !(J == null ? void 0 : J.length)) Promise.reject(Q);
      L(this, r8, "f").call(this, Q), L(this, t8, "f").call(this, Q), this._emit("end");
      return;
    }
    if ($ === "error") {
      let Q = X[0];
      if (!L(this, q1, "f") && !(J == null ? void 0 : J.length)) Promise.reject(Q);
      L(this, r8, "f").call(this, Q), L(this, t8, "f").call(this, Q), this._emit("end");
    }
  }
  _emitFinal() {
    if (this.receivedMessages.at(-1)) this._emit("finalMessage", L(this, A6, "m", r5).call(this));
  }
  async _fromReadableStream($, X) {
    var _a3;
    let J = X == null ? void 0 : X.signal, Q;
    if (J) {
      if (J.aborted) this.controller.abort();
      Q = this.controller.abort.bind(this.controller), J.addEventListener("abort", Q);
    }
    try {
      L(this, A6, "m", t5).call(this), this._connected(null);
      let Y = B6.fromReadableStream($, this.controller);
      for await (let W of Y) L(this, A6, "m", a5).call(this, W);
      if ((_a3 = Y.controller.signal) == null ? void 0 : _a3.aborted) throw new g$();
      L(this, A6, "m", s5).call(this);
    } finally {
      if (J && Q) J.removeEventListener("abort", Q);
    }
  }
  [(y4 = /* @__PURE__ */ new WeakMap(), G0 = /* @__PURE__ */ new WeakMap(), n8 = /* @__PURE__ */ new WeakMap(), CJ = /* @__PURE__ */ new WeakMap(), r8 = /* @__PURE__ */ new WeakMap(), o8 = /* @__PURE__ */ new WeakMap(), kJ = /* @__PURE__ */ new WeakMap(), t8 = /* @__PURE__ */ new WeakMap(), K4 = /* @__PURE__ */ new WeakMap(), a8 = /* @__PURE__ */ new WeakMap(), _J = /* @__PURE__ */ new WeakMap(), xJ = /* @__PURE__ */ new WeakMap(), q1 = /* @__PURE__ */ new WeakMap(), TJ = /* @__PURE__ */ new WeakMap(), yJ = /* @__PURE__ */ new WeakMap(), s8 = /* @__PURE__ */ new WeakMap(), o5 = /* @__PURE__ */ new WeakMap(), A6 = /* @__PURE__ */ new WeakSet(), r5 = function() {
    if (this.receivedMessages.length === 0) throw new y("stream ended without producing a Message with role=assistant");
    return this.receivedMessages.at(-1);
  }, _K = function() {
    if (this.receivedMessages.length === 0) throw new y("stream ended without producing a Message with role=assistant");
    let X = this.receivedMessages.at(-1).content.filter((J) => J.type === "text").map((J) => J.text);
    if (X.length === 0) throw new y("stream ended without producing a content block with type=text");
    return X.join(" ");
  }, t5 = function() {
    if (this.ended) return;
    v(this, y4, void 0, "f");
  }, a5 = function(X) {
    var _a3;
    if (this.ended) return;
    let J = L(this, A6, "m", xK).call(this, X);
    switch (this._emit("streamEvent", X, J), X.type) {
      case "content_block_delta": {
        let Q = J.content.at(-1);
        switch (X.delta.type) {
          case "text_delta": {
            if (Q.type === "text") this._emit("text", X.delta.text, Q.text || "");
            break;
          }
          case "citations_delta": {
            if (Q.type === "text") this._emit("citation", X.delta.citation, (_a3 = Q.citations) != null ? _a3 : []);
            break;
          }
          case "input_json_delta": {
            if (yK(Q) && Q.input) this._emit("inputJson", X.delta.partial_json, Q.input);
            break;
          }
          case "thinking_delta": {
            if (Q.type === "thinking") this._emit("thinking", X.delta.thinking, Q.thinking);
            break;
          }
          case "signature_delta": {
            if (Q.type === "thinking") this._emit("signature", Q.signature);
            break;
          }
          default:
            fK(X.delta);
        }
        break;
      }
      case "message_stop": {
        this._addMessageParam(J), this._addMessage(i5(J, L(this, G0, "f"), { logger: L(this, s8, "f") }), true);
        break;
      }
      case "content_block_stop": {
        this._emit("contentBlock", J.content.at(-1));
        break;
      }
      case "message_start": {
        v(this, y4, J, "f");
        break;
      }
      case "content_block_start":
      case "message_delta":
        break;
    }
  }, s5 = function() {
    if (this.ended) throw new y("stream has ended, this shouldn't happen");
    let X = L(this, y4, "f");
    if (!X) throw new y("request ended without sending any chunks");
    return v(this, y4, void 0, "f"), i5(X, L(this, G0, "f"), { logger: L(this, s8, "f") });
  }, xK = function(X) {
    var _a3;
    let J = L(this, y4, "f");
    if (X.type === "message_start") {
      if (J) throw new y(`Unexpected event order, got ${X.type} before receiving "message_stop"`);
      return X.message;
    }
    if (!J) throw new y(`Unexpected event order, got ${X.type} before "message_start"`);
    switch (X.type) {
      case "message_stop":
        return J;
      case "message_delta":
        if (J.stop_reason = X.delta.stop_reason, J.stop_sequence = X.delta.stop_sequence, J.usage.output_tokens = X.usage.output_tokens, X.usage.input_tokens != null) J.usage.input_tokens = X.usage.input_tokens;
        if (X.usage.cache_creation_input_tokens != null) J.usage.cache_creation_input_tokens = X.usage.cache_creation_input_tokens;
        if (X.usage.cache_read_input_tokens != null) J.usage.cache_read_input_tokens = X.usage.cache_read_input_tokens;
        if (X.usage.server_tool_use != null) J.usage.server_tool_use = X.usage.server_tool_use;
        return J;
      case "content_block_start":
        return J.content.push({ ...X.content_block }), J;
      case "content_block_delta": {
        let Q = J.content.at(X.index);
        switch (X.delta.type) {
          case "text_delta": {
            if ((Q == null ? void 0 : Q.type) === "text") J.content[X.index] = { ...Q, text: (Q.text || "") + X.delta.text };
            break;
          }
          case "citations_delta": {
            if ((Q == null ? void 0 : Q.type) === "text") J.content[X.index] = { ...Q, citations: [...(_a3 = Q.citations) != null ? _a3 : [], X.delta.citation] };
            break;
          }
          case "input_json_delta": {
            if (Q && yK(Q)) {
              let Y = Q[TK] || "";
              Y += X.delta.partial_json;
              let W = { ...Q };
              if (Object.defineProperty(W, TK, { value: Y, enumerable: false, writable: true }), Y) W.input = IJ(Y);
              J.content[X.index] = W;
            }
            break;
          }
          case "thinking_delta": {
            if ((Q == null ? void 0 : Q.type) === "thinking") J.content[X.index] = { ...Q, thinking: Q.thinking + X.delta.thinking };
            break;
          }
          case "signature_delta": {
            if ((Q == null ? void 0 : Q.type) === "thinking") J.content[X.index] = { ...Q, signature: X.delta.signature };
            break;
          }
          default:
            fK(X.delta);
        }
        return J;
      }
      case "content_block_stop":
        return J;
    }
  }, Symbol.asyncIterator)]() {
    let $ = [], X = [], J = false;
    return this.on("streamEvent", (Q) => {
      let Y = X.shift();
      if (Y) Y.resolve(Q);
      else $.push(Q);
    }), this.on("end", () => {
      J = true;
      for (let Q of X) Q.resolve(void 0);
      X.length = 0;
    }), this.on("abort", (Q) => {
      J = true;
      for (let Y of X) Y.reject(Q);
      X.length = 0;
    }), this.on("error", (Q) => {
      J = true;
      for (let Y of X) Y.reject(Q);
      X.length = 0;
    }), { next: async () => {
      if (!$.length) {
        if (J) return { value: void 0, done: true };
        return new Promise((Y, W) => X.push({ resolve: Y, reject: W })).then((Y) => Y ? { value: Y, done: false } : { value: void 0, done: true });
      }
      return { value: $.shift(), done: false };
    }, return: async () => {
      return this.abort(), { value: void 0, done: true };
    } };
  }
  toReadableStream() {
    return new B6(this[Symbol.asyncIterator].bind(this), this.controller).toReadableStream();
  }
};
function fK($) {
}
var $X = class extends b$ {
  create($, X) {
    return this._client.post("/v1/messages/batches", { body: $, ...X });
  }
  retrieve($, X) {
    return this._client.get(M$`/v1/messages/batches/${$}`, X);
  }
  list($ = {}, X) {
    return this._client.getAPIList("/v1/messages/batches", k6, { query: $, ...X });
  }
  delete($, X) {
    return this._client.delete(M$`/v1/messages/batches/${$}`, X);
  }
  cancel($, X) {
    return this._client.post(M$`/v1/messages/batches/${$}/cancel`, X);
  }
  async results($, X) {
    let J = await this.retrieve($);
    if (!J.results_url) throw new y(`No batch \`results_url\`; Has it finished processing? ${J.processing_status} - ${J.id}`);
    return this._client.get(J.results_url, { ...X, headers: i([{ Accept: "application/binary" }, X == null ? void 0 : X.headers]), stream: true, __binaryResponse: true })._thenUnwrap((Q, Y) => Q0.fromResponse(Y.response, Y.controller));
  }
};
var L1 = class extends b$ {
  constructor() {
    super(...arguments);
    this.batches = new $X(this._client);
  }
  create($, X) {
    var _a3, _b2;
    if ($.model in gK) console.warn(`The model '${$.model}' is deprecated and will reach end-of-life on ${gK[$.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);
    if ($.model in xM && $.thinking && $.thinking.type === "enabled") console.warn(`Using Claude with ${$.model} and 'thinking.type=enabled' is deprecated. Use 'thinking.type=adaptive' instead which results in better model performance in our testing: https://platform.claude.com/docs/en/build-with-claude/adaptive-thinking`);
    let J = this._client._options.timeout;
    if (!$.stream && J == null) {
      let Y = (_a3 = AJ[$.model]) != null ? _a3 : void 0;
      J = this._client.calculateNonstreamingTimeout($.max_tokens, Y);
    }
    let Q = MJ($.tools, $.messages);
    return this._client.post("/v1/messages", { body: $, timeout: J != null ? J : 6e5, ...X, headers: i([Q, X == null ? void 0 : X.headers]), stream: (_b2 = $.stream) != null ? _b2 : false });
  }
  parse($, X) {
    return this.create($, X).then((J) => {
      var _a3;
      return n5(J, $, { logger: (_a3 = this._client.logger) != null ? _a3 : console });
    });
  }
  stream($, X) {
    var _a3;
    return e8.createMessage(this, $, X, { logger: (_a3 = this._client.logger) != null ? _a3 : console });
  }
  countTokens($, X) {
    return this._client.post("/v1/messages/count_tokens", { body: $, ...X });
  }
};
var gK = { "claude-1.3": "November 6th, 2024", "claude-1.3-100k": "November 6th, 2024", "claude-instant-1.1": "November 6th, 2024", "claude-instant-1.1-100k": "November 6th, 2024", "claude-instant-1.2": "November 6th, 2024", "claude-3-sonnet-20240229": "July 21st, 2025", "claude-3-opus-20240229": "January 5th, 2026", "claude-2.1": "July 21st, 2025", "claude-2.0": "July 21st, 2025", "claude-3-7-sonnet-latest": "February 19th, 2026", "claude-3-7-sonnet-20250219": "February 19th, 2026", "claude-3-5-haiku-latest": "February 19th, 2026", "claude-3-5-haiku-20241022": "February 19th, 2026" };
var xM = ["claude-opus-4-6"];
L1.Batches = $X;
var U0 = class extends b$ {
  retrieve($, X = {}, J) {
    let { betas: Q } = X != null ? X : {};
    return this._client.get(M$`/v1/models/${$}`, { ...J, headers: i([{ ...(Q == null ? void 0 : Q.toString()) != null ? { "anthropic-beta": Q == null ? void 0 : Q.toString() } : void 0 }, J == null ? void 0 : J.headers]) });
  }
  list($ = {}, X) {
    let { betas: J, ...Q } = $ != null ? $ : {};
    return this._client.getAPIList("/v1/models", k6, { query: Q, ...X, headers: i([{ ...(J == null ? void 0 : J.toString()) != null ? { "anthropic-beta": J == null ? void 0 : J.toString() } : void 0 }, X == null ? void 0 : X.headers]) });
  }
};
var XX = ($) => {
  var _a3, _b2, _c, _d2, _e, _f;
  if (typeof globalThis.process < "u") return (_c = (_b2 = (_a3 = globalThis.process.env) == null ? void 0 : _a3[$]) == null ? void 0 : _b2.trim()) != null ? _c : void 0;
  if (typeof globalThis.Deno < "u") return (_f = (_e = (_d2 = globalThis.Deno.env) == null ? void 0 : _d2.get) == null ? void 0 : _e.call(_d2, $)) == null ? void 0 : _f.trim();
  return;
};
var e5;
var $W;
var fJ;
var hK;
var uK = "\\n\\nHuman:";
var mK = "\\n\\nAssistant:";
var P$ = class {
  constructor({ baseURL: $ = XX("ANTHROPIC_BASE_URL"), apiKey: X = ((_a3) => (_a3 = XX("ANTHROPIC_API_KEY")) != null ? _a3 : null)(), authToken: J = ((_b2) => (_b2 = XX("ANTHROPIC_AUTH_TOKEN")) != null ? _b2 : null)(), ...Q } = {}) {
    var _a4, _b3, _c, _d2, _e, _f;
    e5.add(this), fJ.set(this, void 0);
    let Y = { apiKey: X, authToken: J, ...Q, baseURL: $ || "https://api.anthropic.com" };
    if (!Y.dangerouslyAllowBrowser && JK()) throw new y(`It looks like you're running in a browser-like environment.

This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,

new Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);
    this.baseURL = Y.baseURL, this.timeout = (_a4 = Y.timeout) != null ? _a4 : $W.DEFAULT_TIMEOUT, this.logger = (_b3 = Y.logger) != null ? _b3 : console;
    let W = "warn";
    this.logLevel = W, this.logLevel = (_d2 = (_c = C5(Y.logLevel, "ClientOptions.logLevel", this)) != null ? _c : C5(XX("ANTHROPIC_LOG"), "process.env['ANTHROPIC_LOG']", this)) != null ? _d2 : W, this.fetchOptions = Y.fetchOptions, this.maxRetries = (_e = Y.maxRetries) != null ? _e : 2, this.fetch = (_f = Y.fetch) != null ? _f : QK(), v(this, fJ, zK, "f"), this._options = Y, this.apiKey = typeof X === "string" ? X : null, this.authToken = J;
  }
  withOptions($) {
    return new this.constructor({ ...this._options, baseURL: this.baseURL, maxRetries: this.maxRetries, timeout: this.timeout, logger: this.logger, logLevel: this.logLevel, fetch: this.fetch, fetchOptions: this.fetchOptions, apiKey: this.apiKey, authToken: this.authToken, ...$ });
  }
  defaultQuery() {
    return this._options.defaultQuery;
  }
  validateHeaders({ values: $, nulls: X }) {
    if ($.get("x-api-key") || $.get("authorization")) return;
    if (this.apiKey && $.get("x-api-key")) return;
    if (X.has("x-api-key")) return;
    if (this.authToken && $.get("authorization")) return;
    if (X.has("authorization")) return;
    throw Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted');
  }
  async authHeaders($) {
    return i([await this.apiKeyAuth($), await this.bearerAuth($)]);
  }
  async apiKeyAuth($) {
    if (this.apiKey == null) return;
    return i([{ "X-Api-Key": this.apiKey }]);
  }
  async bearerAuth($) {
    if (this.authToken == null) return;
    return i([{ Authorization: `Bearer ${this.authToken}` }]);
  }
  stringifyQuery($) {
    return GK($);
  }
  getUserAgent() {
    return `${this.constructor.name}/JS ${C4}`;
  }
  defaultIdempotencyKey() {
    return `stainless-node-retry-${Z5()}`;
  }
  makeStatusError($, X, J, Q) {
    return C$.generate($, X, J, Q);
  }
  buildURL($, X, J) {
    let Q = !L(this, e5, "m", hK).call(this) && J || this.baseURL, Y = oH($) ? new URL($) : new URL(Q + (Q.endsWith("/") && $.startsWith("/") ? $.slice(1) : $)), W = this.defaultQuery(), z8 = Object.fromEntries(Y.searchParams);
    if (!E5(W) || !E5(z8)) X = { ...z8, ...W, ...X };
    if (typeof X === "object" && X && !Array.isArray(X)) Y.search = this.stringifyQuery(X);
    return Y.toString();
  }
  _calculateNonstreamingTimeout($) {
    if (3600 * $ / 128e3 > 600) throw new y("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");
    return 6e5;
  }
  async prepareOptions($) {
  }
  async prepareRequest($, { url: X, options: J }) {
  }
  get($, X) {
    return this.methodRequest("get", $, X);
  }
  post($, X) {
    return this.methodRequest("post", $, X);
  }
  patch($, X) {
    return this.methodRequest("patch", $, X);
  }
  put($, X) {
    return this.methodRequest("put", $, X);
  }
  delete($, X) {
    return this.methodRequest("delete", $, X);
  }
  methodRequest($, X, J) {
    return this.request(Promise.resolve(J).then((Q) => {
      return { method: $, path: X, ...Q };
    }));
  }
  request($, X = null) {
    return new N1(this, this.makeRequest($, X, void 0));
  }
  async makeRequest($, X, J) {
    var _a3, _b2, _c;
    let Q = await $, Y = (_a3 = Q.maxRetries) != null ? _a3 : this.maxRetries;
    if (X == null) X = Y;
    await this.prepareOptions(Q);
    let { req: W, url: z8, timeout: G } = await this.buildRequest(Q, { retryCount: Y - X });
    await this.prepareRequest(W, { url: z8, options: Q });
    let U = "log_" + (Math.random() * 16777216 | 0).toString(16).padStart(6, "0"), H = J === void 0 ? "" : `, retryOf: ${J}`, K = Date.now();
    if (y$(this).debug(`[${U}] sending request`, G4({ retryOfRequestLogID: J, method: Q.method, url: z8, options: Q, headers: W.headers })), (_b2 = Q.signal) == null ? void 0 : _b2.aborted) throw new g$();
    let V = new AbortController(), N = await this.fetchWithTimeout(z8, W, G, V).catch(w8), O = Date.now();
    if (N instanceof globalThis.Error) {
      let D = `retrying, ${X} attempts remaining`;
      if ((_c = Q.signal) == null ? void 0 : _c.aborted) throw new g$();
      let j = z4(N) || /timed? ?out/i.test(String(N) + ("cause" in N ? String(N.cause) : ""));
      if (X) return y$(this).info(`[${U}] connection ${j ? "timed out" : "failed"} - ${D}`), y$(this).debug(`[${U}] connection ${j ? "timed out" : "failed"} (${D})`, G4({ retryOfRequestLogID: J, url: z8, durationMs: O - K, message: N.message })), this.retryRequest(Q, X, J != null ? J : U);
      if (y$(this).info(`[${U}] connection ${j ? "timed out" : "failed"} - error; no more retries left`), y$(this).debug(`[${U}] connection ${j ? "timed out" : "failed"} (error; no more retries left)`, G4({ retryOfRequestLogID: J, url: z8, durationMs: O - K, message: N.message })), j) throw new B8();
      throw new V1({ cause: N });
    }
    let w = [...N.headers.entries()].filter(([D]) => D === "request-id").map(([D, j]) => ", " + D + ": " + JSON.stringify(j)).join(""), B = `[${U}${H}${w}] ${W.method} ${z8} ${N.ok ? "succeeded" : "failed"} with status ${N.status} in ${O - K}ms`;
    if (!N.ok) {
      let D = await this.shouldRetry(N);
      if (X && D) {
        let U$ = `retrying, ${X} attempts remaining`;
        return await WK(N.body), y$(this).info(`${B} - ${U$}`), y$(this).debug(`[${U}] response error (${U$})`, G4({ retryOfRequestLogID: J, url: N.url, status: N.status, headers: N.headers, durationMs: O - K })), this.retryRequest(Q, X, J != null ? J : U, N.headers);
      }
      let j = D ? "error; no more retries left" : "error; not retryable";
      y$(this).info(`${B} - ${j}`);
      let A = await N.text().catch((U$) => w8(U$).message), I = NJ(A), x = I ? void 0 : A;
      throw y$(this).debug(`[${U}] response error (${j})`, G4({ retryOfRequestLogID: J, url: N.url, status: N.status, headers: N.headers, message: x, durationMs: Date.now() - K })), this.makeStatusError(N.status, I, x, N.headers);
    }
    return y$(this).info(B), y$(this).debug(`[${U}] response start`, G4({ retryOfRequestLogID: J, url: N.url, status: N.status, headers: N.headers, durationMs: O - K })), { response: N, options: Q, controller: V, requestLogID: U, retryOfRequestLogID: J, startTime: K };
  }
  getAPIList($, X, J) {
    return this.requestAPIList(X, J && "then" in J ? J.then((Q) => ({ method: "get", path: $, ...Q })) : { method: "get", path: $, ...J });
  }
  requestAPIList($, X) {
    let J = this.makeRequest(X, null, void 0);
    return new DJ(this, J, $);
  }
  async fetchWithTimeout($, X, J, Q) {
    let { signal: Y, method: W, ...z8 } = X || {}, G = this._makeAbort(Q);
    if (Y) Y.addEventListener("abort", G, { once: true });
    let U = setTimeout(G, J), H = globalThis.ReadableStream && z8.body instanceof globalThis.ReadableStream || typeof z8.body === "object" && z8.body !== null && Symbol.asyncIterator in z8.body, K = { signal: Q.signal, ...H ? { duplex: "half" } : {}, method: "GET", ...z8 };
    if (W) K.method = W.toUpperCase();
    try {
      return await this.fetch.call(void 0, $, K);
    } finally {
      clearTimeout(U);
    }
  }
  async shouldRetry($) {
    let X = $.headers.get("x-should-retry");
    if (X === "true") return true;
    if (X === "false") return false;
    if ($.status === 408) return true;
    if ($.status === 409) return true;
    if ($.status === 429) return true;
    if ($.status >= 500) return true;
    return false;
  }
  async retryRequest($, X, J, Q) {
    var _a3;
    let Y, W = Q == null ? void 0 : Q.get("retry-after-ms");
    if (W) {
      let G = parseFloat(W);
      if (!Number.isNaN(G)) Y = G;
    }
    let z8 = Q == null ? void 0 : Q.get("retry-after");
    if (z8 && !Y) {
      let G = parseFloat(z8);
      if (!Number.isNaN(G)) Y = G * 1e3;
      else Y = Date.parse(z8) - Date.now();
    }
    if (Y === void 0) {
      let G = (_a3 = $.maxRetries) != null ? _a3 : this.maxRetries;
      Y = this.calculateDefaultRetryTimeoutMillis(X, G);
    }
    return await sH(Y), this.makeRequest($, X - 1, J);
  }
  calculateDefaultRetryTimeoutMillis($, X) {
    let Y = X - $, W = Math.min(0.5 * Math.pow(2, Y), 8), z8 = 1 - Math.random() * 0.25;
    return W * z8 * 1e3;
  }
  calculateNonstreamingTimeout($, X) {
    if (36e5 * $ / 128e3 > 6e5 || X != null && $ > X) throw new y("Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");
    return 6e5;
  }
  async buildRequest($, { retryCount: X = 0 } = {}) {
    var _a3, _b2, _c;
    let J = { ...$ }, { method: Q, path: Y, query: W, defaultBaseURL: z8 } = J, G = this.buildURL(Y, W, z8);
    if ("timeout" in J) aH("timeout", J.timeout);
    J.timeout = (_a3 = J.timeout) != null ? _a3 : this.timeout;
    let { bodyHeaders: U, body: H } = this.buildBody({ options: J }), K = await this.buildHeaders({ options: $, method: Q, bodyHeaders: U, retryCount: X });
    return { req: { method: Q, headers: K, ...J.signal && { signal: J.signal }, ...globalThis.ReadableStream && H instanceof globalThis.ReadableStream && { duplex: "half" }, ...H && { body: H }, ...(_b2 = this.fetchOptions) != null ? _b2 : {}, ...(_c = J.fetchOptions) != null ? _c : {} }, url: G, timeout: J.timeout };
  }
  async buildHeaders({ options: $, method: X, bodyHeaders: J, retryCount: Q }) {
    let Y = {};
    if (this.idempotencyHeader && X !== "get") {
      if (!$.idempotencyKey) $.idempotencyKey = this.defaultIdempotencyKey();
      Y[this.idempotencyHeader] = $.idempotencyKey;
    }
    let W = i([Y, { Accept: "application/json", "User-Agent": this.getUserAgent(), "X-Stainless-Retry-Count": String(Q), ...$.timeout ? { "X-Stainless-Timeout": String(Math.trunc($.timeout / 1e3)) } : {}, ...YK(), ...this._options.dangerouslyAllowBrowser ? { "anthropic-dangerous-direct-browser-access": "true" } : void 0, "anthropic-version": "2023-06-01" }, await this.authHeaders($), this._options.defaultHeaders, J, $.headers]);
    return this.validateHeaders(W), W.values;
  }
  _makeAbort($) {
    return () => $.abort();
  }
  buildBody({ options: { body: $, headers: X } }) {
    if (!$) return { bodyHeaders: void 0, body: void 0 };
    let J = i([X]);
    if (ArrayBuffer.isView($) || $ instanceof ArrayBuffer || $ instanceof DataView || typeof $ === "string" && J.values.has("content-type") || globalThis.Blob && $ instanceof globalThis.Blob || $ instanceof FormData || $ instanceof URLSearchParams || globalThis.ReadableStream && $ instanceof globalThis.ReadableStream) return { bodyHeaders: void 0, body: $ };
    else if (typeof $ === "object" && (Symbol.asyncIterator in $ || Symbol.iterator in $ && "next" in $ && typeof $.next === "function")) return { bodyHeaders: void 0, body: OJ($) };
    else if (typeof $ === "object" && J.values.get("content-type") === "application/x-www-form-urlencoded") return { bodyHeaders: { "content-type": "application/x-www-form-urlencoded" }, body: this.stringifyQuery($) };
    else return L(this, fJ, "f").call(this, { body: $, headers: J });
  }
};
$W = P$, fJ = /* @__PURE__ */ new WeakMap(), e5 = /* @__PURE__ */ new WeakSet(), hK = function() {
  return this.baseURL !== "https://api.anthropic.com";
};
P$.Anthropic = $W;
P$.HUMAN_PROMPT = uK;
P$.AI_PROMPT = mK;
P$.DEFAULT_TIMEOUT = 6e5;
P$.AnthropicError = y;
P$.APIError = C$;
P$.APIConnectionError = V1;
P$.APIConnectionTimeoutError = B8;
P$.APIUserAbortError = g$;
P$.NotFoundError = j8;
P$.ConflictError = F8;
P$.RateLimitError = A8;
P$.BadRequestError = q8;
P$.AuthenticationError = L8;
P$.InternalServerError = I8;
P$.PermissionDeniedError = D8;
P$.UnprocessableEntityError = M8;
P$.toFile = jJ;
var D1 = class extends P$ {
  constructor() {
    super(...arguments);
    this.completions = new z0(this), this.messages = new L1(this), this.models = new U0(this), this.beta = new r6(this);
  }
};
D1.Completions = z0;
D1.Messages = L1;
D1.Models = U0;
D1.Beta = r6;
function f4($) {
  return $ instanceof Error ? $ : Error(String($));
}
function H0($) {
  return $ instanceof Error ? $.message : String($);
}
function _6($) {
  if ($ && typeof $ === "object" && "code" in $ && typeof $.code === "string") return $.code;
  return;
}
function JX($) {
  return _6($) === "ENOENT";
}
function XW($) {
  return _6($) === "EISDIR";
}
var V0;
var K0 = null;
function hM() {
  if (K0) return K0;
  if (!r$(process.env.DEBUG_CLAUDE_AGENT_SDK)) return V0 = null, K0 = Promise.resolve(), K0;
  let $ = (0, import_path3.join)(v4(), "debug");
  return V0 = (0, import_path3.join)($, `sdk-${(0, import_crypto2.randomUUID)()}.txt`), process.stderr.write(`SDK debug logs: ${V0}
`), K0 = (0, import_promises2.mkdir)($, { recursive: true }).then(() => {
  }).catch(() => {
  }), K0;
}
function Y6($) {
  if (V0 === null) return;
  let J = `${(/* @__PURE__ */ new Date()).toISOString()} ${$}
`;
  hM().then(() => {
    if (V0) (0, import_promises2.appendFile)(V0, J).catch(() => {
    });
  });
}
function mM() {
  let $ = "";
  if (typeof process < "u" && typeof process.cwd === "function" && typeof import_fs.realpathSync === "function") {
    let J = (0, import_process.cwd)();
    try {
      $ = (0, import_fs.realpathSync)(J).normalize("NFC");
    } catch (e2) {
      $ = J.normalize("NFC");
    }
  }
  return { originalCwd: $, projectRoot: $, totalCostUSD: 0, totalAPIDuration: 0, totalAPIDurationWithoutRetries: 0, totalToolDuration: 0, startTime: Date.now(), lastInteractionTime: Date.now(), totalLinesAdded: 0, totalLinesRemoved: 0, hasUnknownModelCost: false, cwd: $, modelUsage: {}, mainLoopModelOverride: void 0, initialMainLoopModel: null, modelStrings: null, isInteractive: false, hasStreamingInput: false, kairosActive: false, strictToolResultPairing: false, memoryToggledOff: false, teamMemoryServerStatus: void 0, sdkAgentProgressSummariesEnabled: false, userMsgOptIn: false, clientType: "cli", sessionSource: void 0, questionPreviewFormat: void 0, sessionIngressToken: void 0, oauthTokenFromFd: void 0, apiKeyFromFd: void 0, flagSettingsPath: void 0, flagSettingsInline: null, allowedSettingSources: ["userSettings", "projectSettings", "localSettings", "flagSettings", "policySettings"], meter: null, sessionCounter: null, locCounter: null, prCounter: null, commitCounter: null, costCounter: null, tokenCounter: null, codeEditToolDecisionCounter: null, activeTimeCounter: null, statsStore: null, sessionId: (0, import_crypto3.randomUUID)(), parentSessionId: void 0, loggerProvider: null, eventLogger: null, meterProvider: null, tracerProvider: null, agentColorMap: /* @__PURE__ */ new Map(), agentColorIndex: 0, lastAPIRequest: null, lastAPIRequestMessages: null, lastClassifierRequests: null, cachedClaudeMdContent: null, inMemoryErrorLog: [], inlinePlugins: [], chromeFlagOverride: void 0, useCoworkPlugins: false, sessionBypassPermissionsMode: false, scheduledTasksEnabled: false, sessionCronTasks: [], loopChainStartedAt: /* @__PURE__ */ Object.create(null), sessionCreatedTeams: /* @__PURE__ */ new Set(), sessionTrustAccepted: false, sessionPersistenceDisabled: false, hasExitedPlanMode: false, needsPlanModeExitAttachment: false, needsAutoModeExitAttachment: false, lspRecommendationShownThisSession: false, initJsonSchema: null, registeredHooks: null, planSlugCache: /* @__PURE__ */ new Map(), teleportedSessionInfo: null, invokedSkills: /* @__PURE__ */ new Map(), slowOperations: [], sdkBetas: void 0, sdkOAuthTokenRefreshCallback: null, mainThreadAgentType: void 0, isRemoteMode: false, replBridgeActive: false, directConnectServerUrl: void 0, activeRoutine: void 0, systemPromptSectionCache: /* @__PURE__ */ new Map(), lastEmittedDate: null, additionalDirectoriesForClaudeMd: [], allowedChannels: [], hasDevChannels: false, sessionProjectDir: null, promptCache1hAllowlist: null, afkModeHeaderLatched: null, fastModeHeaderLatched: null, cacheEditingHeaderLatched: null, thinkingClearLatched: null, promptId: null, lastMainRequestId: void 0, lastApiCompletionTimestamp: null, pendingPostCompaction: false };
}
var lM = mM();
function JW() {
  return lM.sessionId;
}
var cM = n1();
var jl = cM.subscribe;
var pM = n1();
var Fl = pM.subscribe;
var dM = n1();
var Ml = dM.subscribe;
function pK({ writeFn: $, flushIntervalMs: X = 1e3, maxBufferSize: J = 100, maxBufferBytes: Q = 1 / 0, immediateMode: Y = false }) {
  let W = [], z8 = 0, G = null, U = null;
  function H() {
    if (G) clearTimeout(G), G = null;
  }
  function K() {
    if (U) $(U.join("")), U = null;
    if (W.length === 0) return;
    $(W.join("")), W = [], z8 = 0, H();
  }
  function V() {
    if (!G) G = setTimeout(K, X);
  }
  function N() {
    if (U) {
      U.push(...W), W = [], z8 = 0, H();
      return;
    }
    let O = W;
    W = [], z8 = 0, H(), U = O, setImmediate(() => {
      let w = U;
      if (U = null, w) $(w.join(""));
    });
  }
  return { write(O) {
    if (Y) {
      $(O);
      return;
    }
    if (W.push(O), z8 += O.length, V(), W.length >= J || z8 >= Q) N();
  }, flush: K, dispose() {
    K();
  } };
}
var dK = /* @__PURE__ */ new Set();
function iK($) {
  return dK.add($), () => dK.delete($);
}
var nK = C6(($) => {
  if (!$ || $.trim() === "") return null;
  let X = $.split(",").map((W) => W.trim()).filter(Boolean);
  if (X.length === 0) return null;
  let J = X.some((W) => W.startsWith("!")), Q = X.some((W) => !W.startsWith("!"));
  if (J && Q) return null;
  let Y = X.map((W) => W.replace(/^!/, "").toLowerCase());
  return { include: J ? [] : Y, exclude: J ? Y : [], isExclusive: J };
});
function iM($) {
  let X = [], J = $.match(/^MCP server ["']([^"']+)["']/);
  if (J && J[1]) X.push("mcp"), X.push(J[1].toLowerCase());
  else {
    let W = $.match(/^([^:[]+):/);
    if (W && W[1]) X.push(W[1].trim().toLowerCase());
  }
  let Q = $.match(/^\[([^\]]+)]/);
  if (Q && Q[1]) X.push(Q[1].trim().toLowerCase());
  if ($.toLowerCase().includes("1p event:")) X.push("1p");
  let Y = $.match(/:\s*([^:]+?)(?:\s+(?:type|mode|status|event))?:/);
  if (Y && Y[1]) {
    let W = Y[1].trim().toLowerCase();
    if (W.length < 30 && !W.includes(" ")) X.push(W);
  }
  return Array.from(new Set(X));
}
function nM($, X) {
  if (!X) return true;
  if ($.length === 0) return false;
  if (X.isExclusive) return !$.some((J) => X.exclude.includes(J));
  else return $.some((J) => X.include.includes(J));
}
function rK($, X) {
  if (!X) return true;
  let J = iM($);
  return nM(J, X);
}
var J2 = { cwd() {
  return process.cwd();
}, existsSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.existsSync(${$})`, 0);
    return r.existsSync($);
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, async stat($) {
  return (0, import_promises4.stat)($);
}, async readdir($) {
  return (0, import_promises4.readdir)($, { withFileTypes: true });
}, async unlink($) {
  return (0, import_promises4.unlink)($);
}, async rmdir($) {
  return (0, import_promises4.rmdir)($);
}, async rm($, X) {
  return (0, import_promises4.rm)($, X);
}, async mkdir($, X) {
  try {
    await (0, import_promises4.mkdir)($, { recursive: true, ...X });
  } catch (J) {
    if (_6(J) !== "EEXIST") throw J;
  }
}, async readFile($, X) {
  return (0, import_promises4.readFile)($, { encoding: X.encoding });
}, async rename($, X) {
  return (0, import_promises4.rename)($, X);
}, statSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.statSync(${$})`, 0);
    return r.statSync($);
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, lstatSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.lstatSync(${$})`, 0);
    return r.lstatSync($);
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, readFileSync($, X) {
  let Q = [];
  try {
    const J = w$(Q, Z$`fs.readFileSync(${$})`, 0);
    return r.readFileSync($, { encoding: X.encoding });
  } catch (Y) {
    var W = Y, z8 = 1;
  } finally {
    B$(Q, W, z8);
  }
}, readFileBytesSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.readFileBytesSync(${$})`, 0);
    return r.readFileSync($);
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, readSync($, X) {
  let Y = [];
  try {
    const J = w$(Y, Z$`fs.readSync(${$}, ${X.length} bytes)`, 0);
    let Q = void 0;
    try {
      Q = r.openSync($, "r");
      let U = Buffer.alloc(X.length), H = r.readSync(Q, U, 0, X.length, 0);
      return { buffer: U, bytesRead: H };
    } finally {
      if (Q) r.closeSync(Q);
    }
  } catch (W) {
    var z8 = W, G = 1;
  } finally {
    B$(Y, z8, G);
  }
}, appendFileSync($, X, J) {
  let Y = [];
  try {
    const Q = w$(Y, Z$`fs.appendFileSync(${$}, ${X.length} chars)`, 0);
    if ((J == null ? void 0 : J.mode) !== void 0) try {
      let U = r.openSync($, "ax", J.mode);
      try {
        r.appendFileSync(U, X);
      } finally {
        r.closeSync(U);
      }
      return;
    } catch (U) {
      if (_6(U) !== "EEXIST") throw U;
    }
    r.appendFileSync($, X);
  } catch (W) {
    var z8 = W, G = 1;
  } finally {
    B$(Y, z8, G);
  }
}, copyFileSync($, X) {
  let Q = [];
  try {
    const J = w$(Q, Z$`fs.copyFileSync(${$} → ${X})`, 0);
    r.copyFileSync($, X);
  } catch (Y) {
    var W = Y, z8 = 1;
  } finally {
    B$(Q, W, z8);
  }
}, unlinkSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.unlinkSync(${$})`, 0);
    r.unlinkSync($);
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, renameSync($, X) {
  let Q = [];
  try {
    const J = w$(Q, Z$`fs.renameSync(${$} → ${X})`, 0);
    r.renameSync($, X);
  } catch (Y) {
    var W = Y, z8 = 1;
  } finally {
    B$(Q, W, z8);
  }
}, linkSync($, X) {
  let Q = [];
  try {
    const J = w$(Q, Z$`fs.linkSync(${$} → ${X})`, 0);
    r.linkSync($, X);
  } catch (Y) {
    var W = Y, z8 = 1;
  } finally {
    B$(Q, W, z8);
  }
}, symlinkSync($, X, J) {
  let Y = [];
  try {
    const Q = w$(Y, Z$`fs.symlinkSync(${$} → ${X})`, 0);
    r.symlinkSync($, X, J);
  } catch (W) {
    var z8 = W, G = 1;
  } finally {
    B$(Y, z8, G);
  }
}, readlinkSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.readlinkSync(${$})`, 0);
    return r.readlinkSync($);
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, realpathSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.realpathSync(${$})`, 0);
    return r.realpathSync($).normalize("NFC");
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, mkdirSync($, X) {
  let Y = [];
  try {
    const J = w$(Y, Z$`fs.mkdirSync(${$})`, 0);
    let Q = { recursive: true };
    if ((X == null ? void 0 : X.mode) !== void 0) Q.mode = X.mode;
    try {
      r.mkdirSync($, Q);
    } catch (U) {
      if (_6(U) !== "EEXIST") throw U;
    }
  } catch (W) {
    var z8 = W, G = 1;
  } finally {
    B$(Y, z8, G);
  }
}, readdirSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.readdirSync(${$})`, 0);
    return r.readdirSync($, { withFileTypes: true });
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, readdirStringSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.readdirStringSync(${$})`, 0);
    return r.readdirSync($);
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, isDirEmptySync($) {
  let Q = [];
  try {
    const X = w$(Q, Z$`fs.isDirEmptySync(${$})`, 0);
    let J = this.readdirSync($);
    return J.length === 0;
  } catch (Y) {
    var W = Y, z8 = 1;
  } finally {
    B$(Q, W, z8);
  }
}, rmdirSync($) {
  let J = [];
  try {
    const X = w$(J, Z$`fs.rmdirSync(${$})`, 0);
    r.rmdirSync($);
  } catch (Q) {
    var Y = Q, W = 1;
  } finally {
    B$(J, Y, W);
  }
}, rmSync($, X) {
  let Q = [];
  try {
    const J = w$(Q, Z$`fs.rmSync(${$})`, 0);
    r.rmSync($, X);
  } catch (Y) {
    var W = Y, z8 = 1;
  } finally {
    B$(Q, W, z8);
  }
}, createWriteStream($) {
  return r.createWriteStream($);
}, async readFileBytes($, X) {
  if (X === void 0) return (0, import_promises4.readFile)($);
  let J = await (0, import_promises4.open)($, "r");
  try {
    let { size: Q } = await J.stat(), Y = Math.min(Q, X), W = Buffer.allocUnsafe(Y), z8 = 0;
    while (z8 < Y) {
      let { bytesRead: G } = await J.read(W, z8, Y - z8, z8);
      if (G === 0) break;
      z8 += G;
    }
    return z8 < Y ? W.subarray(0, z8) : W;
  } finally {
    await J.close();
  }
} };
var Y2 = J2;
function gJ() {
  return Y2;
}
function Q2($, X) {
  if ($.destroyed) return;
  $.write(X);
}
function tK($) {
  Q2(process.stderr, $);
}
var QW = { verbose: 0, debug: 1, info: 2, warn: 3, error: 4 };
var U2 = C6(() => {
  var _a3;
  let $ = (_a3 = process.env.CLAUDE_CODE_DEBUG_LOG_LEVEL) == null ? void 0 : _a3.toLowerCase().trim();
  if ($ && Object.hasOwn(QW, $)) return $;
  return "debug";
});
var H2 = false;
function uJ() {
  return typeof process < "u" && Array.isArray(process.argv) ? process.argv : [];
}
var WW = C6(() => {
  let $ = uJ();
  return H2 || r$(process.env.DEBUG) || r$(process.env.DEBUG_SDK) || $.includes("--debug") || $.includes("-d") || eK() || $.some((X) => X.startsWith("--debug=")) || $V() !== null;
});
var K2 = C6(() => {
  let $ = uJ().find((J) => J.startsWith("--debug="));
  if (!$) return null;
  let X = $.substring(8);
  return nK(X);
});
var eK = C6(() => {
  let $ = uJ();
  return $.includes("--debug-to-stderr") || $.includes("-d2e");
});
var $V = C6(() => {
  let $ = uJ();
  for (let X = 0; X < $.length; X++) {
    let J = $[X];
    if (J.startsWith("--debug-file=")) return J.substring(13);
    if (J === "--debug-file" && X + 1 < $.length) return $[X + 1];
  }
  return null;
});
function V2($) {
  if (!WW()) return false;
  if (typeof process > "u" || typeof process.versions > "u" || typeof process.versions.node > "u") return false;
  let X = K2();
  return rK($, X);
}
var N2 = false;
var hJ = null;
var YW = Promise.resolve();
var zW = null;
function XV($) {
  return zW = (0, import_path4.join)($, `${JW()}.txt`), zW;
}
async function O2($, X, J, Q) {
  if ($) await (0, import_promises3.mkdir)(X, { recursive: true }).catch(() => {
  });
  try {
    await (0, import_promises3.appendFile)(J, Q);
  } catch (Y) {
    if (!XW(Y)) throw Y;
    await (0, import_promises3.appendFile)(XV(J), Q);
  }
  YV();
}
function w2() {
}
function B2() {
  if (!hJ) {
    let $ = null;
    hJ = pK({ writeFn: (X) => {
      let J = JV(), Q = (0, import_path4.dirname)(J), Y = $ !== Q;
      if ($ = Q, WW()) {
        if (Y) try {
          gJ().mkdirSync(Q);
        } catch (e2) {
        }
        try {
          gJ().appendFileSync(J, X);
        } catch (W) {
          if (!XW(W)) throw W;
          gJ().appendFileSync(XV(J), X);
        }
        YV();
        return;
      }
      YW = YW.then(O2.bind(null, Y, Q, J, X)).catch(w2);
    }, flushIntervalMs: 1e3, maxBufferSize: 100, immediateMode: WW() }), iK(async () => {
      hJ == null ? void 0 : hJ.dispose(), await YW;
    });
  }
  return hJ;
}
function f$($, { level: X } = { level: "debug" }) {
  if (QW[X] < QW[U2()]) return;
  if (!V2($)) return;
  if (N2 && $.includes(`
`)) $ = q$($);
  let Q = `${(/* @__PURE__ */ new Date()).toISOString()} [${X.toUpperCase()}] ${$.trim()}
`;
  if (eK()) {
    tK(Q);
    return;
  }
  B2().write(Q);
}
function JV() {
  var _a3, _b2, _c;
  return (_c = (_b2 = (_a3 = $V()) != null ? _a3 : zW) != null ? _b2 : process.env.CLAUDE_CODE_DEBUG_LOGS_DIR) != null ? _c : (0, import_path4.join)(v4(), "debug", `${JW()}.txt`);
}
var YV = C6(async () => {
  try {
    let $ = JV(), X = (0, import_path4.dirname)($), J = (0, import_path4.join)(X, "latest");
    await (0, import_promises3.unlink)(J).catch(() => {
    }), await (0, import_promises3.symlink)($, J);
  } catch (e2) {
  }
});
var tl = (() => {
  let $ = process.env.CLAUDE_CODE_SLOW_OPERATION_THRESHOLD_MS;
  if ($ !== void 0) {
    let X = Number($);
    if (!Number.isNaN(X) && X >= 0) return X;
  }
  return 1 / 0;
})();
var q2 = { [Symbol.dispose]() {
} };
function L2() {
  return q2;
}
var Z$ = L2;
function q$($, X, J) {
  let Y = [];
  try {
    const Q = w$(Y, Z$`JSON.stringify(${$})`, 0);
    return JSON.stringify($, X, J);
  } catch (W) {
    var z8 = W, G = 1;
  } finally {
    B$(Y, z8, G);
  }
}
var o$ = ($, X) => {
  let Q = [];
  try {
    const J = w$(Q, Z$`JSON.parse(${$})`, 0);
    return typeof X > "u" ? JSON.parse($) : JSON.parse($, X);
  } catch (Y) {
    var W = Y, z8 = 1;
  } finally {
    B$(Q, W, z8);
  }
};
function D2($) {
  let X = $.trim();
  return X.startsWith("{") && X.endsWith("}");
}
function QV($, X) {
  let J = { ...$ };
  if (X) {
    let Q = X.enabled === true && X.failIfUnavailable === void 0 ? { ...X, failIfUnavailable: true } : X, Y = J.settings;
    if (Y && !D2(Y)) throw Error("Cannot use both a settings file path and the sandbox option. Include the sandbox configuration in your settings file instead.");
    let W = { sandbox: Q };
    if (Y) try {
      W = { ...o$(Y), sandbox: Q };
    } catch (e2) {
    }
    J.settings = q$(W);
  }
  return J;
}
var M2 = 2e3;
var mJ = /* @__PURE__ */ new Set();
var WV = false;
function A2() {
  for (let $ of mJ) if (!$.killed) $.kill("SIGTERM");
}
function I2($) {
  if (mJ.add($), !WV) WV = true, process.on("exit", A2);
}
var QX = class {
  constructor($) {
    __publicField(this, "options");
    __publicField(this, "process");
    __publicField(this, "processStdin");
    __publicField(this, "processStdout");
    __publicField(this, "ready", false);
    __publicField(this, "abortController");
    __publicField(this, "exitError");
    __publicField(this, "exitListeners", []);
    __publicField(this, "abortHandler");
    __publicField(this, "pendingWrites", []);
    __publicField(this, "pendingEndInput", false);
    __publicField(this, "spawnResolve");
    __publicField(this, "spawnReject");
    __publicField(this, "spawnPromise");
    this.options = $;
    if (this.abortController = $.abortController || d1(), $.deferSpawn) this.spawnPromise = new Promise((X, J) => {
      this.spawnResolve = X, this.spawnReject = J;
    }), this.spawnPromise.catch(() => {
    });
    else this.initialize();
  }
  spawn() {
    var _a3;
    try {
      this.initialize();
    } catch (X) {
      throw this.spawnAbort(f4(X)), X;
    }
    let $ = this.pendingWrites;
    if (this.pendingWrites = [], this.spawnResolve) this.spawnResolve(), this.spawnResolve = void 0, this.spawnReject = void 0;
    for (let X of $) this.write(X);
    if (this.pendingEndInput) this.pendingEndInput = false, (_a3 = this.processStdin) == null ? void 0 : _a3.end();
  }
  spawnAbort($) {
    if (this.spawnReject) this.spawnReject($), this.spawnReject = void 0, this.spawnResolve = void 0, this.pendingWrites = [];
  }
  updateEnv($) {
    if (this.options.env) Object.assign(this.options.env, $);
    else this.options.env = { ...$ };
  }
  getDefaultExecutable() {
    return i1() ? "bun" : "node";
  }
  spawnLocalProcess($) {
    let { command: X, args: J, cwd: Q, env: Y, signal: W } = $, z8 = r$(Y.DEBUG_CLAUDE_AGENT_SDK) || this.options.stderr ? "pipe" : "ignore", G = (0, import_child_process2.spawn)(X, J, { cwd: Q, stdio: ["pipe", "pipe", z8], signal: W, env: Y, windowsHide: true });
    if (r$(Y.DEBUG_CLAUDE_AGENT_SDK) || this.options.stderr) G.stderr.on("data", (H) => {
      let K = H.toString();
      if (Y6(K), this.options.stderr) this.options.stderr(K);
    });
    return { stdin: G.stdin, stdout: G.stdout, get killed() {
      return G.killed;
    }, get exitCode() {
      return G.exitCode;
    }, kill: G.kill.bind(G), on: G.on.bind(G), once: G.once.bind(G), off: G.off.bind(G) };
  }
  initialize() {
    try {
      let { additionalDirectories: $ = [], agent: X, betas: J, cwd: Q, executable: Y = this.getDefaultExecutable(), executableArgs: W = [], extraArgs: z8 = {}, pathToClaudeCodeExecutable: G, env: U = { ...process.env }, thinkingConfig: H, maxTurns: K, maxBudgetUsd: V, taskBudget: N, model: O, fallbackModel: w, jsonSchema: B, permissionMode: D, allowDangerouslySkipPermissions: j, permissionPromptToolName: A, continueConversation: I, resume: x, settingSources: T, allowedTools: U$ = [], disallowedTools: T$ = [], tools: n$, mcpServers: X4, strictMcpConfig: X6, canUseTool: U1, includePartialMessages: l1, plugins: J4, sandbox: z82 } = this.options, p = ["--output-format", "stream-json", "--verbose", "--input-format", "stream-json"];
      if (H) {
        switch (H.type) {
          case "enabled":
            if (H.budgetTokens === void 0) p.push("--thinking", "adaptive");
            else p.push("--max-thinking-tokens", H.budgetTokens.toString());
            break;
          case "disabled":
            p.push("--thinking", "disabled");
            break;
          case "adaptive":
            p.push("--thinking", "adaptive");
            break;
        }
        if (H.type !== "disabled" && H.display) p.push("--thinking-display", H.display);
      }
      if (this.options.effort) p.push("--effort", this.options.effort);
      if (K) p.push("--max-turns", K.toString());
      if (V !== void 0) p.push("--max-budget-usd", V.toString());
      if (N) p.push("--task-budget", N.total.toString());
      if (O) p.push("--model", O);
      if (X) p.push("--agent", X);
      if (J && J.length > 0) p.push("--betas", J.join(","));
      if (B) p.push("--json-schema", q$(B));
      if (this.options.debugFile) p.push("--debug-file", this.options.debugFile);
      else if (this.options.debug) p.push("--debug");
      if (r$(U.DEBUG_CLAUDE_AGENT_SDK)) p.push("--debug-to-stderr");
      if (U1) {
        if (A) throw Error("canUseTool callback cannot be used with permissionPromptToolName. Please use one or the other.");
        p.push("--permission-prompt-tool", "stdio");
      } else if (A) p.push("--permission-prompt-tool", A);
      if (I) p.push("--continue");
      if (x) p.push("--resume", x);
      if (this.options.assistant) p.push("--assistant");
      if (this.options.channels && this.options.channels.length > 0) p.push("--channels", ...this.options.channels);
      if (U$.length > 0) p.push("--allowedTools", U$.join(","));
      if (T$.length > 0) p.push("--disallowedTools", T$.join(","));
      if (n$ !== void 0) if (Array.isArray(n$)) if (n$.length === 0) p.push("--tools", "");
      else p.push("--tools", n$.join(","));
      else p.push("--tools", "default");
      if (X4 && Object.keys(X4).length > 0) p.push("--mcp-config", q$({ mcpServers: X4 }));
      if (T !== void 0) p.push(`--setting-sources=${T.join(",")}`);
      if (X6) p.push("--strict-mcp-config");
      if (D) p.push("--permission-mode", D);
      if (j) p.push("--allow-dangerously-skip-permissions");
      if (w) {
        if (O && w === O) throw Error("Fallback model cannot be the same as the main model. Please specify a different model for fallbackModel option.");
        p.push("--fallback-model", w);
      }
      if (this.options.includeHookEvents) p.push("--include-hook-events");
      if (l1) p.push("--include-partial-messages");
      if (this.options.sessionMirror) p.push("--session-mirror");
      for (let l$ of $) p.push("--add-dir", l$);
      if (J4 && J4.length > 0) for (let l$ of J4) if (l$.type === "local") p.push("--plugin-dir", l$.path);
      else throw Error(`Unsupported plugin type: ${l$.type}`);
      if (this.options.forkSession) p.push("--fork-session");
      if (this.options.resumeSessionAt) p.push("--resume-session-at", this.options.resumeSessionAt);
      if (this.options.sessionId) p.push("--session-id", this.options.sessionId);
      if (this.options.persistSession === false) p.push("--no-session-persistence");
      let G8 = { ...z8 != null ? z8 : {} };
      if (this.options.settings) G8.settings = this.options.settings;
      let D5 = QV(G8, z82);
      for (let [l$, v6] of Object.entries(D5)) if (v6 === null) p.push(`--${l$}`);
      else p.push(`--${l$}`, v6);
      if (!U.CLAUDE_CODE_ENTRYPOINT) U.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
      if (delete U.NODE_OPTIONS, r$(U.DEBUG_CLAUDE_AGENT_SDK)) U.DEBUG = "1";
      else delete U.DEBUG;
      let c1 = b2(G), U8 = c1 ? G : Y, H8 = c1 ? [...W, ...p] : [...W, G, ...p], GJ = { command: U8, args: H8, cwd: Q, env: U, signal: this.abortController.signal };
      if (this.options.spawnClaudeCodeProcess) Y6(`Spawning Claude Code (custom): ${U8} ${H8.join(" ")}`), this.process = this.options.spawnClaudeCodeProcess(GJ);
      else Y6(`Spawning Claude Code: ${U8} ${H8.join(" ")}`), this.process = this.spawnLocalProcess(GJ);
      this.processStdin = this.process.stdin, this.processStdout = this.process.stdout, I2(this.process), this.abortHandler = () => {
        if (this.process && !this.process.killed) this.process.kill("SIGTERM");
      }, this.abortController.signal.addEventListener("abort", this.abortHandler), this.process.on("error", (l$) => {
        if (this.ready = false, this.abortController.signal.aborted) this.exitError = new J6("Claude Code process aborted by user");
        else if (JX(l$)) {
          let v6 = c1 ? `Claude Code native binary not found at ${G}. Please ensure Claude Code is installed via native installer or specify a valid path with options.pathToClaudeCodeExecutable.` : `Claude Code executable not found at ${G}. Is options.pathToClaudeCodeExecutable set?`;
          this.exitError = ReferenceError(v6), Y6(this.exitError.message);
        } else this.exitError = Error(`Failed to spawn Claude Code process: ${l$.message}`), Y6(this.exitError.message);
      }), this.process.on("exit", (l$, v6) => {
        if (this.ready = false, this.abortController.signal.aborted) this.exitError = new J6("Claude Code process aborted by user");
        else {
          let Y4 = this.getProcessExitError(l$, v6);
          if (Y4) this.exitError = Y4, Y6(Y4.message);
        }
      }), this.ready = true;
    } catch ($) {
      throw this.ready = false, $;
    }
  }
  getProcessExitError($, X) {
    if ($ !== 0 && $ !== null) return Error(`Claude Code process exited with code ${$}`);
    else if (X) return Error(`Claude Code process terminated by signal ${X}`);
    return;
  }
  write($) {
    var _a3, _b2;
    if (this.abortController.signal.aborted) throw new J6("Operation aborted");
    if (this.spawnResolve) {
      this.pendingWrites.push($);
      return;
    }
    if (!this.ready || !this.processStdin) throw Error("ProcessTransport is not ready for writing");
    if (this.processStdin.writableEnded) {
      Y6("[ProcessTransport] Dropping write to ended stdin stream");
      return;
    }
    if (((_a3 = this.process) == null ? void 0 : _a3.killed) || ((_b2 = this.process) == null ? void 0 : _b2.exitCode) !== null) throw Error("Cannot write to terminated process");
    if (this.exitError) throw Error(`Cannot write to process that exited with error: ${this.exitError.message}`);
    Y6(`[ProcessTransport] Writing to stdin: ${$.substring(0, 100)}`);
    try {
      if (!this.processStdin.write($)) Y6("[ProcessTransport] Write buffer full, data queued");
    } catch (X) {
      throw this.ready = false, Error(`Failed to write to process stdin: ${H0(X)}`);
    }
  }
  [Symbol.dispose]() {
    this.close();
  }
  close() {
    var _a3;
    if (this.spawnAbort(Error("Query closed before spawn")), this.processStdin) this.processStdin.end(), this.processStdin = void 0;
    if (this.abortHandler) this.abortController.signal.removeEventListener("abort", this.abortHandler), this.abortHandler = void 0;
    for (let { handler: X } of this.exitListeners) (_a3 = this.process) == null ? void 0 : _a3.off("exit", X);
    this.exitListeners = [];
    let $ = this.process;
    if ($ && !$.killed && $.exitCode === null) {
      const processKillTimer = setTimeout((X) => {
        if (X.killed || X.exitCode !== null) return;
        X.kill("SIGTERM");
        const forceKillTimer = setTimeout((J) => {
          if (J.exitCode === null) J.kill("SIGKILL");
        }, 5e3, X);
        forceKillTimer.unref?.();
      }, M2, $);
      processKillTimer.unref?.();
      $.once("exit", () => mJ.delete($));
    }
    else if ($) mJ.delete($);
    this.ready = false;
  }
  isReady() {
    return this.ready;
  }
  async *readMessages() {
    if (this.spawnPromise) await this.spawnPromise, this.spawnPromise = void 0;
    if (!this.processStdout) throw Error("ProcessTransport output stream not available");
    if (this.exitError) throw this.exitError;
    let $ = (0, import_readline.createInterface)({ input: this.processStdout }), X = this.process ? (() => {
      let J = this.process, Q = () => $.close();
      return J.on("error", Q), () => J.off("error", Q);
    })() : void 0;
    if (this.exitError) $.close();
    try {
      for await (let J of $) if (J.trim()) {
        let Q;
        try {
          Q = o$(J);
        } catch (Y) {
          Y6(`Non-JSON stdout: ${J}`);
          continue;
        }
        yield Q;
      }
      if (this.exitError) throw this.exitError;
      await this.waitForExit();
    } catch (J) {
      throw J;
    } finally {
      X == null ? void 0 : X(), $.close();
    }
  }
  endInput() {
    if (this.spawnResolve) {
      this.pendingEndInput = true;
      return;
    }
    if (this.processStdin) this.processStdin.end();
  }
  getInputStream() {
    return this.processStdin;
  }
  onExit($) {
    if (!this.process) return () => {
    };
    let X = (J, Q) => {
      let Y = this.getProcessExitError(J, Q);
      $(Y);
    };
    return this.process.on("exit", X), this.exitListeners.push({ callback: $, handler: X }), () => {
      if (this.process) this.process.off("exit", X);
      let J = this.exitListeners.findIndex((Q) => Q.handler === X);
      if (J !== -1) this.exitListeners.splice(J, 1);
    };
  }
  async waitForExit() {
    if (!this.process) {
      if (this.exitError) throw this.exitError;
      return;
    }
    if (this.process.exitCode !== null || this.process.killed || this.exitError) {
      if (this.exitError) throw this.exitError;
      return;
    }
    return new Promise(($, X) => {
      let J = (Y, W) => {
        if (this.abortController.signal.aborted) {
          X(new J6("Operation aborted"));
          return;
        }
        let z8 = this.getProcessExitError(Y, W);
        if (z8) X(z8);
        else $();
      };
      this.process.once("exit", J);
      let Q = (Y) => {
        this.process.off("exit", J), X(Y);
      };
      this.process.once("error", Q), this.process.once("exit", () => {
        this.process.off("error", Q);
      });
    });
  }
};
function b2($) {
  return ![".js", ".mjs", ".tsx", ".ts", ".jsx"].some((J) => $.endsWith(J));
}
function lJ($, X = process.platform, J = process.arch) {
  let Y = X === "win32" ? ".exe" : "", z8 = (X === "linux" ? [`@anthropic-ai/claude-agent-sdk-linux-${J}-musl`, `@anthropic-ai/claude-agent-sdk-linux-${J}`] : [`@anthropic-ai/claude-agent-sdk-${X}-${J}`]).map((G) => `${G}/claude${Y}`);
  for (let G of z8) try {
    return $(G);
  } catch (e2) {
  }
  return null;
}
var j1 = class {
  constructor($) {
    __publicField(this, "returned");
    __publicField(this, "queue", []);
    __publicField(this, "readResolve");
    __publicField(this, "readReject");
    __publicField(this, "isDone", false);
    __publicField(this, "hasError");
    __publicField(this, "started", false);
    this.returned = $;
  }
  [Symbol.asyncIterator]() {
    if (this.started) throw Error("Stream can only be iterated once");
    return this.started = true, this;
  }
  next() {
    if (this.queue.length > 0) return Promise.resolve({ done: false, value: this.queue.shift() });
    if (this.isDone) return Promise.resolve({ done: true, value: void 0 });
    if (this.hasError) return Promise.reject(this.hasError);
    return new Promise(($, X) => {
      this.readResolve = $, this.readReject = X;
    });
  }
  enqueue($) {
    if (this.readResolve) {
      let X = this.readResolve;
      this.readResolve = void 0, this.readReject = void 0, X({ done: false, value: $ });
    } else this.queue.push($);
  }
  done() {
    if (this.isDone = true, this.readResolve) {
      let $ = this.readResolve;
      this.readResolve = void 0, this.readReject = void 0, $({ done: true, value: void 0 });
    }
  }
  error($) {
    if (this.hasError = $, this.readReject) {
      let X = this.readReject;
      this.readResolve = void 0, this.readReject = void 0, X($);
    }
  }
  return() {
    if (this.isDone = true, this.returned) this.returned();
    return Promise.resolve({ done: true, value: void 0 });
  }
};
var UW = class {
  constructor($) {
    __publicField(this, "sendMcpMessage");
    __publicField(this, "isClosed", false);
    __publicField(this, "onclose");
    __publicField(this, "onerror");
    __publicField(this, "onmessage");
    this.sendMcpMessage = $;
  }
  async start() {
  }
  async send($) {
    if (this.isClosed) throw Error("Transport is closed");
    this.sendMcpMessage($);
  }
  async close() {
    var _a3;
    if (this.isClosed) return;
    this.isClosed = true, (_a3 = this.onclose) == null ? void 0 : _a3.call(this);
  }
};
var WX = class {
  constructor($, X, J, Q, Y, W = /* @__PURE__ */ new Map(), z8, G, U, H) {
    __publicField(this, "transport");
    __publicField(this, "isSingleUserTurn");
    __publicField(this, "canUseTool");
    __publicField(this, "hooks");
    __publicField(this, "abortController");
    __publicField(this, "jsonSchema");
    __publicField(this, "initConfig");
    __publicField(this, "onElicitation");
    __publicField(this, "getOAuthToken");
    __publicField(this, "pendingControlResponses", /* @__PURE__ */ new Map());
    __publicField(this, "cleanupPerformed", false);
    __publicField(this, "sdkMessages");
    __publicField(this, "inputStream", new j1());
    __publicField(this, "initialization");
    __publicField(this, "cancelControllers", /* @__PURE__ */ new Map());
    __publicField(this, "hookCallbacks", /* @__PURE__ */ new Map());
    __publicField(this, "nextCallbackId", 0);
    __publicField(this, "sdkMcpTransports", /* @__PURE__ */ new Map());
    __publicField(this, "sdkMcpServerInstances", /* @__PURE__ */ new Map());
    __publicField(this, "pendingMcpResponses", /* @__PURE__ */ new Map());
    __publicField(this, "firstResultReceivedResolve");
    __publicField(this, "firstResultReceived", false);
    __publicField(this, "lastErrorResultText");
    __publicField(this, "transcriptMirrorBatcher");
    __publicField(this, "cleanupCallbacks", []);
    __publicField(this, "cleanupPromise");
    this.transport = $;
    this.isSingleUserTurn = X;
    this.canUseTool = J;
    this.hooks = Q;
    this.abortController = Y;
    this.jsonSchema = z8;
    this.initConfig = G;
    this.onElicitation = U;
    this.getOAuthToken = H;
    for (let [K, V] of W) this.connectSdkMcpServer(K, V);
    this.sdkMessages = this.readSdkMessages(), this.readMessages(), this.initialization = this.initialize(), this.initialization.catch(() => {
    });
  }
  setIsSingleUserTurn($) {
    this.isSingleUserTurn = $;
  }
  setTranscriptMirrorBatcher($) {
    this.transcriptMirrorBatcher = $;
  }
  reportMirrorError($, X) {
    let J = { type: "system", subtype: "mirror_error", error: X, key: $, uuid: (0, import_crypto3.randomUUID)(), session_id: $.sessionId };
    this.inputStream.enqueue(J);
  }
  addCleanupCallback($) {
    if (this.cleanupPerformed) $();
    else this.cleanupCallbacks.push($);
  }
  isClosed() {
    return this.cleanupPerformed;
  }
  hasBidirectionalNeeds() {
    return this.sdkMcpTransports.size > 0 || this.hooks !== void 0 && Object.keys(this.hooks).length > 0 || this.canUseTool !== void 0 || this.onElicitation !== void 0 || this.getOAuthToken !== void 0;
  }
  setError($) {
    this.inputStream.error($);
  }
  async stopTask($) {
    await this.request({ subtype: "stop_task", task_id: $ });
  }
  close() {
    this.cleanup();
  }
  cleanup($) {
    if (this.cleanupPromise) return this.cleanupPromise;
    return this.cleanupPerformed = true, this.cleanupPromise = this.performCleanup($), this.cleanupPromise;
  }
  async performCleanup($) {
    for (let X of this.cleanupCallbacks) try {
      X();
    } catch (e2) {
    }
    if (this.cleanupCallbacks = [], this.transcriptMirrorBatcher) try {
      await this.transcriptMirrorBatcher.flush();
    } catch (e2) {
    }
    try {
      for (let J of this.cancelControllers.values()) J.abort();
      this.cancelControllers.clear(), this.transport.close();
      let X = $ != null ? $ : Error("Query closed before response received");
      for (let { reject: J } of this.pendingControlResponses.values()) J(X);
      this.pendingControlResponses.clear();
      for (let { reject: J } of this.pendingMcpResponses.values()) J(X);
      this.pendingMcpResponses.clear(), this.hookCallbacks.clear();
      for (let J of this.sdkMcpTransports.values()) J.close().catch(() => {
      });
      if (this.sdkMcpTransports.clear(), $) this.inputStream.error($);
      else this.inputStream.done();
    } catch (X) {
    }
  }
  next(...[$]) {
    return this.sdkMessages.next(...[$]);
  }
  async return($) {
    return await this.cleanup(), this.sdkMessages.return($);
  }
  async throw($) {
    return await this.cleanup(), this.sdkMessages.throw($);
  }
  [Symbol.asyncIterator]() {
    return this.sdkMessages;
  }
  async [Symbol.asyncDispose]() {
    await this.cleanup();
  }
  async readMessages() {
    var _a3;
    try {
      for await (let $ of this.transport.readMessages()) {
        if ($.type === "control_response") {
          let X = this.pendingControlResponses.get($.response.request_id);
          if (X) X.handler($.response);
          continue;
        } else if ($.type === "control_request") {
          this.handleControlRequest($);
          continue;
        } else if ($.type === "control_cancel_request") {
          this.handleControlCancelRequest($);
          continue;
        } else if ($.type === "keep_alive") continue;
        else if ($.type === "transcript_mirror") {
          (_a3 = this.transcriptMirrorBatcher) == null ? void 0 : _a3.enqueue($.filePath, $.entries);
          continue;
        }
        if ($.type === "system" && $.subtype === "post_turn_summary") {
          this.inputStream.enqueue($);
          continue;
        }
        if ($.type === "result") {
          if (this.transcriptMirrorBatcher) await this.transcriptMirrorBatcher.flush();
          if (this.lastErrorResultText = $.is_error ? $.subtype === "success" ? $.result : $.errors.join("; ") : void 0, this.firstResultReceived = true, this.firstResultReceivedResolve) this.firstResultReceivedResolve();
          if (this.isSingleUserTurn) f$("[Query.readMessages] First result received for single-turn query, closing stdin"), this.transport.endInput();
        } else if (!($.type === "system" && $.subtype === "session_state_changed")) this.lastErrorResultText = void 0;
        this.inputStream.enqueue($);
      }
      if (this.transcriptMirrorBatcher) await this.transcriptMirrorBatcher.flush();
      if (this.firstResultReceivedResolve) this.firstResultReceivedResolve();
      this.inputStream.done(), this.cleanup();
    } catch ($) {
      if (this.transcriptMirrorBatcher) await this.transcriptMirrorBatcher.flush();
      if (this.firstResultReceivedResolve) this.firstResultReceivedResolve();
      if (this.lastErrorResultText !== void 0 && !($ instanceof J6)) {
        let X = Error(`Claude Code returned an error result: ${this.lastErrorResultText}`);
        f$(`[Query.readMessages] Replacing exit error with result text. Original: ${H0($)}`), this.inputStream.error(X), this.cleanup(X);
        return;
      }
      this.inputStream.error($), this.cleanup($);
    }
  }
  async handleControlRequest($) {
    let X = new AbortController();
    this.cancelControllers.set($.request_id, X);
    try {
      let J = await this.processControlRequest($, X.signal);
      if (this.cleanupPerformed) return;
      let Q = { type: "control_response", response: { subtype: "success", request_id: $.request_id, response: J } };
      await Promise.resolve(this.transport.write(q$(Q) + `
`));
    } catch (J) {
      if (this.cleanupPerformed) return;
      let Q = { type: "control_response", response: { subtype: "error", request_id: $.request_id, error: H0(J) } };
      try {
        await Promise.resolve(this.transport.write(q$(Q) + `
`));
      } catch (Y) {
        f$(`[Query.handleControlRequest] Error-response write failed: ${H0(Y)}`, { level: "error" });
      }
    } finally {
      this.cancelControllers.delete($.request_id);
    }
  }
  handleControlCancelRequest($) {
    let X = this.cancelControllers.get($.request_id);
    if (X) X.abort(), this.cancelControllers.delete($.request_id);
  }
  async processControlRequest($, X) {
    var _a3;
    if ($.request.subtype === "can_use_tool") {
      if (!this.canUseTool) throw Error("canUseTool callback is not provided.");
      return { ...await this.canUseTool($.request.tool_name, $.request.input, { signal: X, suggestions: $.request.permission_suggestions, blockedPath: $.request.blocked_path, decisionReason: $.request.decision_reason, title: $.request.title, displayName: $.request.display_name, description: $.request.description, toolUseID: $.request.tool_use_id, agentID: $.request.agent_id }), toolUseID: $.request.tool_use_id };
    } else if ($.request.subtype === "hook_callback") return await this.handleHookCallbacks($.request.callback_id, $.request.input, $.request.tool_use_id, X);
    else if ($.request.subtype === "mcp_message") {
      let J = $.request, Q = this.sdkMcpTransports.get(J.server_name);
      if (!Q) throw Error(`SDK MCP server not found: ${J.server_name}`);
      if ("method" in J.message && "id" in J.message && J.message.id !== null) return { mcp_response: await this.handleMcpControlRequest(J.server_name, J, Q) };
      else {
        if (Q.onmessage) Q.onmessage(J.message);
        return { mcp_response: { jsonrpc: "2.0", result: {}, id: 0 } };
      }
    } else if ($.request.subtype === "elicitation") {
      let J = $.request;
      if (this.onElicitation) return await this.onElicitation({ serverName: J.mcp_server_name, message: J.message, mode: J.mode, url: J.url, elicitationId: J.elicitation_id, requestedSchema: J.requested_schema, title: J.title, displayName: J.display_name, description: J.description }, { signal: X });
      return { action: "decline" };
    } else if ($.request.subtype === "oauth_token_refresh") {
      if (!this.getOAuthToken) throw Error("getOAuthToken callback is not provided.");
      return { accessToken: (_a3 = await this.getOAuthToken({ signal: X })) != null ? _a3 : null };
    }
    throw Error("Unsupported control request subtype: " + $.request.subtype);
  }
  async *readSdkMessages() {
    try {
      for await (let $ of this.inputStream) yield $;
    } finally {
      await this.cleanup();
    }
  }
  async initialize() {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h;
    let $;
    if (this.hooks) {
      $ = {};
      for (let [Y, W] of Object.entries(this.hooks)) if (W.length > 0) $[Y] = W.map((z8) => {
        let G = [];
        for (let U of z8.hooks) {
          let H = `hook_${this.nextCallbackId++}`;
          this.hookCallbacks.set(H, U), G.push(H);
        }
        return { matcher: z8.matcher, hookCallbackIds: G, timeout: z8.timeout };
      });
    }
    let X = this.sdkMcpTransports.size > 0 ? Array.from(this.sdkMcpTransports.keys()) : void 0, J = { subtype: "initialize", hooks: $, sdkMcpServers: X, jsonSchema: this.jsonSchema, systemPrompt: typeof ((_a3 = this.initConfig) == null ? void 0 : _a3.systemPrompt) === "string" ? [this.initConfig.systemPrompt] : (_b2 = this.initConfig) == null ? void 0 : _b2.systemPrompt, appendSystemPrompt: (_c = this.initConfig) == null ? void 0 : _c.appendSystemPrompt, appendSubagentSystemPrompt: (_d2 = this.initConfig) == null ? void 0 : _d2.appendSubagentSystemPrompt, excludeDynamicSections: (_e = this.initConfig) == null ? void 0 : _e.excludeDynamicSections, agents: (_f = this.initConfig) == null ? void 0 : _f.agents, promptSuggestions: (_g = this.initConfig) == null ? void 0 : _g.promptSuggestions, agentProgressSummaries: (_h = this.initConfig) == null ? void 0 : _h.agentProgressSummaries };
    return (await this.request(J)).response;
  }
  async interrupt() {
    await this.request({ subtype: "interrupt" });
  }
  async setPermissionMode($) {
    await this.request({ subtype: "set_permission_mode", mode: $ });
  }
  async setModel($) {
    await this.request({ subtype: "set_model", model: $ });
  }
  async setMaxThinkingTokens($) {
    await this.request({ subtype: "set_max_thinking_tokens", max_thinking_tokens: $ });
  }
  async applyFlagSettings($) {
    await this.request({ subtype: "apply_flag_settings", settings: $ });
  }
  async getSettings() {
    return (await this.request({ subtype: "get_settings" })).response;
  }
  async rewindFiles($, X) {
    return (await this.request({ subtype: "rewind_files", user_message_id: $, dry_run: X == null ? void 0 : X.dryRun })).response;
  }
  async cancelAsyncMessage($) {
    return (await this.request({ subtype: "cancel_async_message", message_uuid: $ })).response.cancelled;
  }
  async seedReadState($, X) {
    await this.request({ subtype: "seed_read_state", path: $, mtime: X });
  }
  async enableRemoteControl($, X) {
    return (await this.request({ subtype: "remote_control", enabled: $, ...X !== void 0 && { name: X } })).response;
  }
  async generateSessionTitle($, X) {
    return (await this.request({ subtype: "generate_session_title", description: $, persist: X == null ? void 0 : X.persist })).response.title;
  }
  async askSideQuestion($) {
    var _a3;
    let J = (await this.request({ subtype: "side_question", question: $ })).response;
    return J.response === null ? null : { response: J.response, synthetic: (_a3 = J.synthetic) != null ? _a3 : false };
  }
  async launchUltrareview($, X) {
    var _a3;
    return (await this.request({ subtype: "ultrareview_launch", args: $, confirm: (_a3 = X == null ? void 0 : X.confirm) != null ? _a3 : false })).response;
  }
  processPendingPermissionRequests($) {
    for (let X of $) if (X.request.subtype === "can_use_tool") this.handleControlRequest(X).catch(() => {
    });
  }
  request($) {
    let X = Math.random().toString(36).substring(2, 15), J = { request_id: X, type: "control_request", request: $ };
    return new Promise((Q, Y) => {
      this.pendingControlResponses.set(X, { handler: (W) => {
        if (this.pendingControlResponses.delete(X), W.subtype === "success") Q(W);
        else if (Y(Error(W.error)), W.pending_permission_requests) this.processPendingPermissionRequests(W.pending_permission_requests);
      }, reject: Y }), Promise.resolve(this.transport.write(q$(J) + `
`)).catch((W) => {
        this.pendingControlResponses.delete(X), Y(W);
      });
    });
  }
  initializationResult() {
    return this.initialization;
  }
  async supportedCommands() {
    return (await this.initialization).commands;
  }
  async supportedModels() {
    return (await this.initialization).models;
  }
  async supportedAgents() {
    return (await this.initialization).agents;
  }
  async reconnectMcpServer($) {
    await this.request({ subtype: "mcp_reconnect", serverName: $ });
  }
  async toggleMcpServer($, X) {
    await this.request({ subtype: "mcp_toggle", serverName: $, enabled: X });
  }
  async enableChannel($) {
    await this.request({ subtype: "channel_enable", serverName: $ });
  }
  async mcpAuthenticate($) {
    return (await this.request({ subtype: "mcp_authenticate", serverName: $ })).response;
  }
  async mcpClearAuth($) {
    return (await this.request({ subtype: "mcp_clear_auth", serverName: $ })).response;
  }
  async mcpSubmitOAuthCallbackUrl($, X) {
    return (await this.request({ subtype: "mcp_oauth_callback_url", serverName: $, callbackUrl: X })).response;
  }
  async claudeAuthenticate($) {
    return (await this.request({ subtype: "claude_authenticate", loginWithClaudeAi: $ })).response;
  }
  async claudeOAuthCallback($, X) {
    return (await this.request({ subtype: "claude_oauth_callback", authorizationCode: $, state: X })).response;
  }
  async claudeOAuthWaitForCompletion() {
    return (await this.request({ subtype: "claude_oauth_wait_for_completion" })).response;
  }
  async mcpServerStatus() {
    return (await this.request({ subtype: "mcp_status" })).response.mcpServers;
  }
  async getContextUsage() {
    return (await this.request({ subtype: "get_context_usage" })).response;
  }
  async reloadPlugins() {
    return (await this.request({ subtype: "reload_plugins" })).response;
  }
  async setMcpServers($) {
    let X = {}, J = {};
    for (let [G, U] of Object.entries($)) if (U.type === "sdk" && "instance" in U) X[G] = U.instance;
    else J[G] = U;
    let Q = new Set(this.sdkMcpServerInstances.keys()), Y = new Set(Object.keys(X));
    for (let G of Q) if (!Y.has(G)) await this.disconnectSdkMcpServer(G);
    for (let [G, U] of Object.entries(X)) if (!Q.has(G)) this.connectSdkMcpServer(G, U);
    let W = {};
    for (let G of Object.keys(X)) W[G] = { type: "sdk", name: G };
    return (await this.request({ subtype: "mcp_set_servers", servers: { ...J, ...W } })).response;
  }
  async accountInfo() {
    return (await this.initialization).account;
  }
  async streamInput($) {
    var _a3;
    f$("[Query.streamInput] Starting to process input stream");
    try {
      let X = 0;
      for await (let J of $) {
        if (X++, f$(`[Query.streamInput] Processing message ${X}: ${J.type}`), (_a3 = this.abortController) == null ? void 0 : _a3.signal.aborted) break;
        await Promise.resolve(this.transport.write(q$(J) + `
`));
      }
      if (f$(`[Query.streamInput] Finished processing ${X} messages from input stream`), X > 0 && this.hasBidirectionalNeeds()) f$("[Query.streamInput] Has bidirectional needs, waiting for first result"), await this.waitForFirstResult();
      f$("[Query] Calling transport.endInput() to close stdin to CLI process"), this.transport.endInput();
    } catch (X) {
      if (!(X instanceof J6)) throw X;
    }
  }
  waitForFirstResult() {
    if (this.firstResultReceived) return f$("[Query.waitForFirstResult] Result already received, returning immediately"), Promise.resolve();
    return new Promise(($) => {
      var _a3, _b2;
      if ((_a3 = this.abortController) == null ? void 0 : _a3.signal.aborted) {
        $();
        return;
      }
      (_b2 = this.abortController) == null ? void 0 : _b2.signal.addEventListener("abort", () => $(), { once: true }), this.firstResultReceivedResolve = $;
    });
  }
  handleHookCallbacks($, X, J, Q) {
    let Y = this.hookCallbacks.get($);
    if (!Y) throw Error(`No hook callback found for ID: ${$}`);
    return Y(X, J, { signal: Q });
  }
  connectSdkMcpServer($, X) {
    let J = new UW((Q) => this.sendMcpServerMessageToCli($, Q));
    this.sdkMcpTransports.set($, J), this.sdkMcpServerInstances.set($, X), X.connect(J).catch((Q) => {
      if (this.sdkMcpTransports.get($) === J) this.sdkMcpTransports.delete($);
      if (this.sdkMcpServerInstances.get($) === X) this.sdkMcpServerInstances.delete($);
      f$(`[Query.connectSdkMcpServer] Failed to connect MCP server '${$}': ${Q}`, { level: "error" });
    });
  }
  async disconnectSdkMcpServer($) {
    let X = this.sdkMcpTransports.get($);
    if (X) await X.close(), this.sdkMcpTransports.delete($);
    this.sdkMcpServerInstances.delete($);
  }
  sendMcpServerMessageToCli($, X) {
    if ("id" in X && X.id !== null && X.id !== void 0) {
      let Q = `${$}:${X.id}`, Y = this.pendingMcpResponses.get(Q);
      if (Y) {
        Y.resolve(X), this.pendingMcpResponses.delete(Q);
        return;
      }
    }
    let J = { type: "control_request", request_id: (0, import_crypto3.randomUUID)(), request: { subtype: "mcp_message", server_name: $, message: X } };
    Promise.resolve(this.transport.write(q$(J) + `
`)).catch((Q) => {
      f$(`[Query.sendMcpServerMessageToCli] Transport write failed: ${Q}`, { level: "error" });
    });
  }
  handleMcpControlRequest($, X, J) {
    let Q = "id" in X.message ? X.message.id : null, Y = `${$}:${Q}`;
    return new Promise((W, z8) => {
      let G = () => {
        this.pendingMcpResponses.delete(Y);
      }, U = (K) => {
        G(), W(K);
      }, H = (K) => {
        G(), z8(K);
      };
      if (this.pendingMcpResponses.set(Y, { resolve: U, reject: H }), J.onmessage) J.onmessage(X.message);
      else {
        G(), z8(Error("No message handler registered"));
        return;
      }
    });
  }
};
var Z2 = 500;
var P2 = 1048576;
var HW = class {
  constructor($, X = 6e4, J, Q = Z2, Y = P2) {
    __publicField(this, "send");
    __publicField(this, "sendTimeoutMs");
    __publicField(this, "onError");
    __publicField(this, "maxPendingEntries");
    __publicField(this, "maxPendingBytes");
    __publicField(this, "pending", []);
    __publicField(this, "pendingEntries", 0);
    __publicField(this, "pendingBytes", 0);
    __publicField(this, "flushPromise", null);
    this.send = $;
    this.sendTimeoutMs = X;
    this.onError = J;
    this.maxPendingEntries = Q;
    this.maxPendingBytes = Y;
  }
  enqueue($, X) {
    let J = q$(X).length;
    if (this.pending.push({ filePath: $, entries: X, bytes: J }), this.pendingEntries += X.length, this.pendingBytes += J, this.pendingEntries > this.maxPendingEntries || this.pendingBytes > this.maxPendingBytes) this.flushPromise = this.drain(), this.flushPromise.catch(() => {
    });
  }
  async flush() {
    let $ = this.drain();
    if (this.flushPromise = $, await $, this.flushPromise === $) this.flushPromise = null;
  }
  async drain() {
    let $ = this.flushPromise, X = this.pending.splice(0);
    if (this.pendingEntries = 0, this.pendingBytes = 0, $) await $;
    if (X.length === 0) return;
    await this.doFlush(X);
  }
  async doFlush($) {
    var _a3;
    let X = /* @__PURE__ */ new Map();
    for (let J of $) {
      let Q = X.get(J.filePath);
      if (Q) Q.push(...J.entries);
      else X.set(J.filePath, J.entries.slice());
    }
    for (let [J, Q] of X) try {
      await K1(this.send(J, Q), this.sendTimeoutMs, `SessionStore.append() timed out after ${this.sendTimeoutMs}ms for ${J}`);
    } catch (Y) {
      f$(`[TranscriptMirrorBatcher] flush failed for ${J}: ${Y}`, { level: "error" });
      try {
        (_a3 = this.onError) == null ? void 0 : _a3.call(this, J, f4(Y));
      } catch (W) {
        f$(`[TranscriptMirrorBatcher] onError callback threw: ${W}`, { level: "error" });
      }
    }
  }
};
var _2 = (0, import_util.promisify)(import_child_process3.execFile);
function GV($) {
  let X = 0;
  for (let J = 0; J < $.length; J++) X = (X << 5) - X + $.charCodeAt(J) | 0;
  return X;
}
var y2 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
function N$($) {
  if (typeof $ !== "string") return null;
  return y2.test($) ? $ : null;
}
async function GX($, X) {
  let J = (0, import_fs2.createWriteStream)($, { mode: 384 });
  try {
    for (let Q of X) if (!J.write(JSON.stringify(Q) + `
`)) await (0, import_events2.once)(J, "drain");
    J.end(), await (0, import_events2.once)(J, "finish");
  } catch (Q) {
    throw J.destroy(), Q;
  }
}
var O0 = 200;
function h2($) {
  return Math.abs(GV($)).toString(36);
}
function A1($) {
  let X = $.replace(/[^a-zA-Z0-9]/g, "-");
  if (X.length <= O0) return X;
  return `${X.slice(0, O0)}-${h2($)}`;
}
var pJ = Buffer.from('{"type":"attribution-snapshot"');
var p2 = Buffer.from('{"type":"system"');
var zX = 10;
var d2 = Buffer.from([zX]);
function AA() {
  return "prod";
}
var IA = "user:inference";
var TV = "user:profile";
var bA = "org:create_api_key";
var ZA = [bA, TV];
var PA = [TV, IA, "user:sessions:claude_code", "user:mcp_servers", "user:file_upload"];
var _p = Array.from(/* @__PURE__ */ new Set([...ZA, ...PA]));
var xV = { BASE_API_URL: "https://api.anthropic.com", CONSOLE_AUTHORIZE_URL: "https://platform.claude.com/oauth/authorize", CLAUDE_AI_AUTHORIZE_URL: "https://claude.com/cai/oauth/authorize", CLAUDE_AI_ORIGIN: "https://claude.ai", TOKEN_URL: "https://platform.claude.com/v1/oauth/token", API_KEY_URL: "https://api.anthropic.com/api/oauth/claude_cli/create_api_key", ROLES_URL: "https://api.anthropic.com/api/oauth/claude_cli/roles", CONSOLE_SUCCESS_URL: "https://platform.claude.com/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code", CLAUDEAI_SUCCESS_URL: "https://platform.claude.com/oauth/code/success?app=claude-code", MANUAL_REDIRECT_URL: "https://platform.claude.com/oauth/code/callback", CLIENT_ID: "9d1c250a-e61b-44d9-88ed-5944d1962f5e", OAUTH_FILE_SUFFIX: "", MCP_PROXY_URL: "https://mcp-proxy.anthropic.com", MCP_PROXY_PATH: "/v1/mcp/{server_id}" };
var RA = void 0;
function EA() {
  var _a3, _b2, _c, _d2, _e, _f;
  let $ = (_b2 = (_a3 = process.env.CLAUDE_LOCAL_OAUTH_API_BASE) == null ? void 0 : _a3.replace(/\/$/, "")) != null ? _b2 : "http://localhost:8000", X = (_d2 = (_c = process.env.CLAUDE_LOCAL_OAUTH_APPS_BASE) == null ? void 0 : _c.replace(/\/$/, "")) != null ? _d2 : "http://localhost:4000", J = (_f = (_e = process.env.CLAUDE_LOCAL_OAUTH_CONSOLE_BASE) == null ? void 0 : _e.replace(/\/$/, "")) != null ? _f : "http://localhost:3000";
  return { BASE_API_URL: $, CONSOLE_AUTHORIZE_URL: `${J}/oauth/authorize`, CLAUDE_AI_AUTHORIZE_URL: `${X}/oauth/authorize`, CLAUDE_AI_ORIGIN: X, TOKEN_URL: `${$}/v1/oauth/token`, API_KEY_URL: `${$}/api/oauth/claude_cli/create_api_key`, ROLES_URL: `${$}/api/oauth/claude_cli/roles`, CONSOLE_SUCCESS_URL: `${J}/buy_credits?returnUrl=/oauth/code/success%3Fapp%3Dclaude-code`, CLAUDEAI_SUCCESS_URL: `${J}/oauth/code/success?app=claude-code`, MANUAL_REDIRECT_URL: `${J}/oauth/code/callback`, CLIENT_ID: "22422756-60c9-4084-8eb7-27705fd5cf9a", OAUTH_FILE_SUFFIX: "-local-oauth", MCP_PROXY_URL: "http://localhost:8205", MCP_PROXY_PATH: "/v1/toolbox/shttp/mcp/{server_id}" };
}
var SA = ["https://beacon.claude-ai.staging.ant.dev", "https://claude.fedstart.com", "https://claude-staging.fedstart.com"];
function yV() {
  let $ = (() => {
    switch (AA()) {
      case "local":
        return EA();
      case "staging":
        return RA != null ? RA : xV;
      case "prod":
        return xV;
    }
  })(), X = process.env.CLAUDE_CODE_CUSTOM_OAUTH_URL;
  if (X) {
    let Q = X.replace(/\/$/, "");
    if (!SA.includes(Q)) throw Error("CLAUDE_CODE_CUSTOM_OAUTH_URL is not an approved endpoint.");
    $ = { ...$, BASE_API_URL: Q, CONSOLE_AUTHORIZE_URL: `${Q}/oauth/authorize`, CLAUDE_AI_AUTHORIZE_URL: `${Q}/oauth/authorize`, CLAUDE_AI_ORIGIN: Q, TOKEN_URL: `${Q}/v1/oauth/token`, API_KEY_URL: `${Q}/api/oauth/claude_cli/create_api_key`, ROLES_URL: `${Q}/api/oauth/claude_cli/roles`, CONSOLE_SUCCESS_URL: `${Q}/oauth/code/success?app=claude-code`, CLAUDEAI_SUCCESS_URL: `${Q}/oauth/code/success?app=claude-code`, MANUAL_REDIRECT_URL: `${Q}/oauth/code/callback`, OAUTH_FILE_SUFFIX: "-custom-oauth" };
  }
  let J = process.env.CLAUDE_CODE_OAUTH_CLIENT_ID;
  if (J) $ = { ...$, CLIENT_ID: J };
  return $;
}
var fV = "-credentials";
function gV($ = "") {
  let X = v4(), Q = !process.env.CLAUDE_CONFIG_DIR ? "" : `-${(0, import_crypto5.createHash)("sha256").update(X).digest("hex").substring(0, 8)}`;
  return `Claude Code${yV().OAUTH_FILE_SUFFIX}${$}${Q}`;
}
function hV() {
  try {
    return process.env.USER || (0, import_os3.userInfo)().username;
  } catch (e2) {
    return "claude-code-user";
  }
}
var X$;
(function($) {
  $.assertEqual = (Y) => {
  };
  function X(Y) {
  }
  $.assertIs = X;
  function J(Y) {
    throw Error();
  }
  $.assertNever = J, $.arrayToEnum = (Y) => {
    let W = {};
    for (let z8 of Y) W[z8] = z8;
    return W;
  }, $.getValidEnumValues = (Y) => {
    let W = $.objectKeys(Y).filter((G) => typeof Y[Y[G]] !== "number"), z8 = {};
    for (let G of W) z8[G] = Y[G];
    return $.objectValues(z8);
  }, $.objectValues = (Y) => {
    return $.objectKeys(Y).map(function(W) {
      return Y[W];
    });
  }, $.objectKeys = typeof Object.keys === "function" ? (Y) => Object.keys(Y) : (Y) => {
    let W = [];
    for (let z8 in Y) if (Object.prototype.hasOwnProperty.call(Y, z8)) W.push(z8);
    return W;
  }, $.find = (Y, W) => {
    for (let z8 of Y) if (W(z8)) return z8;
    return;
  }, $.isInteger = typeof Number.isInteger === "function" ? (Y) => Number.isInteger(Y) : (Y) => typeof Y === "number" && Number.isFinite(Y) && Math.floor(Y) === Y;
  function Q(Y, W = " | ") {
    return Y.map((z8) => typeof z8 === "string" ? `'${z8}'` : z8).join(W);
  }
  $.joinValues = Q, $.jsonStringifyReplacer = (Y, W) => {
    if (typeof W === "bigint") return W.toString();
    return W;
  };
})(X$ || (X$ = {}));
var uV;
(function($) {
  $.mergeShapes = (X, J) => {
    return { ...X, ...J };
  };
})(uV || (uV = {}));
var E = X$.arrayToEnum(["string", "nan", "number", "integer", "float", "boolean", "date", "bigint", "symbol", "function", "undefined", "null", "array", "object", "unknown", "promise", "void", "never", "map", "set"]);
var N4 = ($) => {
  switch (typeof $) {
    case "undefined":
      return E.undefined;
    case "string":
      return E.string;
    case "number":
      return Number.isNaN($) ? E.nan : E.number;
    case "boolean":
      return E.boolean;
    case "function":
      return E.function;
    case "bigint":
      return E.bigint;
    case "symbol":
      return E.symbol;
    case "object":
      if (Array.isArray($)) return E.array;
      if ($ === null) return E.null;
      if ($.then && typeof $.then === "function" && $.catch && typeof $.catch === "function") return E.promise;
      if (typeof Map < "u" && $ instanceof Map) return E.map;
      if (typeof Set < "u" && $ instanceof Set) return E.set;
      if (typeof Date < "u" && $ instanceof Date) return E.date;
      return E.object;
    default:
      return E.unknown;
  }
};
var b = X$.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"]);
var L6 = class _L6 extends Error {
  get errors() {
    return this.issues;
  }
  constructor($) {
    super();
    this.issues = [], this.addIssue = (J) => {
      this.issues = [...this.issues, J];
    }, this.addIssues = (J = []) => {
      this.issues = [...this.issues, ...J];
    };
    let X = new.target.prototype;
    if (Object.setPrototypeOf) Object.setPrototypeOf(this, X);
    else this.__proto__ = X;
    this.name = "ZodError", this.issues = $;
  }
  format($) {
    let X = $ || function(Y) {
      return Y.message;
    }, J = { _errors: [] }, Q = (Y) => {
      for (let W of Y.issues) if (W.code === "invalid_union") W.unionErrors.map(Q);
      else if (W.code === "invalid_return_type") Q(W.returnTypeError);
      else if (W.code === "invalid_arguments") Q(W.argumentsError);
      else if (W.path.length === 0) J._errors.push(X(W));
      else {
        let z8 = J, G = 0;
        while (G < W.path.length) {
          let U = W.path[G];
          if (G !== W.path.length - 1) z8[U] = z8[U] || { _errors: [] };
          else z8[U] = z8[U] || { _errors: [] }, z8[U]._errors.push(X(W));
          z8 = z8[U], G++;
        }
      }
    };
    return Q(this), J;
  }
  static assert($) {
    if (!($ instanceof _L6)) throw Error(`Not a ZodError: ${$}`);
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, X$.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten($ = (X) => X.message) {
    let X = {}, J = [];
    for (let Q of this.issues) if (Q.path.length > 0) {
      let Y = Q.path[0];
      X[Y] = X[Y] || [], X[Y].push($(Q));
    } else J.push($(Q));
    return { formErrors: J, fieldErrors: X };
  }
  get formErrors() {
    return this.flatten();
  }
};
L6.create = ($) => {
  return new L6($);
};
var kA = ($, X) => {
  let J;
  switch ($.code) {
    case b.invalid_type:
      if ($.received === E.undefined) J = "Required";
      else J = `Expected ${$.expected}, received ${$.received}`;
      break;
    case b.invalid_literal:
      J = `Invalid literal value, expected ${JSON.stringify($.expected, X$.jsonStringifyReplacer)}`;
      break;
    case b.unrecognized_keys:
      J = `Unrecognized key(s) in object: ${X$.joinValues($.keys, ", ")}`;
      break;
    case b.invalid_union:
      J = "Invalid input";
      break;
    case b.invalid_union_discriminator:
      J = `Invalid discriminator value. Expected ${X$.joinValues($.options)}`;
      break;
    case b.invalid_enum_value:
      J = `Invalid enum value. Expected ${X$.joinValues($.options)}, received '${$.received}'`;
      break;
    case b.invalid_arguments:
      J = "Invalid function arguments";
      break;
    case b.invalid_return_type:
      J = "Invalid function return type";
      break;
    case b.invalid_date:
      J = "Invalid date";
      break;
    case b.invalid_string:
      if (typeof $.validation === "object") if ("includes" in $.validation) {
        if (J = `Invalid input: must include "${$.validation.includes}"`, typeof $.validation.position === "number") J = `${J} at one or more positions greater than or equal to ${$.validation.position}`;
      } else if ("startsWith" in $.validation) J = `Invalid input: must start with "${$.validation.startsWith}"`;
      else if ("endsWith" in $.validation) J = `Invalid input: must end with "${$.validation.endsWith}"`;
      else X$.assertNever($.validation);
      else if ($.validation !== "regex") J = `Invalid ${$.validation}`;
      else J = "Invalid";
      break;
    case b.too_small:
      if ($.type === "array") J = `Array must contain ${$.exact ? "exactly" : $.inclusive ? "at least" : "more than"} ${$.minimum} element(s)`;
      else if ($.type === "string") J = `String must contain ${$.exact ? "exactly" : $.inclusive ? "at least" : "over"} ${$.minimum} character(s)`;
      else if ($.type === "number") J = `Number must be ${$.exact ? "exactly equal to " : $.inclusive ? "greater than or equal to " : "greater than "}${$.minimum}`;
      else if ($.type === "bigint") J = `Number must be ${$.exact ? "exactly equal to " : $.inclusive ? "greater than or equal to " : "greater than "}${$.minimum}`;
      else if ($.type === "date") J = `Date must be ${$.exact ? "exactly equal to " : $.inclusive ? "greater than or equal to " : "greater than "}${new Date(Number($.minimum))}`;
      else J = "Invalid input";
      break;
    case b.too_big:
      if ($.type === "array") J = `Array must contain ${$.exact ? "exactly" : $.inclusive ? "at most" : "less than"} ${$.maximum} element(s)`;
      else if ($.type === "string") J = `String must contain ${$.exact ? "exactly" : $.inclusive ? "at most" : "under"} ${$.maximum} character(s)`;
      else if ($.type === "number") J = `Number must be ${$.exact ? "exactly" : $.inclusive ? "less than or equal to" : "less than"} ${$.maximum}`;
      else if ($.type === "bigint") J = `BigInt must be ${$.exact ? "exactly" : $.inclusive ? "less than or equal to" : "less than"} ${$.maximum}`;
      else if ($.type === "date") J = `Date must be ${$.exact ? "exactly" : $.inclusive ? "smaller than or equal to" : "smaller than"} ${new Date(Number($.maximum))}`;
      else J = "Invalid input";
      break;
    case b.custom:
      J = "Invalid input";
      break;
    case b.invalid_intersection_types:
      J = "Intersection results could not be merged";
      break;
    case b.not_multiple_of:
      J = `Number must be a multiple of ${$.multipleOf}`;
      break;
    case b.not_finite:
      J = "Number must be finite";
      break;
    default:
      J = X.defaultError, X$.assertNever($);
  }
  return { message: J };
};
var h4 = kA;
var _A = h4;
function HX() {
  return _A;
}
var aJ = ($) => {
  let { data: X, path: J, errorMaps: Q, issueData: Y } = $, W = [...J, ...Y.path || []], z8 = { ...Y, path: W };
  if (Y.message !== void 0) return { ...Y, path: W, message: Y.message };
  let G = "", U = Q.filter((H) => !!H).slice().reverse();
  for (let H of U) G = H(z8, { data: X, defaultError: G }).message;
  return { ...Y, path: W, message: G };
};
function C($, X) {
  let J = HX(), Q = aJ({ issueData: X, data: $.data, path: $.path, errorMaps: [$.common.contextualErrorMap, $.schemaErrorMap, J, J === h4 ? void 0 : h4].filter((Y) => !!Y) });
  $.common.issues.push(Q);
}
var c$ = class _c$ {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid") this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted") this.value = "aborted";
  }
  static mergeArray($, X) {
    let J = [];
    for (let Q of X) {
      if (Q.status === "aborted") return l;
      if (Q.status === "dirty") $.dirty();
      J.push(Q.value);
    }
    return { status: $.value, value: J };
  }
  static async mergeObjectAsync($, X) {
    let J = [];
    for (let Q of X) {
      let Y = await Q.key, W = await Q.value;
      J.push({ key: Y, value: W });
    }
    return _c$.mergeObjectSync($, J);
  }
  static mergeObjectSync($, X) {
    let J = {};
    for (let Q of X) {
      let { key: Y, value: W } = Q;
      if (Y.status === "aborted") return l;
      if (W.status === "aborted") return l;
      if (Y.status === "dirty") $.dirty();
      if (W.status === "dirty") $.dirty();
      if (Y.value !== "__proto__" && (typeof W.value < "u" || Q.alwaysSet)) J[Y.value] = W.value;
    }
    return { status: $.value, value: J };
  }
};
var l = Object.freeze({ status: "aborted" });
var L0 = ($) => ({ status: "dirty", value: $ });
var t$ = ($) => ({ status: "valid", value: $ });
var AW = ($) => $.status === "aborted";
var IW = ($) => $.status === "dirty";
var I1 = ($) => $.status === "valid";
var KX = ($) => typeof Promise < "u" && $ instanceof Promise;
var f;
(function($) {
  $.errToObj = (X) => typeof X === "string" ? { message: X } : X || {}, $.toString = (X) => typeof X === "string" ? X : X == null ? void 0 : X.message;
})(f || (f = {}));
var y6 = class {
  constructor($, X, J, Q) {
    this._cachedPath = [], this.parent = $, this.data = X, this._path = J, this._key = Q;
  }
  get path() {
    if (!this._cachedPath.length) if (Array.isArray(this._key)) this._cachedPath.push(...this._path, ...this._key);
    else this._cachedPath.push(...this._path, this._key);
    return this._cachedPath;
  }
};
var mV = ($, X) => {
  if (I1(X)) return { success: true, data: X.value };
  else {
    if (!$.common.issues.length) throw Error("Validation failed but no issues detected.");
    return { success: false, get error() {
      if (this._error) return this._error;
      let J = new L6($.common.issues);
      return this._error = J, this._error;
    } };
  }
};
function o($) {
  if (!$) return {};
  let { errorMap: X, invalid_type_error: J, required_error: Q, description: Y } = $;
  if (X && (J || Q)) throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  if (X) return { errorMap: X, description: Y };
  return { errorMap: (z8, G) => {
    var _a3, _b2;
    let { message: U } = $;
    if (z8.code === "invalid_enum_value") return { message: U != null ? U : G.defaultError };
    if (typeof G.data > "u") return { message: (_a3 = U != null ? U : Q) != null ? _a3 : G.defaultError };
    if (z8.code !== "invalid_type") return { message: G.defaultError };
    return { message: (_b2 = U != null ? U : J) != null ? _b2 : G.defaultError };
  }, description: Y };
}
var e = class {
  get description() {
    return this._def.description;
  }
  _getType($) {
    return N4($.data);
  }
  _getOrReturnCtx($, X) {
    return X || { common: $.parent.common, data: $.data, parsedType: N4($.data), schemaErrorMap: this._def.errorMap, path: $.path, parent: $.parent };
  }
  _processInputParams($) {
    return { status: new c$(), ctx: { common: $.parent.common, data: $.data, parsedType: N4($.data), schemaErrorMap: this._def.errorMap, path: $.path, parent: $.parent } };
  }
  _parseSync($) {
    let X = this._parse($);
    if (KX(X)) throw Error("Synchronous parse encountered promise.");
    return X;
  }
  _parseAsync($) {
    let X = this._parse($);
    return Promise.resolve(X);
  }
  parse($, X) {
    let J = this.safeParse($, X);
    if (J.success) return J.data;
    throw J.error;
  }
  safeParse($, X) {
    var _a3;
    let J = { common: { issues: [], async: (_a3 = X == null ? void 0 : X.async) != null ? _a3 : false, contextualErrorMap: X == null ? void 0 : X.errorMap }, path: (X == null ? void 0 : X.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data: $, parsedType: N4($) }, Q = this._parseSync({ data: $, path: J.path, parent: J });
    return mV(J, Q);
  }
  "~validate"($) {
    var _a3, _b2;
    let X = { common: { issues: [], async: !!this["~standard"].async }, path: [], schemaErrorMap: this._def.errorMap, parent: null, data: $, parsedType: N4($) };
    if (!this["~standard"].async) try {
      let J = this._parseSync({ data: $, path: [], parent: X });
      return I1(J) ? { value: J.value } : { issues: X.common.issues };
    } catch (J) {
      if ((_b2 = (_a3 = J == null ? void 0 : J.message) == null ? void 0 : _a3.toLowerCase()) == null ? void 0 : _b2.includes("encountered")) this["~standard"].async = true;
      X.common = { issues: [], async: true };
    }
    return this._parseAsync({ data: $, path: [], parent: X }).then((J) => I1(J) ? { value: J.value } : { issues: X.common.issues });
  }
  async parseAsync($, X) {
    let J = await this.safeParseAsync($, X);
    if (J.success) return J.data;
    throw J.error;
  }
  async safeParseAsync($, X) {
    let J = { common: { issues: [], contextualErrorMap: X == null ? void 0 : X.errorMap, async: true }, path: (X == null ? void 0 : X.path) || [], schemaErrorMap: this._def.errorMap, parent: null, data: $, parsedType: N4($) }, Q = this._parse({ data: $, path: J.path, parent: J }), Y = await (KX(Q) ? Q : Promise.resolve(Q));
    return mV(J, Y);
  }
  refine($, X) {
    let J = (Q) => {
      if (typeof X === "string" || typeof X > "u") return { message: X };
      else if (typeof X === "function") return X(Q);
      else return X;
    };
    return this._refinement((Q, Y) => {
      let W = $(Q), z8 = () => Y.addIssue({ code: b.custom, ...J(Q) });
      if (typeof Promise < "u" && W instanceof Promise) return W.then((G) => {
        if (!G) return z8(), false;
        else return true;
      });
      if (!W) return z8(), false;
      else return true;
    });
  }
  refinement($, X) {
    return this._refinement((J, Q) => {
      if (!$(J)) return Q.addIssue(typeof X === "function" ? X(J, Q) : X), false;
      else return true;
    });
  }
  _refinement($) {
    return new t6({ schema: this, typeName: Z.ZodEffects, effect: { type: "refinement", refinement: $ } });
  }
  superRefine($) {
    return this._refinement($);
  }
  constructor($) {
    this.spa = this.safeParseAsync, this._def = $, 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: (X) => this["~validate"](X) };
  }
  optional() {
    return I6.create(this, this._def);
  }
  nullable() {
    return u4.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return o6.create(this);
  }
  promise() {
    return A0.create(this, this._def);
  }
  or($) {
    return BX.create([this, $], this._def);
  }
  and($) {
    return qX.create(this, $, this._def);
  }
  transform($) {
    return new t6({ ...o(this._def), schema: this, typeName: Z.ZodEffects, effect: { type: "transform", transform: $ } });
  }
  default($) {
    let X = typeof $ === "function" ? $ : () => $;
    return new FX({ ...o(this._def), innerType: this, defaultValue: X, typeName: Z.ZodDefault });
  }
  brand() {
    return new RW({ typeName: Z.ZodBranded, type: this, ...o(this._def) });
  }
  catch($) {
    let X = typeof $ === "function" ? $ : () => $;
    return new MX({ ...o(this._def), innerType: this, catchValue: X, typeName: Z.ZodCatch });
  }
  describe($) {
    return new this.constructor({ ...this._def, description: $ });
  }
  pipe($) {
    return WY.create(this, $);
  }
  readonly() {
    return AX.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
var xA = /^c[^\s-]{8,}$/i;
var TA = /^[0-9a-z]+$/;
var yA = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var fA = /^[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;
var gA = /^[a-z0-9_-]{21}$/i;
var hA = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var uA = /^[-+]?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)?)??$/;
var mA = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var lA = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";
var bW;
var cA = /^(?:(?: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])$/;
var pA = /^(?:(?: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])$/;
var dA = /^(([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]))$/;
var iA = /^(([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])$/;
var nA = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var rA = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var lV = "((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))";
var oA = new RegExp(`^${lV}$`);
function cV($) {
  let X = "[0-5]\\d";
  if ($.precision) X = `${X}\\.\\d{${$.precision}}`;
  else if ($.precision == null) X = `${X}(\\.\\d+)?`;
  let J = $.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${X})${J}`;
}
function tA($) {
  return new RegExp(`^${cV($)}$`);
}
function aA($) {
  let X = `${lV}T${cV($)}`, J = [];
  if (J.push($.local ? "Z?" : "Z"), $.offset) J.push("([+-]\\d{2}:?\\d{2})");
  return X = `${X}(${J.join("|")})`, new RegExp(`^${X}$`);
}
function sA($, X) {
  if ((X === "v4" || !X) && cA.test($)) return true;
  if ((X === "v6" || !X) && dA.test($)) return true;
  return false;
}
function eA($, X) {
  if (!hA.test($)) return false;
  try {
    let [J] = $.split(".");
    if (!J) return false;
    let Q = J.replace(/-/g, "+").replace(/_/g, "/").padEnd(J.length + (4 - J.length % 4) % 4, "="), Y = JSON.parse(atob(Q));
    if (typeof Y !== "object" || Y === null) return false;
    if ("typ" in Y && (Y == null ? void 0 : Y.typ) !== "JWT") return false;
    if (!Y.alg) return false;
    if (X && Y.alg !== X) return false;
    return true;
  } catch (e2) {
    return false;
  }
}
function $I($, X) {
  if ((X === "v4" || !X) && pA.test($)) return true;
  if ((X === "v6" || !X) && iA.test($)) return true;
  return false;
}
var w4 = class _w4 extends e {
  _parse($) {
    if (this._def.coerce) $.data = String($.data);
    if (this._getType($) !== E.string) {
      let Y = this._getOrReturnCtx($);
      return C(Y, { code: b.invalid_type, expected: E.string, received: Y.parsedType }), l;
    }
    let J = new c$(), Q = void 0;
    for (let Y of this._def.checks) if (Y.kind === "min") {
      if ($.data.length < Y.value) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.too_small, minimum: Y.value, type: "string", inclusive: true, exact: false, message: Y.message }), J.dirty();
    } else if (Y.kind === "max") {
      if ($.data.length > Y.value) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.too_big, maximum: Y.value, type: "string", inclusive: true, exact: false, message: Y.message }), J.dirty();
    } else if (Y.kind === "length") {
      let W = $.data.length > Y.value, z8 = $.data.length < Y.value;
      if (W || z8) {
        if (Q = this._getOrReturnCtx($, Q), W) C(Q, { code: b.too_big, maximum: Y.value, type: "string", inclusive: true, exact: true, message: Y.message });
        else if (z8) C(Q, { code: b.too_small, minimum: Y.value, type: "string", inclusive: true, exact: true, message: Y.message });
        J.dirty();
      }
    } else if (Y.kind === "email") {
      if (!mA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "email", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "emoji") {
      if (!bW) bW = new RegExp(lA, "u");
      if (!bW.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "emoji", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "uuid") {
      if (!fA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "uuid", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "nanoid") {
      if (!gA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "nanoid", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "cuid") {
      if (!xA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "cuid", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "cuid2") {
      if (!TA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "cuid2", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "ulid") {
      if (!yA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "ulid", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "url") try {
      new URL($.data);
    } catch (e2) {
      Q = this._getOrReturnCtx($, Q), C(Q, { validation: "url", code: b.invalid_string, message: Y.message }), J.dirty();
    }
    else if (Y.kind === "regex") {
      if (Y.regex.lastIndex = 0, !Y.regex.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "regex", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "trim") $.data = $.data.trim();
    else if (Y.kind === "includes") {
      if (!$.data.includes(Y.value, Y.position)) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.invalid_string, validation: { includes: Y.value, position: Y.position }, message: Y.message }), J.dirty();
    } else if (Y.kind === "toLowerCase") $.data = $.data.toLowerCase();
    else if (Y.kind === "toUpperCase") $.data = $.data.toUpperCase();
    else if (Y.kind === "startsWith") {
      if (!$.data.startsWith(Y.value)) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.invalid_string, validation: { startsWith: Y.value }, message: Y.message }), J.dirty();
    } else if (Y.kind === "endsWith") {
      if (!$.data.endsWith(Y.value)) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.invalid_string, validation: { endsWith: Y.value }, message: Y.message }), J.dirty();
    } else if (Y.kind === "datetime") {
      if (!aA(Y).test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.invalid_string, validation: "datetime", message: Y.message }), J.dirty();
    } else if (Y.kind === "date") {
      if (!oA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.invalid_string, validation: "date", message: Y.message }), J.dirty();
    } else if (Y.kind === "time") {
      if (!tA(Y).test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.invalid_string, validation: "time", message: Y.message }), J.dirty();
    } else if (Y.kind === "duration") {
      if (!uA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "duration", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "ip") {
      if (!sA($.data, Y.version)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "ip", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "jwt") {
      if (!eA($.data, Y.alg)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "jwt", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "cidr") {
      if (!$I($.data, Y.version)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "cidr", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "base64") {
      if (!nA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "base64", code: b.invalid_string, message: Y.message }), J.dirty();
    } else if (Y.kind === "base64url") {
      if (!rA.test($.data)) Q = this._getOrReturnCtx($, Q), C(Q, { validation: "base64url", code: b.invalid_string, message: Y.message }), J.dirty();
    } else X$.assertNever(Y);
    return { status: J.value, value: $.data };
  }
  _regex($, X, J) {
    return this.refinement((Q) => $.test(Q), { validation: X, code: b.invalid_string, ...f.errToObj(J) });
  }
  _addCheck($) {
    return new _w4({ ...this._def, checks: [...this._def.checks, $] });
  }
  email($) {
    return this._addCheck({ kind: "email", ...f.errToObj($) });
  }
  url($) {
    return this._addCheck({ kind: "url", ...f.errToObj($) });
  }
  emoji($) {
    return this._addCheck({ kind: "emoji", ...f.errToObj($) });
  }
  uuid($) {
    return this._addCheck({ kind: "uuid", ...f.errToObj($) });
  }
  nanoid($) {
    return this._addCheck({ kind: "nanoid", ...f.errToObj($) });
  }
  cuid($) {
    return this._addCheck({ kind: "cuid", ...f.errToObj($) });
  }
  cuid2($) {
    return this._addCheck({ kind: "cuid2", ...f.errToObj($) });
  }
  ulid($) {
    return this._addCheck({ kind: "ulid", ...f.errToObj($) });
  }
  base64($) {
    return this._addCheck({ kind: "base64", ...f.errToObj($) });
  }
  base64url($) {
    return this._addCheck({ kind: "base64url", ...f.errToObj($) });
  }
  jwt($) {
    return this._addCheck({ kind: "jwt", ...f.errToObj($) });
  }
  ip($) {
    return this._addCheck({ kind: "ip", ...f.errToObj($) });
  }
  cidr($) {
    return this._addCheck({ kind: "cidr", ...f.errToObj($) });
  }
  datetime($) {
    var _a3, _b2;
    if (typeof $ === "string") return this._addCheck({ kind: "datetime", precision: null, offset: false, local: false, message: $ });
    return this._addCheck({ kind: "datetime", precision: typeof ($ == null ? void 0 : $.precision) > "u" ? null : $ == null ? void 0 : $.precision, offset: (_a3 = $ == null ? void 0 : $.offset) != null ? _a3 : false, local: (_b2 = $ == null ? void 0 : $.local) != null ? _b2 : false, ...f.errToObj($ == null ? void 0 : $.message) });
  }
  date($) {
    return this._addCheck({ kind: "date", message: $ });
  }
  time($) {
    if (typeof $ === "string") return this._addCheck({ kind: "time", precision: null, message: $ });
    return this._addCheck({ kind: "time", precision: typeof ($ == null ? void 0 : $.precision) > "u" ? null : $ == null ? void 0 : $.precision, ...f.errToObj($ == null ? void 0 : $.message) });
  }
  duration($) {
    return this._addCheck({ kind: "duration", ...f.errToObj($) });
  }
  regex($, X) {
    return this._addCheck({ kind: "regex", regex: $, ...f.errToObj(X) });
  }
  includes($, X) {
    return this._addCheck({ kind: "includes", value: $, position: X == null ? void 0 : X.position, ...f.errToObj(X == null ? void 0 : X.message) });
  }
  startsWith($, X) {
    return this._addCheck({ kind: "startsWith", value: $, ...f.errToObj(X) });
  }
  endsWith($, X) {
    return this._addCheck({ kind: "endsWith", value: $, ...f.errToObj(X) });
  }
  min($, X) {
    return this._addCheck({ kind: "min", value: $, ...f.errToObj(X) });
  }
  max($, X) {
    return this._addCheck({ kind: "max", value: $, ...f.errToObj(X) });
  }
  length($, X) {
    return this._addCheck({ kind: "length", value: $, ...f.errToObj(X) });
  }
  nonempty($) {
    return this.min(1, f.errToObj($));
  }
  trim() {
    return new _w4({ ...this._def, checks: [...this._def.checks, { kind: "trim" }] });
  }
  toLowerCase() {
    return new _w4({ ...this._def, checks: [...this._def.checks, { kind: "toLowerCase" }] });
  }
  toUpperCase() {
    return new _w4({ ...this._def, checks: [...this._def.checks, { kind: "toUpperCase" }] });
  }
  get isDatetime() {
    return !!this._def.checks.find(($) => $.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find(($) => $.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find(($) => $.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find(($) => $.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find(($) => $.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find(($) => $.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find(($) => $.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find(($) => $.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find(($) => $.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find(($) => $.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find(($) => $.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find(($) => $.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find(($) => $.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find(($) => $.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find(($) => $.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find(($) => $.kind === "base64url");
  }
  get minLength() {
    let $ = null;
    for (let X of this._def.checks) if (X.kind === "min") {
      if ($ === null || X.value > $) $ = X.value;
    }
    return $;
  }
  get maxLength() {
    let $ = null;
    for (let X of this._def.checks) if (X.kind === "max") {
      if ($ === null || X.value < $) $ = X.value;
    }
    return $;
  }
};
w4.create = ($) => {
  var _a3;
  return new w4({ checks: [], typeName: Z.ZodString, coerce: (_a3 = $ == null ? void 0 : $.coerce) != null ? _a3 : false, ...o($) });
};
function XI($, X) {
  let J = ($.toString().split(".")[1] || "").length, Q = (X.toString().split(".")[1] || "").length, Y = J > Q ? J : Q, W = Number.parseInt($.toFixed(Y).replace(".", "")), z8 = Number.parseInt(X.toFixed(Y).replace(".", ""));
  return W % z8 / 10 ** Y;
}
var j0 = class _j0 extends e {
  constructor() {
    super(...arguments);
    this.min = this.gte, this.max = this.lte, this.step = this.multipleOf;
  }
  _parse($) {
    if (this._def.coerce) $.data = Number($.data);
    if (this._getType($) !== E.number) {
      let Y = this._getOrReturnCtx($);
      return C(Y, { code: b.invalid_type, expected: E.number, received: Y.parsedType }), l;
    }
    let J = void 0, Q = new c$();
    for (let Y of this._def.checks) if (Y.kind === "int") {
      if (!X$.isInteger($.data)) J = this._getOrReturnCtx($, J), C(J, { code: b.invalid_type, expected: "integer", received: "float", message: Y.message }), Q.dirty();
    } else if (Y.kind === "min") {
      if (Y.inclusive ? $.data < Y.value : $.data <= Y.value) J = this._getOrReturnCtx($, J), C(J, { code: b.too_small, minimum: Y.value, type: "number", inclusive: Y.inclusive, exact: false, message: Y.message }), Q.dirty();
    } else if (Y.kind === "max") {
      if (Y.inclusive ? $.data > Y.value : $.data >= Y.value) J = this._getOrReturnCtx($, J), C(J, { code: b.too_big, maximum: Y.value, type: "number", inclusive: Y.inclusive, exact: false, message: Y.message }), Q.dirty();
    } else if (Y.kind === "multipleOf") {
      if (XI($.data, Y.value) !== 0) J = this._getOrReturnCtx($, J), C(J, { code: b.not_multiple_of, multipleOf: Y.value, message: Y.message }), Q.dirty();
    } else if (Y.kind === "finite") {
      if (!Number.isFinite($.data)) J = this._getOrReturnCtx($, J), C(J, { code: b.not_finite, message: Y.message }), Q.dirty();
    } else X$.assertNever(Y);
    return { status: Q.value, value: $.data };
  }
  gte($, X) {
    return this.setLimit("min", $, true, f.toString(X));
  }
  gt($, X) {
    return this.setLimit("min", $, false, f.toString(X));
  }
  lte($, X) {
    return this.setLimit("max", $, true, f.toString(X));
  }
  lt($, X) {
    return this.setLimit("max", $, false, f.toString(X));
  }
  setLimit($, X, J, Q) {
    return new _j0({ ...this._def, checks: [...this._def.checks, { kind: $, value: X, inclusive: J, message: f.toString(Q) }] });
  }
  _addCheck($) {
    return new _j0({ ...this._def, checks: [...this._def.checks, $] });
  }
  int($) {
    return this._addCheck({ kind: "int", message: f.toString($) });
  }
  positive($) {
    return this._addCheck({ kind: "min", value: 0, inclusive: false, message: f.toString($) });
  }
  negative($) {
    return this._addCheck({ kind: "max", value: 0, inclusive: false, message: f.toString($) });
  }
  nonpositive($) {
    return this._addCheck({ kind: "max", value: 0, inclusive: true, message: f.toString($) });
  }
  nonnegative($) {
    return this._addCheck({ kind: "min", value: 0, inclusive: true, message: f.toString($) });
  }
  multipleOf($, X) {
    return this._addCheck({ kind: "multipleOf", value: $, message: f.toString(X) });
  }
  finite($) {
    return this._addCheck({ kind: "finite", message: f.toString($) });
  }
  safe($) {
    return this._addCheck({ kind: "min", inclusive: true, value: Number.MIN_SAFE_INTEGER, message: f.toString($) })._addCheck({ kind: "max", inclusive: true, value: Number.MAX_SAFE_INTEGER, message: f.toString($) });
  }
  get minValue() {
    let $ = null;
    for (let X of this._def.checks) if (X.kind === "min") {
      if ($ === null || X.value > $) $ = X.value;
    }
    return $;
  }
  get maxValue() {
    let $ = null;
    for (let X of this._def.checks) if (X.kind === "max") {
      if ($ === null || X.value < $) $ = X.value;
    }
    return $;
  }
  get isInt() {
    return !!this._def.checks.find(($) => $.kind === "int" || $.kind === "multipleOf" && X$.isInteger($.value));
  }
  get isFinite() {
    let $ = null, X = null;
    for (let J of this._def.checks) if (J.kind === "finite" || J.kind === "int" || J.kind === "multipleOf") return true;
    else if (J.kind === "min") {
      if (X === null || J.value > X) X = J.value;
    } else if (J.kind === "max") {
      if ($ === null || J.value < $) $ = J.value;
    }
    return Number.isFinite(X) && Number.isFinite($);
  }
};
j0.create = ($) => {
  return new j0({ checks: [], typeName: Z.ZodNumber, coerce: ($ == null ? void 0 : $.coerce) || false, ...o($) });
};
var F0 = class _F0 extends e {
  constructor() {
    super(...arguments);
    this.min = this.gte, this.max = this.lte;
  }
  _parse($) {
    if (this._def.coerce) try {
      $.data = BigInt($.data);
    } catch (e2) {
      return this._getInvalidInput($);
    }
    if (this._getType($) !== E.bigint) return this._getInvalidInput($);
    let J = void 0, Q = new c$();
    for (let Y of this._def.checks) if (Y.kind === "min") {
      if (Y.inclusive ? $.data < Y.value : $.data <= Y.value) J = this._getOrReturnCtx($, J), C(J, { code: b.too_small, type: "bigint", minimum: Y.value, inclusive: Y.inclusive, message: Y.message }), Q.dirty();
    } else if (Y.kind === "max") {
      if (Y.inclusive ? $.data > Y.value : $.data >= Y.value) J = this._getOrReturnCtx($, J), C(J, { code: b.too_big, type: "bigint", maximum: Y.value, inclusive: Y.inclusive, message: Y.message }), Q.dirty();
    } else if (Y.kind === "multipleOf") {
      if ($.data % Y.value !== BigInt(0)) J = this._getOrReturnCtx($, J), C(J, { code: b.not_multiple_of, multipleOf: Y.value, message: Y.message }), Q.dirty();
    } else X$.assertNever(Y);
    return { status: Q.value, value: $.data };
  }
  _getInvalidInput($) {
    let X = this._getOrReturnCtx($);
    return C(X, { code: b.invalid_type, expected: E.bigint, received: X.parsedType }), l;
  }
  gte($, X) {
    return this.setLimit("min", $, true, f.toString(X));
  }
  gt($, X) {
    return this.setLimit("min", $, false, f.toString(X));
  }
  lte($, X) {
    return this.setLimit("max", $, true, f.toString(X));
  }
  lt($, X) {
    return this.setLimit("max", $, false, f.toString(X));
  }
  setLimit($, X, J, Q) {
    return new _F0({ ...this._def, checks: [...this._def.checks, { kind: $, value: X, inclusive: J, message: f.toString(Q) }] });
  }
  _addCheck($) {
    return new _F0({ ...this._def, checks: [...this._def.checks, $] });
  }
  positive($) {
    return this._addCheck({ kind: "min", value: BigInt(0), inclusive: false, message: f.toString($) });
  }
  negative($) {
    return this._addCheck({ kind: "max", value: BigInt(0), inclusive: false, message: f.toString($) });
  }
  nonpositive($) {
    return this._addCheck({ kind: "max", value: BigInt(0), inclusive: true, message: f.toString($) });
  }
  nonnegative($) {
    return this._addCheck({ kind: "min", value: BigInt(0), inclusive: true, message: f.toString($) });
  }
  multipleOf($, X) {
    return this._addCheck({ kind: "multipleOf", value: $, message: f.toString(X) });
  }
  get minValue() {
    let $ = null;
    for (let X of this._def.checks) if (X.kind === "min") {
      if ($ === null || X.value > $) $ = X.value;
    }
    return $;
  }
  get maxValue() {
    let $ = null;
    for (let X of this._def.checks) if (X.kind === "max") {
      if ($ === null || X.value < $) $ = X.value;
    }
    return $;
  }
};
F0.create = ($) => {
  var _a3;
  return new F0({ checks: [], typeName: Z.ZodBigInt, coerce: (_a3 = $ == null ? void 0 : $.coerce) != null ? _a3 : false, ...o($) });
};
var sJ = class extends e {
  _parse($) {
    if (this._def.coerce) $.data = Boolean($.data);
    if (this._getType($) !== E.boolean) {
      let J = this._getOrReturnCtx($);
      return C(J, { code: b.invalid_type, expected: E.boolean, received: J.parsedType }), l;
    }
    return t$($.data);
  }
};
sJ.create = ($) => {
  return new sJ({ typeName: Z.ZodBoolean, coerce: ($ == null ? void 0 : $.coerce) || false, ...o($) });
};
var NX = class _NX extends e {
  _parse($) {
    if (this._def.coerce) $.data = new Date($.data);
    if (this._getType($) !== E.date) {
      let Y = this._getOrReturnCtx($);
      return C(Y, { code: b.invalid_type, expected: E.date, received: Y.parsedType }), l;
    }
    if (Number.isNaN($.data.getTime())) {
      let Y = this._getOrReturnCtx($);
      return C(Y, { code: b.invalid_date }), l;
    }
    let J = new c$(), Q = void 0;
    for (let Y of this._def.checks) if (Y.kind === "min") {
      if ($.data.getTime() < Y.value) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.too_small, message: Y.message, inclusive: true, exact: false, minimum: Y.value, type: "date" }), J.dirty();
    } else if (Y.kind === "max") {
      if ($.data.getTime() > Y.value) Q = this._getOrReturnCtx($, Q), C(Q, { code: b.too_big, message: Y.message, inclusive: true, exact: false, maximum: Y.value, type: "date" }), J.dirty();
    } else X$.assertNever(Y);
    return { status: J.value, value: new Date($.data.getTime()) };
  }
  _addCheck($) {
    return new _NX({ ...this._def, checks: [...this._def.checks, $] });
  }
  min($, X) {
    return this._addCheck({ kind: "min", value: $.getTime(), message: f.toString(X) });
  }
  max($, X) {
    return this._addCheck({ kind: "max", value: $.getTime(), message: f.toString(X) });
  }
  get minDate() {
    let $ = null;
    for (let X of this._def.checks) if (X.kind === "min") {
      if ($ === null || X.value > $) $ = X.value;
    }
    return $ != null ? new Date($) : null;
  }
  get maxDate() {
    let $ = null;
    for (let X of this._def.checks) if (X.kind === "max") {
      if ($ === null || X.value < $) $ = X.value;
    }
    return $ != null ? new Date($) : null;
  }
};
NX.create = ($) => {
  return new NX({ checks: [], coerce: ($ == null ? void 0 : $.coerce) || false, typeName: Z.ZodDate, ...o($) });
};
var eJ = class extends e {
  _parse($) {
    if (this._getType($) !== E.symbol) {
      let J = this._getOrReturnCtx($);
      return C(J, { code: b.invalid_type, expected: E.symbol, received: J.parsedType }), l;
    }
    return t$($.data);
  }
};
eJ.create = ($) => {
  return new eJ({ typeName: Z.ZodSymbol, ...o($) });
};
var OX = class extends e {
  _parse($) {
    if (this._getType($) !== E.undefined) {
      let J = this._getOrReturnCtx($);
      return C(J, { code: b.invalid_type, expected: E.undefined, received: J.parsedType }), l;
    }
    return t$($.data);
  }
};
OX.create = ($) => {
  return new OX({ typeName: Z.ZodUndefined, ...o($) });
};
var wX = class extends e {
  _parse($) {
    if (this._getType($) !== E.null) {
      let J = this._getOrReturnCtx($);
      return C(J, { code: b.invalid_type, expected: E.null, received: J.parsedType }), l;
    }
    return t$($.data);
  }
};
wX.create = ($) => {
  return new wX({ typeName: Z.ZodNull, ...o($) });
};
var $Y = class extends e {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse($) {
    return t$($.data);
  }
};
$Y.create = ($) => {
  return new $Y({ typeName: Z.ZodAny, ...o($) });
};
var b1 = class extends e {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse($) {
    return t$($.data);
  }
};
b1.create = ($) => {
  return new b1({ typeName: Z.ZodUnknown, ...o($) });
};
var B4 = class extends e {
  _parse($) {
    let X = this._getOrReturnCtx($);
    return C(X, { code: b.invalid_type, expected: E.never, received: X.parsedType }), l;
  }
};
B4.create = ($) => {
  return new B4({ typeName: Z.ZodNever, ...o($) });
};
var XY = class extends e {
  _parse($) {
    if (this._getType($) !== E.undefined) {
      let J = this._getOrReturnCtx($);
      return C(J, { code: b.invalid_type, expected: E.void, received: J.parsedType }), l;
    }
    return t$($.data);
  }
};
XY.create = ($) => {
  return new XY({ typeName: Z.ZodVoid, ...o($) });
};
var o6 = class _o6 extends e {
  _parse($) {
    let { ctx: X, status: J } = this._processInputParams($), Q = this._def;
    if (X.parsedType !== E.array) return C(X, { code: b.invalid_type, expected: E.array, received: X.parsedType }), l;
    if (Q.exactLength !== null) {
      let W = X.data.length > Q.exactLength.value, z8 = X.data.length < Q.exactLength.value;
      if (W || z8) C(X, { code: W ? b.too_big : b.too_small, minimum: z8 ? Q.exactLength.value : void 0, maximum: W ? Q.exactLength.value : void 0, type: "array", inclusive: true, exact: true, message: Q.exactLength.message }), J.dirty();
    }
    if (Q.minLength !== null) {
      if (X.data.length < Q.minLength.value) C(X, { code: b.too_small, minimum: Q.minLength.value, type: "array", inclusive: true, exact: false, message: Q.minLength.message }), J.dirty();
    }
    if (Q.maxLength !== null) {
      if (X.data.length > Q.maxLength.value) C(X, { code: b.too_big, maximum: Q.maxLength.value, type: "array", inclusive: true, exact: false, message: Q.maxLength.message }), J.dirty();
    }
    if (X.common.async) return Promise.all([...X.data].map((W, z8) => {
      return Q.type._parseAsync(new y6(X, W, X.path, z8));
    })).then((W) => {
      return c$.mergeArray(J, W);
    });
    let Y = [...X.data].map((W, z8) => {
      return Q.type._parseSync(new y6(X, W, X.path, z8));
    });
    return c$.mergeArray(J, Y);
  }
  get element() {
    return this._def.type;
  }
  min($, X) {
    return new _o6({ ...this._def, minLength: { value: $, message: f.toString(X) } });
  }
  max($, X) {
    return new _o6({ ...this._def, maxLength: { value: $, message: f.toString(X) } });
  }
  length($, X) {
    return new _o6({ ...this._def, exactLength: { value: $, message: f.toString(X) } });
  }
  nonempty($) {
    return this.min(1, $);
  }
};
o6.create = ($, X) => {
  return new o6({ type: $, minLength: null, maxLength: null, exactLength: null, typeName: Z.ZodArray, ...o(X) });
};
function D0($) {
  if ($ instanceof R$) {
    let X = {};
    for (let J in $.shape) {
      let Q = $.shape[J];
      X[J] = I6.create(D0(Q));
    }
    return new R$({ ...$._def, shape: () => X });
  } else if ($ instanceof o6) return new o6({ ...$._def, type: D0($.element) });
  else if ($ instanceof I6) return I6.create(D0($.unwrap()));
  else if ($ instanceof u4) return u4.create(D0($.unwrap()));
  else if ($ instanceof q4) return q4.create($.items.map((X) => D0(X)));
  else return $;
}
var R$ = class _R$ extends e {
  constructor() {
    super(...arguments);
    this._cached = null, this.nonstrict = this.passthrough, this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null) return this._cached;
    let $ = this._def.shape(), X = X$.objectKeys($);
    return this._cached = { shape: $, keys: X }, this._cached;
  }
  _parse($) {
    if (this._getType($) !== E.object) {
      let U = this._getOrReturnCtx($);
      return C(U, { code: b.invalid_type, expected: E.object, received: U.parsedType }), l;
    }
    let { status: J, ctx: Q } = this._processInputParams($), { shape: Y, keys: W } = this._getCached(), z8 = [];
    if (!(this._def.catchall instanceof B4 && this._def.unknownKeys === "strip")) {
      for (let U in Q.data) if (!W.includes(U)) z8.push(U);
    }
    let G = [];
    for (let U of W) {
      let H = Y[U], K = Q.data[U];
      G.push({ key: { status: "valid", value: U }, value: H._parse(new y6(Q, K, Q.path, U)), alwaysSet: U in Q.data });
    }
    if (this._def.catchall instanceof B4) {
      let U = this._def.unknownKeys;
      if (U === "passthrough") for (let H of z8) G.push({ key: { status: "valid", value: H }, value: { status: "valid", value: Q.data[H] } });
      else if (U === "strict") {
        if (z8.length > 0) C(Q, { code: b.unrecognized_keys, keys: z8 }), J.dirty();
      } else if (U === "strip") ;
      else throw Error("Internal ZodObject error: invalid unknownKeys value.");
    } else {
      let U = this._def.catchall;
      for (let H of z8) {
        let K = Q.data[H];
        G.push({ key: { status: "valid", value: H }, value: U._parse(new y6(Q, K, Q.path, H)), alwaysSet: H in Q.data });
      }
    }
    if (Q.common.async) return Promise.resolve().then(async () => {
      let U = [];
      for (let H of G) {
        let K = await H.key, V = await H.value;
        U.push({ key: K, value: V, alwaysSet: H.alwaysSet });
      }
      return U;
    }).then((U) => {
      return c$.mergeObjectSync(J, U);
    });
    else return c$.mergeObjectSync(J, G);
  }
  get shape() {
    return this._def.shape();
  }
  strict($) {
    return f.errToObj, new _R$({ ...this._def, unknownKeys: "strict", ...$ !== void 0 ? { errorMap: (X, J) => {
      var _a3, _b2, _c, _d2;
      let Q = (_c = (_b2 = (_a3 = this._def).errorMap) == null ? void 0 : _b2.call(_a3, X, J).message) != null ? _c : J.defaultError;
      if (X.code === "unrecognized_keys") return { message: (_d2 = f.errToObj($).message) != null ? _d2 : Q };
      return { message: Q };
    } } : {} });
  }
  strip() {
    return new _R$({ ...this._def, unknownKeys: "strip" });
  }
  passthrough() {
    return new _R$({ ...this._def, unknownKeys: "passthrough" });
  }
  extend($) {
    return new _R$({ ...this._def, shape: () => ({ ...this._def.shape(), ...$ }) });
  }
  merge($) {
    return new _R$({ unknownKeys: $._def.unknownKeys, catchall: $._def.catchall, shape: () => ({ ...this._def.shape(), ...$._def.shape() }), typeName: Z.ZodObject });
  }
  setKey($, X) {
    return this.augment({ [$]: X });
  }
  catchall($) {
    return new _R$({ ...this._def, catchall: $ });
  }
  pick($) {
    let X = {};
    for (let J of X$.objectKeys($)) if ($[J] && this.shape[J]) X[J] = this.shape[J];
    return new _R$({ ...this._def, shape: () => X });
  }
  omit($) {
    let X = {};
    for (let J of X$.objectKeys(this.shape)) if (!$[J]) X[J] = this.shape[J];
    return new _R$({ ...this._def, shape: () => X });
  }
  deepPartial() {
    return D0(this);
  }
  partial($) {
    let X = {};
    for (let J of X$.objectKeys(this.shape)) {
      let Q = this.shape[J];
      if ($ && !$[J]) X[J] = Q;
      else X[J] = Q.optional();
    }
    return new _R$({ ...this._def, shape: () => X });
  }
  required($) {
    let X = {};
    for (let J of X$.objectKeys(this.shape)) if ($ && !$[J]) X[J] = this.shape[J];
    else {
      let Y = this.shape[J];
      while (Y instanceof I6) Y = Y._def.innerType;
      X[J] = Y;
    }
    return new _R$({ ...this._def, shape: () => X });
  }
  keyof() {
    return pV(X$.objectKeys(this.shape));
  }
};
R$.create = ($, X) => {
  return new R$({ shape: () => $, unknownKeys: "strip", catchall: B4.create(), typeName: Z.ZodObject, ...o(X) });
};
R$.strictCreate = ($, X) => {
  return new R$({ shape: () => $, unknownKeys: "strict", catchall: B4.create(), typeName: Z.ZodObject, ...o(X) });
};
R$.lazycreate = ($, X) => {
  return new R$({ shape: $, unknownKeys: "strip", catchall: B4.create(), typeName: Z.ZodObject, ...o(X) });
};
var BX = class extends e {
  _parse($) {
    let { ctx: X } = this._processInputParams($), J = this._def.options;
    function Q(Y) {
      for (let z8 of Y) if (z8.result.status === "valid") return z8.result;
      for (let z8 of Y) if (z8.result.status === "dirty") return X.common.issues.push(...z8.ctx.common.issues), z8.result;
      let W = Y.map((z8) => new L6(z8.ctx.common.issues));
      return C(X, { code: b.invalid_union, unionErrors: W }), l;
    }
    if (X.common.async) return Promise.all(J.map(async (Y) => {
      let W = { ...X, common: { ...X.common, issues: [] }, parent: null };
      return { result: await Y._parseAsync({ data: X.data, path: X.path, parent: W }), ctx: W };
    })).then(Q);
    else {
      let Y = void 0, W = [];
      for (let G of J) {
        let U = { ...X, common: { ...X.common, issues: [] }, parent: null }, H = G._parseSync({ data: X.data, path: X.path, parent: U });
        if (H.status === "valid") return H;
        else if (H.status === "dirty" && !Y) Y = { result: H, ctx: U };
        if (U.common.issues.length) W.push(U.common.issues);
      }
      if (Y) return X.common.issues.push(...Y.ctx.common.issues), Y.result;
      let z8 = W.map((G) => new L6(G));
      return C(X, { code: b.invalid_union, unionErrors: z8 }), l;
    }
  }
  get options() {
    return this._def.options;
  }
};
BX.create = ($, X) => {
  return new BX({ options: $, typeName: Z.ZodUnion, ...o(X) });
};
var O4 = ($) => {
  if ($ instanceof LX) return O4($.schema);
  else if ($ instanceof t6) return O4($.innerType());
  else if ($ instanceof DX) return [$.value];
  else if ($ instanceof Z1) return $.options;
  else if ($ instanceof jX) return X$.objectValues($.enum);
  else if ($ instanceof FX) return O4($._def.innerType);
  else if ($ instanceof OX) return [void 0];
  else if ($ instanceof wX) return [null];
  else if ($ instanceof I6) return [void 0, ...O4($.unwrap())];
  else if ($ instanceof u4) return [null, ...O4($.unwrap())];
  else if ($ instanceof RW) return O4($.unwrap());
  else if ($ instanceof AX) return O4($.unwrap());
  else if ($ instanceof MX) return O4($._def.innerType);
  else return [];
};
var PW = class _PW extends e {
  _parse($) {
    let { ctx: X } = this._processInputParams($);
    if (X.parsedType !== E.object) return C(X, { code: b.invalid_type, expected: E.object, received: X.parsedType }), l;
    let J = this.discriminator, Q = X.data[J], Y = this.optionsMap.get(Q);
    if (!Y) return C(X, { code: b.invalid_union_discriminator, options: Array.from(this.optionsMap.keys()), path: [J] }), l;
    if (X.common.async) return Y._parseAsync({ data: X.data, path: X.path, parent: X });
    else return Y._parseSync({ data: X.data, path: X.path, parent: X });
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  static create($, X, J) {
    let Q = /* @__PURE__ */ new Map();
    for (let Y of X) {
      let W = O4(Y.shape[$]);
      if (!W.length) throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);
      for (let z8 of W) {
        if (Q.has(z8)) throw Error(`Discriminator property ${String($)} has duplicate value ${String(z8)}`);
        Q.set(z8, Y);
      }
    }
    return new _PW({ typeName: Z.ZodDiscriminatedUnion, discriminator: $, options: X, optionsMap: Q, ...o(J) });
  }
};
function ZW($, X) {
  let J = N4($), Q = N4(X);
  if ($ === X) return { valid: true, data: $ };
  else if (J === E.object && Q === E.object) {
    let Y = X$.objectKeys(X), W = X$.objectKeys($).filter((G) => Y.indexOf(G) !== -1), z8 = { ...$, ...X };
    for (let G of W) {
      let U = ZW($[G], X[G]);
      if (!U.valid) return { valid: false };
      z8[G] = U.data;
    }
    return { valid: true, data: z8 };
  } else if (J === E.array && Q === E.array) {
    if ($.length !== X.length) return { valid: false };
    let Y = [];
    for (let W = 0; W < $.length; W++) {
      let z8 = $[W], G = X[W], U = ZW(z8, G);
      if (!U.valid) return { valid: false };
      Y.push(U.data);
    }
    return { valid: true, data: Y };
  } else if (J === E.date && Q === E.date && +$ === +X) return { valid: true, data: $ };
  else return { valid: false };
}
var qX = class extends e {
  _parse($) {
    let { status: X, ctx: J } = this._processInputParams($), Q = (Y, W) => {
      if (AW(Y) || AW(W)) return l;
      let z8 = ZW(Y.value, W.value);
      if (!z8.valid) return C(J, { code: b.invalid_intersection_types }), l;
      if (IW(Y) || IW(W)) X.dirty();
      return { status: X.value, value: z8.data };
    };
    if (J.common.async) return Promise.all([this._def.left._parseAsync({ data: J.data, path: J.path, parent: J }), this._def.right._parseAsync({ data: J.data, path: J.path, parent: J })]).then(([Y, W]) => Q(Y, W));
    else return Q(this._def.left._parseSync({ data: J.data, path: J.path, parent: J }), this._def.right._parseSync({ data: J.data, path: J.path, parent: J }));
  }
};
qX.create = ($, X, J) => {
  return new qX({ left: $, right: X, typeName: Z.ZodIntersection, ...o(J) });
};
var q4 = class _q4 extends e {
  _parse($) {
    let { status: X, ctx: J } = this._processInputParams($);
    if (J.parsedType !== E.array) return C(J, { code: b.invalid_type, expected: E.array, received: J.parsedType }), l;
    if (J.data.length < this._def.items.length) return C(J, { code: b.too_small, minimum: this._def.items.length, inclusive: true, exact: false, type: "array" }), l;
    if (!this._def.rest && J.data.length > this._def.items.length) C(J, { code: b.too_big, maximum: this._def.items.length, inclusive: true, exact: false, type: "array" }), X.dirty();
    let Y = [...J.data].map((W, z8) => {
      let G = this._def.items[z8] || this._def.rest;
      if (!G) return null;
      return G._parse(new y6(J, W, J.path, z8));
    }).filter((W) => !!W);
    if (J.common.async) return Promise.all(Y).then((W) => {
      return c$.mergeArray(X, W);
    });
    else return c$.mergeArray(X, Y);
  }
  get items() {
    return this._def.items;
  }
  rest($) {
    return new _q4({ ...this._def, rest: $ });
  }
};
q4.create = ($, X) => {
  if (!Array.isArray($)) throw Error("You must pass an array of schemas to z.tuple([ ... ])");
  return new q4({ items: $, typeName: Z.ZodTuple, rest: null, ...o(X) });
};
var JY = class _JY extends e {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse($) {
    let { status: X, ctx: J } = this._processInputParams($);
    if (J.parsedType !== E.object) return C(J, { code: b.invalid_type, expected: E.object, received: J.parsedType }), l;
    let Q = [], Y = this._def.keyType, W = this._def.valueType;
    for (let z8 in J.data) Q.push({ key: Y._parse(new y6(J, z8, J.path, z8)), value: W._parse(new y6(J, J.data[z8], J.path, z8)), alwaysSet: z8 in J.data });
    if (J.common.async) return c$.mergeObjectAsync(X, Q);
    else return c$.mergeObjectSync(X, Q);
  }
  get element() {
    return this._def.valueType;
  }
  static create($, X, J) {
    if (X instanceof e) return new _JY({ keyType: $, valueType: X, typeName: Z.ZodRecord, ...o(J) });
    return new _JY({ keyType: w4.create(), valueType: $, typeName: Z.ZodRecord, ...o(X) });
  }
};
var YY = class extends e {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse($) {
    let { status: X, ctx: J } = this._processInputParams($);
    if (J.parsedType !== E.map) return C(J, { code: b.invalid_type, expected: E.map, received: J.parsedType }), l;
    let Q = this._def.keyType, Y = this._def.valueType, W = [...J.data.entries()].map(([z8, G], U) => {
      return { key: Q._parse(new y6(J, z8, J.path, [U, "key"])), value: Y._parse(new y6(J, G, J.path, [U, "value"])) };
    });
    if (J.common.async) {
      let z8 = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (let G of W) {
          let U = await G.key, H = await G.value;
          if (U.status === "aborted" || H.status === "aborted") return l;
          if (U.status === "dirty" || H.status === "dirty") X.dirty();
          z8.set(U.value, H.value);
        }
        return { status: X.value, value: z8 };
      });
    } else {
      let z8 = /* @__PURE__ */ new Map();
      for (let G of W) {
        let { key: U, value: H } = G;
        if (U.status === "aborted" || H.status === "aborted") return l;
        if (U.status === "dirty" || H.status === "dirty") X.dirty();
        z8.set(U.value, H.value);
      }
      return { status: X.value, value: z8 };
    }
  }
};
YY.create = ($, X, J) => {
  return new YY({ valueType: X, keyType: $, typeName: Z.ZodMap, ...o(J) });
};
var M0 = class _M0 extends e {
  _parse($) {
    let { status: X, ctx: J } = this._processInputParams($);
    if (J.parsedType !== E.set) return C(J, { code: b.invalid_type, expected: E.set, received: J.parsedType }), l;
    let Q = this._def;
    if (Q.minSize !== null) {
      if (J.data.size < Q.minSize.value) C(J, { code: b.too_small, minimum: Q.minSize.value, type: "set", inclusive: true, exact: false, message: Q.minSize.message }), X.dirty();
    }
    if (Q.maxSize !== null) {
      if (J.data.size > Q.maxSize.value) C(J, { code: b.too_big, maximum: Q.maxSize.value, type: "set", inclusive: true, exact: false, message: Q.maxSize.message }), X.dirty();
    }
    let Y = this._def.valueType;
    function W(G) {
      let U = /* @__PURE__ */ new Set();
      for (let H of G) {
        if (H.status === "aborted") return l;
        if (H.status === "dirty") X.dirty();
        U.add(H.value);
      }
      return { status: X.value, value: U };
    }
    let z8 = [...J.data.values()].map((G, U) => Y._parse(new y6(J, G, J.path, U)));
    if (J.common.async) return Promise.all(z8).then((G) => W(G));
    else return W(z8);
  }
  min($, X) {
    return new _M0({ ...this._def, minSize: { value: $, message: f.toString(X) } });
  }
  max($, X) {
    return new _M0({ ...this._def, maxSize: { value: $, message: f.toString(X) } });
  }
  size($, X) {
    return this.min($, X).max($, X);
  }
  nonempty($) {
    return this.min(1, $);
  }
};
M0.create = ($, X) => {
  return new M0({ valueType: $, minSize: null, maxSize: null, typeName: Z.ZodSet, ...o(X) });
};
var VX = class _VX extends e {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse($) {
    let { ctx: X } = this._processInputParams($);
    if (X.parsedType !== E.function) return C(X, { code: b.invalid_type, expected: E.function, received: X.parsedType }), l;
    function J(z8, G) {
      return aJ({ data: z8, path: X.path, errorMaps: [X.common.contextualErrorMap, X.schemaErrorMap, HX(), h4].filter((U) => !!U), issueData: { code: b.invalid_arguments, argumentsError: G } });
    }
    function Q(z8, G) {
      return aJ({ data: z8, path: X.path, errorMaps: [X.common.contextualErrorMap, X.schemaErrorMap, HX(), h4].filter((U) => !!U), issueData: { code: b.invalid_return_type, returnTypeError: G } });
    }
    let Y = { errorMap: X.common.contextualErrorMap }, W = X.data;
    if (this._def.returns instanceof A0) {
      let z8 = this;
      return t$(async function(...G) {
        let U = new L6([]), H = await z8._def.args.parseAsync(G, Y).catch((N) => {
          throw U.addIssue(J(G, N)), U;
        }), K = await Reflect.apply(W, this, H);
        return await z8._def.returns._def.type.parseAsync(K, Y).catch((N) => {
          throw U.addIssue(Q(K, N)), U;
        });
      });
    } else {
      let z8 = this;
      return t$(function(...G) {
        let U = z8._def.args.safeParse(G, Y);
        if (!U.success) throw new L6([J(G, U.error)]);
        let H = Reflect.apply(W, this, U.data), K = z8._def.returns.safeParse(H, Y);
        if (!K.success) throw new L6([Q(H, K.error)]);
        return K.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...$) {
    return new _VX({ ...this._def, args: q4.create($).rest(b1.create()) });
  }
  returns($) {
    return new _VX({ ...this._def, returns: $ });
  }
  implement($) {
    return this.parse($);
  }
  strictImplement($) {
    return this.parse($);
  }
  static create($, X, J) {
    return new _VX({ args: $ ? $ : q4.create([]).rest(b1.create()), returns: X || b1.create(), typeName: Z.ZodFunction, ...o(J) });
  }
};
var LX = class extends e {
  get schema() {
    return this._def.getter();
  }
  _parse($) {
    let { ctx: X } = this._processInputParams($);
    return this._def.getter()._parse({ data: X.data, path: X.path, parent: X });
  }
};
LX.create = ($, X) => {
  return new LX({ getter: $, typeName: Z.ZodLazy, ...o(X) });
};
var DX = class extends e {
  _parse($) {
    if ($.data !== this._def.value) {
      let X = this._getOrReturnCtx($);
      return C(X, { received: X.data, code: b.invalid_literal, expected: this._def.value }), l;
    }
    return { status: "valid", value: $.data };
  }
  get value() {
    return this._def.value;
  }
};
DX.create = ($, X) => {
  return new DX({ value: $, typeName: Z.ZodLiteral, ...o(X) });
};
function pV($, X) {
  return new Z1({ values: $, typeName: Z.ZodEnum, ...o(X) });
}
var Z1 = class _Z1 extends e {
  _parse($) {
    if (typeof $.data !== "string") {
      let X = this._getOrReturnCtx($), J = this._def.values;
      return C(X, { expected: X$.joinValues(J), received: X.parsedType, code: b.invalid_type }), l;
    }
    if (!this._cache) this._cache = new Set(this._def.values);
    if (!this._cache.has($.data)) {
      let X = this._getOrReturnCtx($), J = this._def.values;
      return C(X, { received: X.data, code: b.invalid_enum_value, options: J }), l;
    }
    return t$($.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    let $ = {};
    for (let X of this._def.values) $[X] = X;
    return $;
  }
  get Values() {
    let $ = {};
    for (let X of this._def.values) $[X] = X;
    return $;
  }
  get Enum() {
    let $ = {};
    for (let X of this._def.values) $[X] = X;
    return $;
  }
  extract($, X = this._def) {
    return _Z1.create($, { ...this._def, ...X });
  }
  exclude($, X = this._def) {
    return _Z1.create(this.options.filter((J) => !$.includes(J)), { ...this._def, ...X });
  }
};
Z1.create = pV;
var jX = class extends e {
  _parse($) {
    let X = X$.getValidEnumValues(this._def.values), J = this._getOrReturnCtx($);
    if (J.parsedType !== E.string && J.parsedType !== E.number) {
      let Q = X$.objectValues(X);
      return C(J, { expected: X$.joinValues(Q), received: J.parsedType, code: b.invalid_type }), l;
    }
    if (!this._cache) this._cache = new Set(X$.getValidEnumValues(this._def.values));
    if (!this._cache.has($.data)) {
      let Q = X$.objectValues(X);
      return C(J, { received: J.data, code: b.invalid_enum_value, options: Q }), l;
    }
    return t$($.data);
  }
  get enum() {
    return this._def.values;
  }
};
jX.create = ($, X) => {
  return new jX({ values: $, typeName: Z.ZodNativeEnum, ...o(X) });
};
var A0 = class extends e {
  unwrap() {
    return this._def.type;
  }
  _parse($) {
    let { ctx: X } = this._processInputParams($);
    if (X.parsedType !== E.promise && X.common.async === false) return C(X, { code: b.invalid_type, expected: E.promise, received: X.parsedType }), l;
    let J = X.parsedType === E.promise ? X.data : Promise.resolve(X.data);
    return t$(J.then((Q) => {
      return this._def.type.parseAsync(Q, { path: X.path, errorMap: X.common.contextualErrorMap });
    }));
  }
};
A0.create = ($, X) => {
  return new A0({ type: $, typeName: Z.ZodPromise, ...o(X) });
};
var t6 = class extends e {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === Z.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse($) {
    let { status: X, ctx: J } = this._processInputParams($), Q = this._def.effect || null, Y = { addIssue: (W) => {
      if (C(J, W), W.fatal) X.abort();
      else X.dirty();
    }, get path() {
      return J.path;
    } };
    if (Y.addIssue = Y.addIssue.bind(Y), Q.type === "preprocess") {
      let W = Q.transform(J.data, Y);
      if (J.common.async) return Promise.resolve(W).then(async (z8) => {
        if (X.value === "aborted") return l;
        let G = await this._def.schema._parseAsync({ data: z8, path: J.path, parent: J });
        if (G.status === "aborted") return l;
        if (G.status === "dirty") return L0(G.value);
        if (X.value === "dirty") return L0(G.value);
        return G;
      });
      else {
        if (X.value === "aborted") return l;
        let z8 = this._def.schema._parseSync({ data: W, path: J.path, parent: J });
        if (z8.status === "aborted") return l;
        if (z8.status === "dirty") return L0(z8.value);
        if (X.value === "dirty") return L0(z8.value);
        return z8;
      }
    }
    if (Q.type === "refinement") {
      let W = (z8) => {
        let G = Q.refinement(z8, Y);
        if (J.common.async) return Promise.resolve(G);
        if (G instanceof Promise) throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        return z8;
      };
      if (J.common.async === false) {
        let z8 = this._def.schema._parseSync({ data: J.data, path: J.path, parent: J });
        if (z8.status === "aborted") return l;
        if (z8.status === "dirty") X.dirty();
        return W(z8.value), { status: X.value, value: z8.value };
      } else return this._def.schema._parseAsync({ data: J.data, path: J.path, parent: J }).then((z8) => {
        if (z8.status === "aborted") return l;
        if (z8.status === "dirty") X.dirty();
        return W(z8.value).then(() => {
          return { status: X.value, value: z8.value };
        });
      });
    }
    if (Q.type === "transform") if (J.common.async === false) {
      let W = this._def.schema._parseSync({ data: J.data, path: J.path, parent: J });
      if (!I1(W)) return l;
      let z8 = Q.transform(W.value, Y);
      if (z8 instanceof Promise) throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");
      return { status: X.value, value: z8 };
    } else return this._def.schema._parseAsync({ data: J.data, path: J.path, parent: J }).then((W) => {
      if (!I1(W)) return l;
      return Promise.resolve(Q.transform(W.value, Y)).then((z8) => ({ status: X.value, value: z8 }));
    });
    X$.assertNever(Q);
  }
};
t6.create = ($, X, J) => {
  return new t6({ schema: $, typeName: Z.ZodEffects, effect: X, ...o(J) });
};
t6.createWithPreprocess = ($, X, J) => {
  return new t6({ schema: X, effect: { type: "preprocess", transform: $ }, typeName: Z.ZodEffects, ...o(J) });
};
var I6 = class extends e {
  _parse($) {
    if (this._getType($) === E.undefined) return t$(void 0);
    return this._def.innerType._parse($);
  }
  unwrap() {
    return this._def.innerType;
  }
};
I6.create = ($, X) => {
  return new I6({ innerType: $, typeName: Z.ZodOptional, ...o(X) });
};
var u4 = class extends e {
  _parse($) {
    if (this._getType($) === E.null) return t$(null);
    return this._def.innerType._parse($);
  }
  unwrap() {
    return this._def.innerType;
  }
};
u4.create = ($, X) => {
  return new u4({ innerType: $, typeName: Z.ZodNullable, ...o(X) });
};
var FX = class extends e {
  _parse($) {
    let { ctx: X } = this._processInputParams($), J = X.data;
    if (X.parsedType === E.undefined) J = this._def.defaultValue();
    return this._def.innerType._parse({ data: J, path: X.path, parent: X });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
FX.create = ($, X) => {
  return new FX({ innerType: $, typeName: Z.ZodDefault, defaultValue: typeof X.default === "function" ? X.default : () => X.default, ...o(X) });
};
var MX = class extends e {
  _parse($) {
    let { ctx: X } = this._processInputParams($), J = { ...X, common: { ...X.common, issues: [] } }, Q = this._def.innerType._parse({ data: J.data, path: J.path, parent: { ...J } });
    if (KX(Q)) return Q.then((Y) => {
      return { status: "valid", value: Y.status === "valid" ? Y.value : this._def.catchValue({ get error() {
        return new L6(J.common.issues);
      }, input: J.data }) };
    });
    else return { status: "valid", value: Q.status === "valid" ? Q.value : this._def.catchValue({ get error() {
      return new L6(J.common.issues);
    }, input: J.data }) };
  }
  removeCatch() {
    return this._def.innerType;
  }
};
MX.create = ($, X) => {
  return new MX({ innerType: $, typeName: Z.ZodCatch, catchValue: typeof X.catch === "function" ? X.catch : () => X.catch, ...o(X) });
};
var QY = class extends e {
  _parse($) {
    if (this._getType($) !== E.nan) {
      let J = this._getOrReturnCtx($);
      return C(J, { code: b.invalid_type, expected: E.nan, received: J.parsedType }), l;
    }
    return { status: "valid", value: $.data };
  }
};
QY.create = ($) => {
  return new QY({ typeName: Z.ZodNaN, ...o($) });
};
var RW = class extends e {
  _parse($) {
    let { ctx: X } = this._processInputParams($), J = X.data;
    return this._def.type._parse({ data: J, path: X.path, parent: X });
  }
  unwrap() {
    return this._def.type;
  }
};
var WY = class _WY extends e {
  _parse($) {
    let { status: X, ctx: J } = this._processInputParams($);
    if (J.common.async) return (async () => {
      let Y = await this._def.in._parseAsync({ data: J.data, path: J.path, parent: J });
      if (Y.status === "aborted") return l;
      if (Y.status === "dirty") return X.dirty(), L0(Y.value);
      else return this._def.out._parseAsync({ data: Y.value, path: J.path, parent: J });
    })();
    else {
      let Q = this._def.in._parseSync({ data: J.data, path: J.path, parent: J });
      if (Q.status === "aborted") return l;
      if (Q.status === "dirty") return X.dirty(), { status: "dirty", value: Q.value };
      else return this._def.out._parseSync({ data: Q.value, path: J.path, parent: J });
    }
  }
  static create($, X) {
    return new _WY({ in: $, out: X, typeName: Z.ZodPipeline });
  }
};
var AX = class extends e {
  _parse($) {
    let X = this._def.innerType._parse($), J = (Q) => {
      if (I1(Q)) Q.value = Object.freeze(Q.value);
      return Q;
    };
    return KX(X) ? X.then((Q) => J(Q)) : J(X);
  }
  unwrap() {
    return this._def.innerType;
  }
};
AX.create = ($, X) => {
  return new AX({ innerType: $, typeName: Z.ZodReadonly, ...o(X) });
};
var Qd = { object: R$.lazycreate };
var Z;
(function($) {
  $.ZodString = "ZodString", $.ZodNumber = "ZodNumber", $.ZodNaN = "ZodNaN", $.ZodBigInt = "ZodBigInt", $.ZodBoolean = "ZodBoolean", $.ZodDate = "ZodDate", $.ZodSymbol = "ZodSymbol", $.ZodUndefined = "ZodUndefined", $.ZodNull = "ZodNull", $.ZodAny = "ZodAny", $.ZodUnknown = "ZodUnknown", $.ZodNever = "ZodNever", $.ZodVoid = "ZodVoid", $.ZodArray = "ZodArray", $.ZodObject = "ZodObject", $.ZodUnion = "ZodUnion", $.ZodDiscriminatedUnion = "ZodDiscriminatedUnion", $.ZodIntersection = "ZodIntersection", $.ZodTuple = "ZodTuple", $.ZodRecord = "ZodRecord", $.ZodMap = "ZodMap", $.ZodSet = "ZodSet", $.ZodFunction = "ZodFunction", $.ZodLazy = "ZodLazy", $.ZodLiteral = "ZodLiteral", $.ZodEnum = "ZodEnum", $.ZodEffects = "ZodEffects", $.ZodNativeEnum = "ZodNativeEnum", $.ZodOptional = "ZodOptional", $.ZodNullable = "ZodNullable", $.ZodDefault = "ZodDefault", $.ZodCatch = "ZodCatch", $.ZodPromise = "ZodPromise", $.ZodBranded = "ZodBranded", $.ZodPipeline = "ZodPipeline", $.ZodReadonly = "ZodReadonly";
})(Z || (Z = {}));
var Wd = w4.create;
var zd = j0.create;
var Gd = QY.create;
var Ud = F0.create;
var Hd = sJ.create;
var Kd = NX.create;
var Vd = eJ.create;
var Nd = OX.create;
var Od = wX.create;
var wd = $Y.create;
var Bd = b1.create;
var qd = B4.create;
var Ld = XY.create;
var Dd = o6.create;
var dV = R$.create;
var jd = R$.strictCreate;
var Fd = BX.create;
var Md = PW.create;
var Ad = qX.create;
var Id = q4.create;
var bd = JY.create;
var Zd = YY.create;
var Pd = M0.create;
var Rd = VX.create;
var Ed = LX.create;
var Sd = DX.create;
var vd = Z1.create;
var Cd = jX.create;
var kd = A0.create;
var _d = t6.create;
var xd = I6.create;
var Td = u4.create;
var yd = t6.createWithPreprocess;
var fd = WY.create;
var f6 = {};
H1(f6, { version: () => Cz, util: () => R, treeifyError: () => HY, toJSONSchema: () => g0, toDotPath: () => rV, safeParseAsync: () => c4, safeParse: () => l4, registry: () => gX, regexes: () => p4, prettifyError: () => KY, parseAsync: () => S1, parse: () => E1, locales: () => _0, isValidJWT: () => NN, isValidBase64URL: () => VN, isValidBase64: () => fz, globalRegistry: () => G6, globalConfig: () => IX, function: () => p7, formatError: () => R0, flattenError: () => P0, config: () => E$, clone: () => p$, _xid: () => tX, _void: () => y7, _uuidv7: () => cX, _uuidv6: () => lX, _uuidv4: () => mX, _uuid: () => uX, _url: () => pX, _uppercase: () => H9, _unknown: () => k1, _union: () => jb, _undefined: () => k7, _ulid: () => oX, _uint64: () => v7, _uint32: () => P7, _tuple: () => y3, _trim: () => B9, _transform: () => Eb, _toUpperCase: () => L9, _toLowerCase: () => q9, _templateLiteral: () => fb, _symbol: () => C7, _success: () => _b, _stringbool: () => l7, _stringFormat: () => c7, _string: () => j7, _startsWith: () => V9, _size: () => z9, _set: () => bb, _safeParseAsync: () => wY, _safeParse: () => OY, _regex: () => G9, _refine: () => m7, _record: () => Ab, _readonly: () => yb, _property: () => T3, _promise: () => hb, _positive: () => C3, _pipe: () => Tb, _parseAsync: () => NY, _parse: () => VY, _overwrite: () => M4, _optional: () => Sb, _number: () => M7, _nullable: () => vb, _null: () => _7, _normalize: () => w9, _nonpositive: () => _3, _nonoptional: () => kb, _nonnegative: () => x3, _never: () => T7, _negative: () => k3, _nativeEnum: () => Pb, _nanoid: () => iX, _nan: () => g7, _multipleOf: () => _1, _minSize: () => x1, _minLength: () => n4, _min: () => U6, _mime: () => O9, _maxSize: () => T0, _maxLength: () => y0, _max: () => b6, _map: () => Ib, _lte: () => b6, _lt: () => j4, _lowercase: () => U9, _literal: () => Rb, _length: () => f0, _lazy: () => gb, _ksuid: () => aX, _jwt: () => W9, _isoTime: () => Z3, _isoDuration: () => P3, _isoDateTime: () => I3, _isoDate: () => b3, _ipv6: () => eX, _ipv4: () => sX, _intersection: () => Mb, _int64: () => S7, _int32: () => Z7, _int: () => A7, _includes: () => K9, _guid: () => x0, _gte: () => U6, _gt: () => F4, _float64: () => b7, _float32: () => I7, _file: () => h7, _enum: () => Zb, _endsWith: () => N9, _emoji: () => dX, _email: () => hX, _e164: () => Q9, _discriminatedUnion: () => Fb, _default: () => Cb, _date: () => f7, _custom: () => u7, _cuid2: () => rX, _cuid: () => nX, _coercedString: () => A3, _coercedNumber: () => R3, _coercedDate: () => v3, _coercedBoolean: () => E3, _coercedBigint: () => S3, _cidrv6: () => X9, _cidrv4: () => $9, _catch: () => xb, _boolean: () => R7, _bigint: () => E7, _base64url: () => Y9, _base64: () => J9, _array: () => D9, _any: () => x7, TimePrecision: () => F7, NEVER: () => zY, JSONSchemaGenerator: () => d7, JSONSchema: () => qN, Doc: () => DY, $output: () => L7, $input: () => D7, $constructor: () => q, $brand: () => GY, $ZodXID: () => vY, $ZodVoid: () => rY, $ZodUnknown: () => C1, $ZodUnion: () => TX, $ZodUndefined: () => pY, $ZodUUID: () => AY, $ZodURL: () => bY, $ZodULID: () => SY, $ZodType: () => d, $ZodTuple: () => i4, $ZodTransform: () => C0, $ZodTemplateLiteral: () => O7, $ZodSymbol: () => cY, $ZodSuccess: () => H7, $ZodStringFormat: () => H$, $ZodString: () => d4, $ZodSet: () => $7, $ZodRegistry: () => fX, $ZodRecord: () => sY, $ZodRealError: () => Z0, $ZodReadonly: () => N7, $ZodPromise: () => w7, $ZodPrefault: () => G7, $ZodPipe: () => k0, $ZodOptional: () => Q7, $ZodObject: () => xX, $ZodNumberFormat: () => mY, $ZodNumber: () => kX, $ZodNullable: () => W7, $ZodNull: () => dY, $ZodNonOptional: () => U7, $ZodNever: () => nY, $ZodNanoID: () => PY, $ZodNaN: () => V7, $ZodMap: () => eY, $ZodLiteral: () => J7, $ZodLazy: () => B7, $ZodKSUID: () => CY, $ZodJWT: () => hY, $ZodIntersection: () => aY, $ZodISOTime: () => Tz, $ZodISODuration: () => yz, $ZodISODateTime: () => _z, $ZodISODate: () => xz, $ZodIPv6: () => _Y, $ZodIPv4: () => kY, $ZodGUID: () => MY, $ZodFunction: () => f3, $ZodFile: () => Y7, $ZodError: () => CX, $ZodEnum: () => X7, $ZodEmoji: () => ZY, $ZodEmail: () => IY, $ZodE164: () => gY, $ZodDiscriminatedUnion: () => tY, $ZodDefault: () => z7, $ZodDate: () => oY, $ZodCustomStringFormat: () => uY, $ZodCustom: () => q7, $ZodCheckUpperCase: () => bz, $ZodCheckStringFormat: () => E0, $ZodCheckStartsWith: () => Pz, $ZodCheckSizeEquals: () => Dz, $ZodCheckRegex: () => Az, $ZodCheckProperty: () => Ez, $ZodCheckOverwrite: () => vz, $ZodCheckNumberFormat: () => wz, $ZodCheckMultipleOf: () => Oz, $ZodCheckMinSize: () => Lz, $ZodCheckMinLength: () => Fz, $ZodCheckMimeType: () => Sz, $ZodCheckMaxSize: () => qz, $ZodCheckMaxLength: () => jz, $ZodCheckLowerCase: () => Iz, $ZodCheckLessThan: () => qY, $ZodCheckLengthEquals: () => Mz, $ZodCheckIncludes: () => Zz, $ZodCheckGreaterThan: () => LY, $ZodCheckEndsWith: () => Rz, $ZodCheckBigIntFormat: () => Bz, $ZodCheck: () => A$, $ZodCatch: () => K7, $ZodCUID2: () => EY, $ZodCUID: () => RY, $ZodCIDRv6: () => TY, $ZodCIDRv4: () => xY, $ZodBoolean: () => S0, $ZodBigIntFormat: () => lY, $ZodBigInt: () => _X, $ZodBase64URL: () => fY, $ZodBase64: () => yY, $ZodAsyncError: () => L4, $ZodArray: () => v0, $ZodAny: () => iY });
var zY = Object.freeze({ status: "aborted" });
function q($, X, J) {
  var _a3;
  function Q(G, U) {
    var _a4, _b2;
    var H;
    Object.defineProperty(G, "_zod", { value: (_a4 = G._zod) != null ? _a4 : {}, enumerable: false }), (_b2 = (H = G._zod).traits) != null ? _b2 : H.traits = /* @__PURE__ */ new Set(), G._zod.traits.add($), X(G, U);
    for (let K in z8.prototype) if (!(K in G)) Object.defineProperty(G, K, { value: z8.prototype[K].bind(G) });
    G._zod.constr = z8, G._zod.def = U;
  }
  let Y = (_a3 = J == null ? void 0 : J.Parent) != null ? _a3 : Object;
  class W extends Y {
  }
  Object.defineProperty(W, "name", { value: $ });
  function z8(G) {
    var _a4;
    var U;
    let H = (J == null ? void 0 : J.Parent) ? new W() : this;
    Q(H, G), (_a4 = (U = H._zod).deferred) != null ? _a4 : U.deferred = [];
    for (let K of H._zod.deferred) K();
    return H;
  }
  return Object.defineProperty(z8, "init", { value: Q }), Object.defineProperty(z8, Symbol.hasInstance, { value: (G) => {
    var _a4, _b2;
    if ((J == null ? void 0 : J.Parent) && G instanceof J.Parent) return true;
    return (_b2 = (_a4 = G == null ? void 0 : G._zod) == null ? void 0 : _a4.traits) == null ? void 0 : _b2.has($);
  } }), Object.defineProperty(z8, "name", { value: $ }), z8;
}
var GY = /* @__PURE__ */ Symbol("zod_brand");
var L4 = class extends Error {
  constructor() {
    super("Encountered Promise during synchronous parse. Use .parseAsync() instead.");
  }
};
var IX = {};
function E$($) {
  if ($) Object.assign(IX, $);
  return IX;
}
var R = {};
H1(R, { unwrapMessage: () => bX, stringifyPrimitive: () => S, required: () => DI, randomString: () => HI, propertyKeyTypes: () => EX, promiseAllObject: () => UI, primitiveTypes: () => _W, prefixIssues: () => z6, pick: () => OI, partial: () => LI, optionalKeys: () => xW, omit: () => wI, numKeys: () => KI, nullish: () => m4, normalizeParams: () => P, merge: () => qI, jsonStringifyReplacer: () => SW, joinValues: () => M, issue: () => fW, isPlainObject: () => b0, isObject: () => I0, getSizableOrigin: () => SX, getParsedType: () => VI, getLengthableOrigin: () => vX, getEnumValues: () => ZX, getElementAtPath: () => GI, floatSafeRemainder: () => vW, finalizeIssue: () => D6, extend: () => BI, escapeRegex: () => D4, esc: () => P1, defineLazy: () => G$, createTransparentProxy: () => NI, clone: () => p$, cleanRegex: () => RX, cleanEnum: () => jI, captureStackTrace: () => UY, cached: () => PX, assignProp: () => CW, assertNotEqual: () => YI, assertNever: () => WI, assertIs: () => QI, assertEqual: () => JI, assert: () => zI, allowsEval: () => kW, aborted: () => R1, NUMBER_FORMAT_RANGES: () => TW, Class: () => iV, BIGINT_FORMAT_RANGES: () => yW });
function JI($) {
  return $;
}
function YI($) {
  return $;
}
function QI($) {
}
function WI($) {
  throw Error();
}
function zI($) {
}
function ZX($) {
  let X = Object.values($).filter((Q) => typeof Q === "number");
  return Object.entries($).filter(([Q, Y]) => X.indexOf(+Q) === -1).map(([Q, Y]) => Y);
}
function M($, X = "|") {
  return $.map((J) => S(J)).join(X);
}
function SW($, X) {
  if (typeof X === "bigint") return X.toString();
  return X;
}
function PX($) {
  return { get value() {
    {
      let J = $();
      return Object.defineProperty(this, "value", { value: J }), J;
    }
    throw Error("cached value already set");
  } };
}
function m4($) {
  return $ === null || $ === void 0;
}
function RX($) {
  let X = $.startsWith("^") ? 1 : 0, J = $.endsWith("$") ? $.length - 1 : $.length;
  return $.slice(X, J);
}
function vW($, X) {
  let J = ($.toString().split(".")[1] || "").length, Q = (X.toString().split(".")[1] || "").length, Y = J > Q ? J : Q, W = Number.parseInt($.toFixed(Y).replace(".", "")), z8 = Number.parseInt(X.toFixed(Y).replace(".", ""));
  return W % z8 / 10 ** Y;
}
function G$($, X, J) {
  Object.defineProperty($, X, { get() {
    {
      let Y = J();
      return $[X] = Y, Y;
    }
    throw Error("cached value already set");
  }, set(Y) {
    Object.defineProperty($, X, { value: Y });
  }, configurable: true });
}
function CW($, X, J) {
  Object.defineProperty($, X, { value: J, writable: true, enumerable: true, configurable: true });
}
function GI($, X) {
  if (!X) return $;
  return X.reduce((J, Q) => J == null ? void 0 : J[Q], $);
}
function UI($) {
  let X = Object.keys($), J = X.map((Q) => $[Q]);
  return Promise.all(J).then((Q) => {
    let Y = {};
    for (let W = 0; W < X.length; W++) Y[X[W]] = Q[W];
    return Y;
  });
}
function HI($ = 10) {
  let J = "";
  for (let Q = 0; Q < $; Q++) J += "abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random() * 26)];
  return J;
}
function P1($) {
  return JSON.stringify($);
}
var UY = Error.captureStackTrace ? Error.captureStackTrace : (...$) => {
};
function I0($) {
  return typeof $ === "object" && $ !== null && !Array.isArray($);
}
var kW = PX(() => {
  var _a3;
  if (typeof navigator < "u" && ((_a3 = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a3.includes("Cloudflare"))) return false;
  try {
    return new Function(""), true;
  } catch ($) {
    return false;
  }
});
function b0($) {
  if (I0($) === false) return false;
  let X = $.constructor;
  if (X === void 0) return true;
  let J = X.prototype;
  if (I0(J) === false) return false;
  if (Object.prototype.hasOwnProperty.call(J, "isPrototypeOf") === false) return false;
  return true;
}
function KI($) {
  let X = 0;
  for (let J in $) if (Object.prototype.hasOwnProperty.call($, J)) X++;
  return X;
}
var VI = ($) => {
  let X = typeof $;
  switch (X) {
    case "undefined":
      return "undefined";
    case "string":
      return "string";
    case "number":
      return Number.isNaN($) ? "nan" : "number";
    case "boolean":
      return "boolean";
    case "function":
      return "function";
    case "bigint":
      return "bigint";
    case "symbol":
      return "symbol";
    case "object":
      if (Array.isArray($)) return "array";
      if ($ === null) return "null";
      if ($.then && typeof $.then === "function" && $.catch && typeof $.catch === "function") return "promise";
      if (typeof Map < "u" && $ instanceof Map) return "map";
      if (typeof Set < "u" && $ instanceof Set) return "set";
      if (typeof Date < "u" && $ instanceof Date) return "date";
      if (typeof File < "u" && $ instanceof File) return "file";
      return "object";
    default:
      throw Error(`Unknown data type: ${X}`);
  }
};
var EX = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
var _W = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
function D4($) {
  return $.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function p$($, X, J) {
  let Q = new $._zod.constr(X != null ? X : $._zod.def);
  if (!X || (J == null ? void 0 : J.parent)) Q._zod.parent = $;
  return Q;
}
function P($) {
  let X = $;
  if (!X) return {};
  if (typeof X === "string") return { error: () => X };
  if ((X == null ? void 0 : X.message) !== void 0) {
    if ((X == null ? void 0 : X.error) !== void 0) throw Error("Cannot specify both `message` and `error` params");
    X.error = X.message;
  }
  if (delete X.message, typeof X.error === "string") return { ...X, error: () => X.error };
  return X;
}
function NI($) {
  let X;
  return new Proxy({}, { get(J, Q, Y) {
    return X != null ? X : X = $(), Reflect.get(X, Q, Y);
  }, set(J, Q, Y, W) {
    return X != null ? X : X = $(), Reflect.set(X, Q, Y, W);
  }, has(J, Q) {
    return X != null ? X : X = $(), Reflect.has(X, Q);
  }, deleteProperty(J, Q) {
    return X != null ? X : X = $(), Reflect.deleteProperty(X, Q);
  }, ownKeys(J) {
    return X != null ? X : X = $(), Reflect.ownKeys(X);
  }, getOwnPropertyDescriptor(J, Q) {
    return X != null ? X : X = $(), Reflect.getOwnPropertyDescriptor(X, Q);
  }, defineProperty(J, Q, Y) {
    return X != null ? X : X = $(), Reflect.defineProperty(X, Q, Y);
  } });
}
function S($) {
  if (typeof $ === "bigint") return $.toString() + "n";
  if (typeof $ === "string") return `"${$}"`;
  return `${$}`;
}
function xW($) {
  return Object.keys($).filter((X) => {
    return $[X]._zod.optin === "optional" && $[X]._zod.optout === "optional";
  });
}
var TW = { 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] };
var yW = { int64: [BigInt("-9223372036854775808"), BigInt("9223372036854775807")], uint64: [BigInt(0), BigInt("18446744073709551615")] };
function OI($, X) {
  let J = {}, Q = $._zod.def;
  for (let Y in X) {
    if (!(Y in Q.shape)) throw Error(`Unrecognized key: "${Y}"`);
    if (!X[Y]) continue;
    J[Y] = Q.shape[Y];
  }
  return p$($, { ...$._zod.def, shape: J, checks: [] });
}
function wI($, X) {
  let J = { ...$._zod.def.shape }, Q = $._zod.def;
  for (let Y in X) {
    if (!(Y in Q.shape)) throw Error(`Unrecognized key: "${Y}"`);
    if (!X[Y]) continue;
    delete J[Y];
  }
  return p$($, { ...$._zod.def, shape: J, checks: [] });
}
function BI($, X) {
  if (!b0(X)) throw Error("Invalid input to extend: expected a plain object");
  let J = { ...$._zod.def, get shape() {
    let Q = { ...$._zod.def.shape, ...X };
    return CW(this, "shape", Q), Q;
  }, checks: [] };
  return p$($, J);
}
function qI($, X) {
  return p$($, { ...$._zod.def, get shape() {
    let J = { ...$._zod.def.shape, ...X._zod.def.shape };
    return CW(this, "shape", J), J;
  }, catchall: X._zod.def.catchall, checks: [] });
}
function LI($, X, J) {
  let Q = X._zod.def.shape, Y = { ...Q };
  if (J) for (let W in J) {
    if (!(W in Q)) throw Error(`Unrecognized key: "${W}"`);
    if (!J[W]) continue;
    Y[W] = $ ? new $({ type: "optional", innerType: Q[W] }) : Q[W];
  }
  else for (let W in Q) Y[W] = $ ? new $({ type: "optional", innerType: Q[W] }) : Q[W];
  return p$(X, { ...X._zod.def, shape: Y, checks: [] });
}
function DI($, X, J) {
  let Q = X._zod.def.shape, Y = { ...Q };
  if (J) for (let W in J) {
    if (!(W in Y)) throw Error(`Unrecognized key: "${W}"`);
    if (!J[W]) continue;
    Y[W] = new $({ type: "nonoptional", innerType: Q[W] });
  }
  else for (let W in Q) Y[W] = new $({ type: "nonoptional", innerType: Q[W] });
  return p$(X, { ...X._zod.def, shape: Y, checks: [] });
}
function R1($, X = 0) {
  var _a3;
  for (let J = X; J < $.issues.length; J++) if (((_a3 = $.issues[J]) == null ? void 0 : _a3.continue) !== true) return true;
  return false;
}
function z6($, X) {
  return X.map((J) => {
    var _a3;
    var Q;
    return (_a3 = (Q = J).path) != null ? _a3 : Q.path = [], J.path.unshift($), J;
  });
}
function bX($) {
  return typeof $ === "string" ? $ : $ == null ? void 0 : $.message;
}
function D6($, X, J) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k;
  let Q = { ...$, path: (_a3 = $.path) != null ? _a3 : [] };
  if (!$.message) {
    let Y = (_k = (_j2 = (_h = (_f = bX((_d2 = (_c = (_b2 = $.inst) == null ? void 0 : _b2._zod.def) == null ? void 0 : _c.error) == null ? void 0 : _d2.call(_c, $))) != null ? _f : bX((_e = X == null ? void 0 : X.error) == null ? void 0 : _e.call(X, $))) != null ? _h : bX((_g = J.customError) == null ? void 0 : _g.call(J, $))) != null ? _j2 : bX((_i = J.localeError) == null ? void 0 : _i.call(J, $))) != null ? _k : "Invalid input";
    Q.message = Y;
  }
  if (delete Q.inst, delete Q.continue, !(X == null ? void 0 : X.reportInput)) delete Q.input;
  return Q;
}
function SX($) {
  if ($ instanceof Set) return "set";
  if ($ instanceof Map) return "map";
  if ($ instanceof File) return "file";
  return "unknown";
}
function vX($) {
  if (Array.isArray($)) return "array";
  if (typeof $ === "string") return "string";
  return "unknown";
}
function fW(...$) {
  let [X, J, Q] = $;
  if (typeof X === "string") return { message: X, code: "custom", input: J, inst: Q };
  return { ...X };
}
function jI($) {
  return Object.entries($).filter(([X, J]) => {
    return Number.isNaN(Number.parseInt(X, 10));
  }).map((X) => X[1]);
}
var iV = class {
  constructor(...$) {
  }
};
var nV = ($, X) => {
  $.name = "$ZodError", Object.defineProperty($, "_zod", { value: $._zod, enumerable: false }), Object.defineProperty($, "issues", { value: X, enumerable: false }), Object.defineProperty($, "message", { get() {
    return JSON.stringify(X, SW, 2);
  }, enumerable: true });
};
var CX = q("$ZodError", nV);
var Z0 = q("$ZodError", nV, { Parent: Error });
function P0($, X = (J) => J.message) {
  let J = {}, Q = [];
  for (let Y of $.issues) if (Y.path.length > 0) J[Y.path[0]] = J[Y.path[0]] || [], J[Y.path[0]].push(X(Y));
  else Q.push(X(Y));
  return { formErrors: Q, fieldErrors: J };
}
function R0($, X) {
  let J = X || function(W) {
    return W.message;
  }, Q = { _errors: [] }, Y = (W) => {
    for (let z8 of W.issues) if (z8.code === "invalid_union" && z8.errors.length) z8.errors.map((G) => Y({ issues: G }));
    else if (z8.code === "invalid_key") Y({ issues: z8.issues });
    else if (z8.code === "invalid_element") Y({ issues: z8.issues });
    else if (z8.path.length === 0) Q._errors.push(J(z8));
    else {
      let G = Q, U = 0;
      while (U < z8.path.length) {
        let H = z8.path[U];
        if (U !== z8.path.length - 1) G[H] = G[H] || { _errors: [] };
        else G[H] = G[H] || { _errors: [] }, G[H]._errors.push(J(z8));
        G = G[H], U++;
      }
    }
  };
  return Y($), Q;
}
function HY($, X) {
  let J = X || function(W) {
    return W.message;
  }, Q = { errors: [] }, Y = (W, z8 = []) => {
    var _a3, _b2, _c, _d2;
    var G, U;
    for (let H of W.issues) if (H.code === "invalid_union" && H.errors.length) H.errors.map((K) => Y({ issues: K }, H.path));
    else if (H.code === "invalid_key") Y({ issues: H.issues }, H.path);
    else if (H.code === "invalid_element") Y({ issues: H.issues }, H.path);
    else {
      let K = [...z8, ...H.path];
      if (K.length === 0) {
        Q.errors.push(J(H));
        continue;
      }
      let V = Q, N = 0;
      while (N < K.length) {
        let O = K[N], w = N === K.length - 1;
        if (typeof O === "string") (_a3 = V.properties) != null ? _a3 : V.properties = {}, (_b2 = (G = V.properties)[O]) != null ? _b2 : G[O] = { errors: [] }, V = V.properties[O];
        else (_c = V.items) != null ? _c : V.items = [], (_d2 = (U = V.items)[O]) != null ? _d2 : U[O] = { errors: [] }, V = V.items[O];
        if (w) V.errors.push(J(H));
        N++;
      }
    }
  };
  return Y($), Q;
}
function rV($) {
  let X = [];
  for (let J of $) if (typeof J === "number") X.push(`[${J}]`);
  else if (typeof J === "symbol") X.push(`[${JSON.stringify(String(J))}]`);
  else if (/[^\w$]/.test(J)) X.push(`[${JSON.stringify(J)}]`);
  else {
    if (X.length) X.push(".");
    X.push(J);
  }
  return X.join("");
}
function KY($) {
  var _a3;
  let X = [], J = [...$.issues].sort((Q, Y) => Q.path.length - Y.path.length);
  for (let Q of J) if (X.push(`\u2716 ${Q.message}`), (_a3 = Q.path) == null ? void 0 : _a3.length) X.push(`  \u2192 at ${rV(Q.path)}`);
  return X.join(`
`);
}
var VY = ($) => (X, J, Q, Y) => {
  var _a3;
  let W = Q ? Object.assign(Q, { async: false }) : { async: false }, z8 = X._zod.run({ value: J, issues: [] }, W);
  if (z8 instanceof Promise) throw new L4();
  if (z8.issues.length) {
    let G = new ((_a3 = Y == null ? void 0 : Y.Err) != null ? _a3 : $)(z8.issues.map((U) => D6(U, W, E$())));
    throw UY(G, Y == null ? void 0 : Y.callee), G;
  }
  return z8.value;
};
var E1 = VY(Z0);
var NY = ($) => async (X, J, Q, Y) => {
  var _a3;
  let W = Q ? Object.assign(Q, { async: true }) : { async: true }, z8 = X._zod.run({ value: J, issues: [] }, W);
  if (z8 instanceof Promise) z8 = await z8;
  if (z8.issues.length) {
    let G = new ((_a3 = Y == null ? void 0 : Y.Err) != null ? _a3 : $)(z8.issues.map((U) => D6(U, W, E$())));
    throw UY(G, Y == null ? void 0 : Y.callee), G;
  }
  return z8.value;
};
var S1 = NY(Z0);
var OY = ($) => (X, J, Q) => {
  let Y = Q ? { ...Q, async: false } : { async: false }, W = X._zod.run({ value: J, issues: [] }, Y);
  if (W instanceof Promise) throw new L4();
  return W.issues.length ? { success: false, error: new ($ != null ? $ : CX)(W.issues.map((z8) => D6(z8, Y, E$()))) } : { success: true, data: W.value };
};
var l4 = OY(Z0);
var wY = ($) => async (X, J, Q) => {
  let Y = Q ? Object.assign(Q, { async: true }) : { async: true }, W = X._zod.run({ value: J, issues: [] }, Y);
  if (W instanceof Promise) W = await W;
  return W.issues.length ? { success: false, error: new $(W.issues.map((z8) => D6(z8, Y, E$()))) } : { success: true, data: W.value };
};
var c4 = wY(Z0);
var p4 = {};
H1(p4, { xid: () => mW, uuid7: () => bI, uuid6: () => II, uuid4: () => AI, uuid: () => v1, uppercase: () => Nz, unicodeEmail: () => RI, undefined: () => Kz, ulid: () => uW, time: () => Jz, string: () => Qz, rfc5322Email: () => PI, number: () => Gz, null: () => Hz, nanoid: () => cW, lowercase: () => Vz, ksuid: () => lW, ipv6: () => oW, ipv4: () => rW, integer: () => zz, html5Email: () => ZI, hostname: () => eW, guid: () => dW, extendedDuration: () => MI, emoji: () => nW, email: () => iW, e164: () => $z, duration: () => pW, domain: () => vI, datetime: () => Yz, date: () => Xz, cuid2: () => hW, cuid: () => gW, cidrv6: () => aW, cidrv4: () => tW, browserEmail: () => EI, boolean: () => Uz, bigint: () => Wz, base64url: () => BY, base64: () => sW, _emoji: () => SI });
var gW = /^[cC][^\s-]{8,}$/;
var hW = /^[0-9a-z]+$/;
var uW = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
var mW = /^[0-9a-vA-V]{20}$/;
var lW = /^[A-Za-z0-9]{27}$/;
var cW = /^[a-zA-Z0-9_-]{21}$/;
var pW = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
var MI = /^[-+]?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)?)??$/;
var dW = /^([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})$/;
var v1 = ($) => {
  if (!$) return /^([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)$/;
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${$}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
var AI = v1(4);
var II = v1(6);
var bI = v1(7);
var iW = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
var ZI = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var PI = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var RI = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
var EI = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var SI = "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";
function nW() {
  return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u");
}
var rW = /^(?:(?: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])$/;
var oW = /^(([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})$/;
var tW = /^((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])$/;
var aW = /^(([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])$/;
var sW = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
var BY = /^[A-Za-z0-9_-]*$/;
var eW = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/;
var vI = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
var $z = /^\+(?:[0-9]){6,14}[0-9]$/;
var oV = "(?:(?:\\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])))";
var Xz = new RegExp(`^${oV}$`);
function tV($) {
  return typeof $.precision === "number" ? $.precision === -1 ? "(?:[01]\\d|2[0-3]):[0-5]\\d" : $.precision === 0 ? "(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d" : `(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${$.precision}}` : "(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?";
}
function Jz($) {
  return new RegExp(`^${tV($)}$`);
}
function Yz($) {
  let X = tV({ precision: $.precision }), J = ["Z"];
  if ($.local) J.push("");
  if ($.offset) J.push("([+-]\\d{2}:\\d{2})");
  let Q = `${X}(?:${J.join("|")})`;
  return new RegExp(`^${oV}T(?:${Q})$`);
}
var Qz = ($) => {
  var _a3, _b2;
  let X = $ ? `[\\s\\S]{${(_a3 = $ == null ? void 0 : $.minimum) != null ? _a3 : 0},${(_b2 = $ == null ? void 0 : $.maximum) != null ? _b2 : ""}}` : "[\\s\\S]*";
  return new RegExp(`^${X}$`);
};
var Wz = /^\d+n?$/;
var zz = /^\d+$/;
var Gz = /^-?\d+(?:\.\d+)?/i;
var Uz = /true|false/i;
var Hz = /null/i;
var Kz = /undefined/i;
var Vz = /^[^A-Z]*$/;
var Nz = /^[^a-z]*$/;
var A$ = q("$ZodCheck", ($, X) => {
  var _a3, _b2;
  var J;
  (_a3 = $._zod) != null ? _a3 : $._zod = {}, $._zod.def = X, (_b2 = (J = $._zod).onattach) != null ? _b2 : J.onattach = [];
});
var sV = { number: "number", bigint: "bigint", object: "date" };
var qY = q("$ZodCheckLessThan", ($, X) => {
  A$.init($, X);
  let J = sV[typeof X.value];
  $._zod.onattach.push((Q) => {
    var _a3;
    let Y = Q._zod.bag, W = (_a3 = X.inclusive ? Y.maximum : Y.exclusiveMaximum) != null ? _a3 : Number.POSITIVE_INFINITY;
    if (X.value < W) if (X.inclusive) Y.maximum = X.value;
    else Y.exclusiveMaximum = X.value;
  }), $._zod.check = (Q) => {
    if (X.inclusive ? Q.value <= X.value : Q.value < X.value) return;
    Q.issues.push({ origin: J, code: "too_big", maximum: X.value, input: Q.value, inclusive: X.inclusive, inst: $, continue: !X.abort });
  };
});
var LY = q("$ZodCheckGreaterThan", ($, X) => {
  A$.init($, X);
  let J = sV[typeof X.value];
  $._zod.onattach.push((Q) => {
    var _a3;
    let Y = Q._zod.bag, W = (_a3 = X.inclusive ? Y.minimum : Y.exclusiveMinimum) != null ? _a3 : Number.NEGATIVE_INFINITY;
    if (X.value > W) if (X.inclusive) Y.minimum = X.value;
    else Y.exclusiveMinimum = X.value;
  }), $._zod.check = (Q) => {
    if (X.inclusive ? Q.value >= X.value : Q.value > X.value) return;
    Q.issues.push({ origin: J, code: "too_small", minimum: X.value, input: Q.value, inclusive: X.inclusive, inst: $, continue: !X.abort });
  };
});
var Oz = q("$ZodCheckMultipleOf", ($, X) => {
  A$.init($, X), $._zod.onattach.push((J) => {
    var _a3;
    var Q;
    (_a3 = (Q = J._zod.bag).multipleOf) != null ? _a3 : Q.multipleOf = X.value;
  }), $._zod.check = (J) => {
    if (typeof J.value !== typeof X.value) throw Error("Cannot mix number and bigint in multiple_of check.");
    if (typeof J.value === "bigint" ? J.value % X.value === BigInt(0) : vW(J.value, X.value) === 0) return;
    J.issues.push({ origin: typeof J.value, code: "not_multiple_of", divisor: X.value, input: J.value, inst: $, continue: !X.abort });
  };
});
var wz = q("$ZodCheckNumberFormat", ($, X) => {
  var _a3;
  A$.init($, X), X.format = X.format || "float64";
  let J = (_a3 = X.format) == null ? void 0 : _a3.includes("int"), Q = J ? "int" : "number", [Y, W] = TW[X.format];
  $._zod.onattach.push((z8) => {
    let G = z8._zod.bag;
    if (G.format = X.format, G.minimum = Y, G.maximum = W, J) G.pattern = zz;
  }), $._zod.check = (z8) => {
    let G = z8.value;
    if (J) {
      if (!Number.isInteger(G)) {
        z8.issues.push({ expected: Q, format: X.format, code: "invalid_type", input: G, inst: $ });
        return;
      }
      if (!Number.isSafeInteger(G)) {
        if (G > 0) z8.issues.push({ input: G, code: "too_big", maximum: Number.MAX_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst: $, origin: Q, continue: !X.abort });
        else z8.issues.push({ input: G, code: "too_small", minimum: Number.MIN_SAFE_INTEGER, note: "Integers must be within the safe integer range.", inst: $, origin: Q, continue: !X.abort });
        return;
      }
    }
    if (G < Y) z8.issues.push({ origin: "number", input: G, code: "too_small", minimum: Y, inclusive: true, inst: $, continue: !X.abort });
    if (G > W) z8.issues.push({ origin: "number", input: G, code: "too_big", maximum: W, inst: $ });
  };
});
var Bz = q("$ZodCheckBigIntFormat", ($, X) => {
  A$.init($, X);
  let [J, Q] = yW[X.format];
  $._zod.onattach.push((Y) => {
    let W = Y._zod.bag;
    W.format = X.format, W.minimum = J, W.maximum = Q;
  }), $._zod.check = (Y) => {
    let W = Y.value;
    if (W < J) Y.issues.push({ origin: "bigint", input: W, code: "too_small", minimum: J, inclusive: true, inst: $, continue: !X.abort });
    if (W > Q) Y.issues.push({ origin: "bigint", input: W, code: "too_big", maximum: Q, inst: $ });
  };
});
var qz = q("$ZodCheckMaxSize", ($, X) => {
  A$.init($, X), $._zod.when = (J) => {
    let Q = J.value;
    return !m4(Q) && Q.size !== void 0;
  }, $._zod.onattach.push((J) => {
    var _a3;
    let Q = (_a3 = J._zod.bag.maximum) != null ? _a3 : Number.POSITIVE_INFINITY;
    if (X.maximum < Q) J._zod.bag.maximum = X.maximum;
  }), $._zod.check = (J) => {
    let Q = J.value;
    if (Q.size <= X.maximum) return;
    J.issues.push({ origin: SX(Q), code: "too_big", maximum: X.maximum, input: Q, inst: $, continue: !X.abort });
  };
});
var Lz = q("$ZodCheckMinSize", ($, X) => {
  A$.init($, X), $._zod.when = (J) => {
    let Q = J.value;
    return !m4(Q) && Q.size !== void 0;
  }, $._zod.onattach.push((J) => {
    var _a3;
    let Q = (_a3 = J._zod.bag.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY;
    if (X.minimum > Q) J._zod.bag.minimum = X.minimum;
  }), $._zod.check = (J) => {
    let Q = J.value;
    if (Q.size >= X.minimum) return;
    J.issues.push({ origin: SX(Q), code: "too_small", minimum: X.minimum, input: Q, inst: $, continue: !X.abort });
  };
});
var Dz = q("$ZodCheckSizeEquals", ($, X) => {
  A$.init($, X), $._zod.when = (J) => {
    let Q = J.value;
    return !m4(Q) && Q.size !== void 0;
  }, $._zod.onattach.push((J) => {
    let Q = J._zod.bag;
    Q.minimum = X.size, Q.maximum = X.size, Q.size = X.size;
  }), $._zod.check = (J) => {
    let Q = J.value, Y = Q.size;
    if (Y === X.size) return;
    let W = Y > X.size;
    J.issues.push({ origin: SX(Q), ...W ? { code: "too_big", maximum: X.size } : { code: "too_small", minimum: X.size }, inclusive: true, exact: true, input: J.value, inst: $, continue: !X.abort });
  };
});
var jz = q("$ZodCheckMaxLength", ($, X) => {
  A$.init($, X), $._zod.when = (J) => {
    let Q = J.value;
    return !m4(Q) && Q.length !== void 0;
  }, $._zod.onattach.push((J) => {
    var _a3;
    let Q = (_a3 = J._zod.bag.maximum) != null ? _a3 : Number.POSITIVE_INFINITY;
    if (X.maximum < Q) J._zod.bag.maximum = X.maximum;
  }), $._zod.check = (J) => {
    let Q = J.value;
    if (Q.length <= X.maximum) return;
    let W = vX(Q);
    J.issues.push({ origin: W, code: "too_big", maximum: X.maximum, inclusive: true, input: Q, inst: $, continue: !X.abort });
  };
});
var Fz = q("$ZodCheckMinLength", ($, X) => {
  A$.init($, X), $._zod.when = (J) => {
    let Q = J.value;
    return !m4(Q) && Q.length !== void 0;
  }, $._zod.onattach.push((J) => {
    var _a3;
    let Q = (_a3 = J._zod.bag.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY;
    if (X.minimum > Q) J._zod.bag.minimum = X.minimum;
  }), $._zod.check = (J) => {
    let Q = J.value;
    if (Q.length >= X.minimum) return;
    let W = vX(Q);
    J.issues.push({ origin: W, code: "too_small", minimum: X.minimum, inclusive: true, input: Q, inst: $, continue: !X.abort });
  };
});
var Mz = q("$ZodCheckLengthEquals", ($, X) => {
  A$.init($, X), $._zod.when = (J) => {
    let Q = J.value;
    return !m4(Q) && Q.length !== void 0;
  }, $._zod.onattach.push((J) => {
    let Q = J._zod.bag;
    Q.minimum = X.length, Q.maximum = X.length, Q.length = X.length;
  }), $._zod.check = (J) => {
    let Q = J.value, Y = Q.length;
    if (Y === X.length) return;
    let W = vX(Q), z8 = Y > X.length;
    J.issues.push({ origin: W, ...z8 ? { code: "too_big", maximum: X.length } : { code: "too_small", minimum: X.length }, inclusive: true, exact: true, input: J.value, inst: $, continue: !X.abort });
  };
});
var E0 = q("$ZodCheckStringFormat", ($, X) => {
  var _a3, _b2;
  var J, Q;
  if (A$.init($, X), $._zod.onattach.push((Y) => {
    var _a4;
    let W = Y._zod.bag;
    if (W.format = X.format, X.pattern) (_a4 = W.patterns) != null ? _a4 : W.patterns = /* @__PURE__ */ new Set(), W.patterns.add(X.pattern);
  }), X.pattern) (_a3 = (J = $._zod).check) != null ? _a3 : J.check = (Y) => {
    if (X.pattern.lastIndex = 0, X.pattern.test(Y.value)) return;
    Y.issues.push({ origin: "string", code: "invalid_format", format: X.format, input: Y.value, ...X.pattern ? { pattern: X.pattern.toString() } : {}, inst: $, continue: !X.abort });
  };
  else (_b2 = (Q = $._zod).check) != null ? _b2 : Q.check = () => {
  };
});
var Az = q("$ZodCheckRegex", ($, X) => {
  E0.init($, X), $._zod.check = (J) => {
    if (X.pattern.lastIndex = 0, X.pattern.test(J.value)) return;
    J.issues.push({ origin: "string", code: "invalid_format", format: "regex", input: J.value, pattern: X.pattern.toString(), inst: $, continue: !X.abort });
  };
});
var Iz = q("$ZodCheckLowerCase", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = Vz, E0.init($, X);
});
var bz = q("$ZodCheckUpperCase", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = Nz, E0.init($, X);
});
var Zz = q("$ZodCheckIncludes", ($, X) => {
  A$.init($, X);
  let J = D4(X.includes), Q = new RegExp(typeof X.position === "number" ? `^.{${X.position}}${J}` : J);
  X.pattern = Q, $._zod.onattach.push((Y) => {
    var _a3;
    let W = Y._zod.bag;
    (_a3 = W.patterns) != null ? _a3 : W.patterns = /* @__PURE__ */ new Set(), W.patterns.add(Q);
  }), $._zod.check = (Y) => {
    if (Y.value.includes(X.includes, X.position)) return;
    Y.issues.push({ origin: "string", code: "invalid_format", format: "includes", includes: X.includes, input: Y.value, inst: $, continue: !X.abort });
  };
});
var Pz = q("$ZodCheckStartsWith", ($, X) => {
  var _a3;
  A$.init($, X);
  let J = new RegExp(`^${D4(X.prefix)}.*`);
  (_a3 = X.pattern) != null ? _a3 : X.pattern = J, $._zod.onattach.push((Q) => {
    var _a4;
    let Y = Q._zod.bag;
    (_a4 = Y.patterns) != null ? _a4 : Y.patterns = /* @__PURE__ */ new Set(), Y.patterns.add(J);
  }), $._zod.check = (Q) => {
    if (Q.value.startsWith(X.prefix)) return;
    Q.issues.push({ origin: "string", code: "invalid_format", format: "starts_with", prefix: X.prefix, input: Q.value, inst: $, continue: !X.abort });
  };
});
var Rz = q("$ZodCheckEndsWith", ($, X) => {
  var _a3;
  A$.init($, X);
  let J = new RegExp(`.*${D4(X.suffix)}$`);
  (_a3 = X.pattern) != null ? _a3 : X.pattern = J, $._zod.onattach.push((Q) => {
    var _a4;
    let Y = Q._zod.bag;
    (_a4 = Y.patterns) != null ? _a4 : Y.patterns = /* @__PURE__ */ new Set(), Y.patterns.add(J);
  }), $._zod.check = (Q) => {
    if (Q.value.endsWith(X.suffix)) return;
    Q.issues.push({ origin: "string", code: "invalid_format", format: "ends_with", suffix: X.suffix, input: Q.value, inst: $, continue: !X.abort });
  };
});
function aV($, X, J) {
  if ($.issues.length) X.issues.push(...z6(J, $.issues));
}
var Ez = q("$ZodCheckProperty", ($, X) => {
  A$.init($, X), $._zod.check = (J) => {
    let Q = X.schema._zod.run({ value: J.value[X.property], issues: [] }, {});
    if (Q instanceof Promise) return Q.then((Y) => aV(Y, J, X.property));
    aV(Q, J, X.property);
    return;
  };
});
var Sz = q("$ZodCheckMimeType", ($, X) => {
  A$.init($, X);
  let J = new Set(X.mime);
  $._zod.onattach.push((Q) => {
    Q._zod.bag.mime = X.mime;
  }), $._zod.check = (Q) => {
    if (J.has(Q.value.type)) return;
    Q.issues.push({ code: "invalid_value", values: X.mime, input: Q.value.type, inst: $ });
  };
});
var vz = q("$ZodCheckOverwrite", ($, X) => {
  A$.init($, X), $._zod.check = (J) => {
    J.value = X.tx(J.value);
  };
});
var DY = class {
  constructor($ = []) {
    if (this.content = [], this.indent = 0, this) this.args = $;
  }
  indented($) {
    this.indent += 1, $(this), this.indent -= 1;
  }
  write($) {
    if (typeof $ === "function") {
      $(this, { execution: "sync" }), $(this, { execution: "async" });
      return;
    }
    let J = $.split(`
`).filter((W) => W), Q = Math.min(...J.map((W) => W.length - W.trimStart().length)), Y = J.map((W) => W.slice(Q)).map((W) => " ".repeat(this.indent * 2) + W);
    for (let W of Y) this.content.push(W);
  }
  compile() {
    var _a3;
    let $ = Function, X = this == null ? void 0 : this.args, Q = [...((_a3 = this == null ? void 0 : this.content) != null ? _a3 : [""]).map((Y) => `  ${Y}`)];
    return new $(...X, Q.join(`
`));
  }
};
var Cz = { major: 4, minor: 0, patch: 0 };
var d = q("$ZodType", ($, X) => {
  var _a3, _b2, _c;
  var J;
  $ != null ? $ : $ = {}, $._zod.def = X, $._zod.bag = $._zod.bag || {}, $._zod.version = Cz;
  let Q = [...(_a3 = $._zod.def.checks) != null ? _a3 : []];
  if ($._zod.traits.has("$ZodCheck")) Q.unshift($);
  for (let Y of Q) for (let W of Y._zod.onattach) W($);
  if (Q.length === 0) (_b2 = (J = $._zod).deferred) != null ? _b2 : J.deferred = [], (_c = $._zod.deferred) == null ? void 0 : _c.push(() => {
    $._zod.run = $._zod.parse;
  });
  else {
    let Y = (W, z8, G) => {
      let U = R1(W), H;
      for (let K of z8) {
        if (K._zod.when) {
          if (!K._zod.when(W)) continue;
        } else if (U) continue;
        let V = W.issues.length, N = K._zod.check(W);
        if (N instanceof Promise && (G == null ? void 0 : G.async) === false) throw new L4();
        if (H || N instanceof Promise) H = (H != null ? H : Promise.resolve()).then(async () => {
          if (await N, W.issues.length === V) return;
          if (!U) U = R1(W, V);
        });
        else {
          if (W.issues.length === V) continue;
          if (!U) U = R1(W, V);
        }
      }
      if (H) return H.then(() => {
        return W;
      });
      return W;
    };
    $._zod.run = (W, z8) => {
      let G = $._zod.parse(W, z8);
      if (G instanceof Promise) {
        if (z8.async === false) throw new L4();
        return G.then((U) => Y(U, Q, z8));
      }
      return Y(G, Q, z8);
    };
  }
  $["~standard"] = { validate: (Y) => {
    var _a4;
    try {
      let W = l4($, Y);
      return W.success ? { value: W.data } : { issues: (_a4 = W.error) == null ? void 0 : _a4.issues };
    } catch (W) {
      return c4($, Y).then((z8) => {
        var _a5;
        return z8.success ? { value: z8.data } : { issues: (_a5 = z8.error) == null ? void 0 : _a5.issues };
      });
    }
  }, vendor: "zod", version: 1 };
});
var d4 = q("$ZodString", ($, X) => {
  var _a3, _b2, _c;
  d.init($, X), $._zod.pattern = (_c = [...(_b2 = (_a3 = $ == null ? void 0 : $._zod.bag) == null ? void 0 : _a3.patterns) != null ? _b2 : []].pop()) != null ? _c : Qz($._zod.bag), $._zod.parse = (J, Q) => {
    if (X.coerce) try {
      J.value = String(J.value);
    } catch (Y) {
    }
    if (typeof J.value === "string") return J;
    return J.issues.push({ expected: "string", code: "invalid_type", input: J.value, inst: $ }), J;
  };
});
var H$ = q("$ZodStringFormat", ($, X) => {
  E0.init($, X), d4.init($, X);
});
var MY = q("$ZodGUID", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = dW, H$.init($, X);
});
var AY = q("$ZodUUID", ($, X) => {
  var _a3, _b2;
  if (X.version) {
    let Q = { v1: 1, v2: 2, v3: 3, v4: 4, v5: 5, v6: 6, v7: 7, v8: 8 }[X.version];
    if (Q === void 0) throw Error(`Invalid UUID version: "${X.version}"`);
    (_a3 = X.pattern) != null ? _a3 : X.pattern = v1(Q);
  } else (_b2 = X.pattern) != null ? _b2 : X.pattern = v1();
  H$.init($, X);
});
var IY = q("$ZodEmail", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = iW, H$.init($, X);
});
var bY = q("$ZodURL", ($, X) => {
  H$.init($, X), $._zod.check = (J) => {
    try {
      let Q = J.value, Y = new URL(Q), W = Y.href;
      if (X.hostname) {
        if (X.hostname.lastIndex = 0, !X.hostname.test(Y.hostname)) J.issues.push({ code: "invalid_format", format: "url", note: "Invalid hostname", pattern: eW.source, input: J.value, inst: $, continue: !X.abort });
      }
      if (X.protocol) {
        if (X.protocol.lastIndex = 0, !X.protocol.test(Y.protocol.endsWith(":") ? Y.protocol.slice(0, -1) : Y.protocol)) J.issues.push({ code: "invalid_format", format: "url", note: "Invalid protocol", pattern: X.protocol.source, input: J.value, inst: $, continue: !X.abort });
      }
      if (!Q.endsWith("/") && W.endsWith("/")) J.value = W.slice(0, -1);
      else J.value = W;
      return;
    } catch (Q) {
      J.issues.push({ code: "invalid_format", format: "url", input: J.value, inst: $, continue: !X.abort });
    }
  };
});
var ZY = q("$ZodEmoji", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = nW(), H$.init($, X);
});
var PY = q("$ZodNanoID", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = cW, H$.init($, X);
});
var RY = q("$ZodCUID", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = gW, H$.init($, X);
});
var EY = q("$ZodCUID2", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = hW, H$.init($, X);
});
var SY = q("$ZodULID", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = uW, H$.init($, X);
});
var vY = q("$ZodXID", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = mW, H$.init($, X);
});
var CY = q("$ZodKSUID", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = lW, H$.init($, X);
});
var _z = q("$ZodISODateTime", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = Yz(X), H$.init($, X);
});
var xz = q("$ZodISODate", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = Xz, H$.init($, X);
});
var Tz = q("$ZodISOTime", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = Jz(X), H$.init($, X);
});
var yz = q("$ZodISODuration", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = pW, H$.init($, X);
});
var kY = q("$ZodIPv4", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = rW, H$.init($, X), $._zod.onattach.push((J) => {
    let Q = J._zod.bag;
    Q.format = "ipv4";
  });
});
var _Y = q("$ZodIPv6", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = oW, H$.init($, X), $._zod.onattach.push((J) => {
    let Q = J._zod.bag;
    Q.format = "ipv6";
  }), $._zod.check = (J) => {
    try {
      new URL(`http://[${J.value}]`);
    } catch (e2) {
      J.issues.push({ code: "invalid_format", format: "ipv6", input: J.value, inst: $, continue: !X.abort });
    }
  };
});
var xY = q("$ZodCIDRv4", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = tW, H$.init($, X);
});
var TY = q("$ZodCIDRv6", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = aW, H$.init($, X), $._zod.check = (J) => {
    let [Q, Y] = J.value.split("/");
    try {
      if (!Y) throw Error();
      let W = Number(Y);
      if (`${W}` !== Y) throw Error();
      if (W < 0 || W > 128) throw Error();
      new URL(`http://[${Q}]`);
    } catch (e2) {
      J.issues.push({ code: "invalid_format", format: "cidrv6", input: J.value, inst: $, continue: !X.abort });
    }
  };
});
function fz($) {
  if ($ === "") return true;
  if ($.length % 4 !== 0) return false;
  try {
    return atob($), true;
  } catch (e2) {
    return false;
  }
}
var yY = q("$ZodBase64", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = sW, H$.init($, X), $._zod.onattach.push((J) => {
    J._zod.bag.contentEncoding = "base64";
  }), $._zod.check = (J) => {
    if (fz(J.value)) return;
    J.issues.push({ code: "invalid_format", format: "base64", input: J.value, inst: $, continue: !X.abort });
  };
});
function VN($) {
  if (!BY.test($)) return false;
  let X = $.replace(/[-_]/g, (Q) => Q === "-" ? "+" : "/"), J = X.padEnd(Math.ceil(X.length / 4) * 4, "=");
  return fz(J);
}
var fY = q("$ZodBase64URL", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = BY, H$.init($, X), $._zod.onattach.push((J) => {
    J._zod.bag.contentEncoding = "base64url";
  }), $._zod.check = (J) => {
    if (VN(J.value)) return;
    J.issues.push({ code: "invalid_format", format: "base64url", input: J.value, inst: $, continue: !X.abort });
  };
});
var gY = q("$ZodE164", ($, X) => {
  var _a3;
  (_a3 = X.pattern) != null ? _a3 : X.pattern = $z, H$.init($, X);
});
function NN($, X = null) {
  try {
    let J = $.split(".");
    if (J.length !== 3) return false;
    let [Q] = J;
    if (!Q) return false;
    let Y = JSON.parse(atob(Q));
    if ("typ" in Y && (Y == null ? void 0 : Y.typ) !== "JWT") return false;
    if (!Y.alg) return false;
    if (X && (!("alg" in Y) || Y.alg !== X)) return false;
    return true;
  } catch (e2) {
    return false;
  }
}
var hY = q("$ZodJWT", ($, X) => {
  H$.init($, X), $._zod.check = (J) => {
    if (NN(J.value, X.alg)) return;
    J.issues.push({ code: "invalid_format", format: "jwt", input: J.value, inst: $, continue: !X.abort });
  };
});
var uY = q("$ZodCustomStringFormat", ($, X) => {
  H$.init($, X), $._zod.check = (J) => {
    if (X.fn(J.value)) return;
    J.issues.push({ code: "invalid_format", format: X.format, input: J.value, inst: $, continue: !X.abort });
  };
});
var kX = q("$ZodNumber", ($, X) => {
  var _a3;
  d.init($, X), $._zod.pattern = (_a3 = $._zod.bag.pattern) != null ? _a3 : Gz, $._zod.parse = (J, Q) => {
    if (X.coerce) try {
      J.value = Number(J.value);
    } catch (z8) {
    }
    let Y = J.value;
    if (typeof Y === "number" && !Number.isNaN(Y) && Number.isFinite(Y)) return J;
    let W = typeof Y === "number" ? Number.isNaN(Y) ? "NaN" : !Number.isFinite(Y) ? "Infinity" : void 0 : void 0;
    return J.issues.push({ expected: "number", code: "invalid_type", input: Y, inst: $, ...W ? { received: W } : {} }), J;
  };
});
var mY = q("$ZodNumber", ($, X) => {
  wz.init($, X), kX.init($, X);
});
var S0 = q("$ZodBoolean", ($, X) => {
  d.init($, X), $._zod.pattern = Uz, $._zod.parse = (J, Q) => {
    if (X.coerce) try {
      J.value = Boolean(J.value);
    } catch (W) {
    }
    let Y = J.value;
    if (typeof Y === "boolean") return J;
    return J.issues.push({ expected: "boolean", code: "invalid_type", input: Y, inst: $ }), J;
  };
});
var _X = q("$ZodBigInt", ($, X) => {
  d.init($, X), $._zod.pattern = Wz, $._zod.parse = (J, Q) => {
    if (X.coerce) try {
      J.value = BigInt(J.value);
    } catch (Y) {
    }
    if (typeof J.value === "bigint") return J;
    return J.issues.push({ expected: "bigint", code: "invalid_type", input: J.value, inst: $ }), J;
  };
});
var lY = q("$ZodBigInt", ($, X) => {
  Bz.init($, X), _X.init($, X);
});
var cY = q("$ZodSymbol", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = J.value;
    if (typeof Y === "symbol") return J;
    return J.issues.push({ expected: "symbol", code: "invalid_type", input: Y, inst: $ }), J;
  };
});
var pY = q("$ZodUndefined", ($, X) => {
  d.init($, X), $._zod.pattern = Kz, $._zod.values = /* @__PURE__ */ new Set([void 0]), $._zod.optin = "optional", $._zod.optout = "optional", $._zod.parse = (J, Q) => {
    let Y = J.value;
    if (typeof Y > "u") return J;
    return J.issues.push({ expected: "undefined", code: "invalid_type", input: Y, inst: $ }), J;
  };
});
var dY = q("$ZodNull", ($, X) => {
  d.init($, X), $._zod.pattern = Hz, $._zod.values = /* @__PURE__ */ new Set([null]), $._zod.parse = (J, Q) => {
    let Y = J.value;
    if (Y === null) return J;
    return J.issues.push({ expected: "null", code: "invalid_type", input: Y, inst: $ }), J;
  };
});
var iY = q("$ZodAny", ($, X) => {
  d.init($, X), $._zod.parse = (J) => J;
});
var C1 = q("$ZodUnknown", ($, X) => {
  d.init($, X), $._zod.parse = (J) => J;
});
var nY = q("$ZodNever", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    return J.issues.push({ expected: "never", code: "invalid_type", input: J.value, inst: $ }), J;
  };
});
var rY = q("$ZodVoid", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = J.value;
    if (typeof Y > "u") return J;
    return J.issues.push({ expected: "void", code: "invalid_type", input: Y, inst: $ }), J;
  };
});
var oY = q("$ZodDate", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    if (X.coerce) try {
      J.value = new Date(J.value);
    } catch (G) {
    }
    let Y = J.value, W = Y instanceof Date;
    if (W && !Number.isNaN(Y.getTime())) return J;
    return J.issues.push({ expected: "date", code: "invalid_type", input: Y, ...W ? { received: "Invalid Date" } : {}, inst: $ }), J;
  };
});
function $N($, X, J) {
  if ($.issues.length) X.issues.push(...z6(J, $.issues));
  X.value[J] = $.value;
}
var v0 = q("$ZodArray", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = J.value;
    if (!Array.isArray(Y)) return J.issues.push({ expected: "array", code: "invalid_type", input: Y, inst: $ }), J;
    J.value = Array(Y.length);
    let W = [];
    for (let z8 = 0; z8 < Y.length; z8++) {
      let G = Y[z8], U = X.element._zod.run({ value: G, issues: [] }, Q);
      if (U instanceof Promise) W.push(U.then((H) => $N(H, J, z8)));
      else $N(U, J, z8);
    }
    if (W.length) return Promise.all(W).then(() => J);
    return J;
  };
});
function jY($, X, J) {
  if ($.issues.length) X.issues.push(...z6(J, $.issues));
  X.value[J] = $.value;
}
function XN($, X, J, Q) {
  if ($.issues.length) if (Q[J] === void 0) if (J in Q) X.value[J] = void 0;
  else X.value[J] = $.value;
  else X.issues.push(...z6(J, $.issues));
  else if ($.value === void 0) {
    if (J in Q) X.value[J] = void 0;
  } else X.value[J] = $.value;
}
var xX = q("$ZodObject", ($, X) => {
  d.init($, X);
  let J = PX(() => {
    let V = Object.keys(X.shape);
    for (let O of V) if (!(X.shape[O] instanceof d)) throw Error(`Invalid element at key "${O}": expected a Zod schema`);
    let N = xW(X.shape);
    return { shape: X.shape, keys: V, keySet: new Set(V), numKeys: V.length, optionalKeys: new Set(N) };
  });
  G$($._zod, "propValues", () => {
    var _a3;
    let V = X.shape, N = {};
    for (let O in V) {
      let w = V[O]._zod;
      if (w.values) {
        (_a3 = N[O]) != null ? _a3 : N[O] = /* @__PURE__ */ new Set();
        for (let B of w.values) N[O].add(B);
      }
    }
    return N;
  });
  let Q = (V) => {
    let N = new DY(["shape", "payload", "ctx"]), O = J.value, w = (A) => {
      let I = P1(A);
      return `shape[${I}]._zod.run({ value: input[${I}], issues: [] }, ctx)`;
    };
    N.write("const input = payload.value;");
    let B = /* @__PURE__ */ Object.create(null), D = 0;
    for (let A of O.keys) B[A] = `key_${D++}`;
    N.write("const newResult = {}");
    for (let A of O.keys) if (O.optionalKeys.has(A)) {
      let I = B[A];
      N.write(`const ${I} = ${w(A)};`);
      let x = P1(A);
      N.write(`
        if (${I}.issues.length) {
          if (input[${x}] === undefined) {
            if (${x} in input) {
              newResult[${x}] = undefined;
            }
          } else {
            payload.issues = payload.issues.concat(
              ${I}.issues.map((iss) => ({
                ...iss,
                path: iss.path ? [${x}, ...iss.path] : [${x}],
              }))
            );
          }
        } else if (${I}.value === undefined) {
          if (${x} in input) newResult[${x}] = undefined;
        } else {
          newResult[${x}] = ${I}.value;
        }
        `);
    } else {
      let I = B[A];
      N.write(`const ${I} = ${w(A)};`), N.write(`
          if (${I}.issues.length) payload.issues = payload.issues.concat(${I}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${P1(A)}, ...iss.path] : [${P1(A)}]
          })));`), N.write(`newResult[${P1(A)}] = ${I}.value`);
    }
    N.write("payload.value = newResult;"), N.write("return payload;");
    let j = N.compile();
    return (A, I) => j(V, A, I);
  }, Y, W = I0, z8 = !IX.jitless, U = z8 && kW.value, H = X.catchall, K;
  $._zod.parse = (V, N) => {
    K != null ? K : K = J.value;
    let O = V.value;
    if (!W(O)) return V.issues.push({ expected: "object", code: "invalid_type", input: O, inst: $ }), V;
    let w = [];
    if (z8 && U && (N == null ? void 0 : N.async) === false && N.jitless !== true) {
      if (!Y) Y = Q(X.shape);
      V = Y(V, N);
    } else {
      V.value = {};
      let I = K.shape;
      for (let x of K.keys) {
        let T = I[x], U$ = T._zod.run({ value: O[x], issues: [] }, N), T$ = T._zod.optin === "optional" && T._zod.optout === "optional";
        if (U$ instanceof Promise) w.push(U$.then((n$) => T$ ? XN(n$, V, x, O) : jY(n$, V, x)));
        else if (T$) XN(U$, V, x, O);
        else jY(U$, V, x);
      }
    }
    if (!H) return w.length ? Promise.all(w).then(() => V) : V;
    let B = [], D = K.keySet, j = H._zod, A = j.def.type;
    for (let I of Object.keys(O)) {
      if (D.has(I)) continue;
      if (A === "never") {
        B.push(I);
        continue;
      }
      let x = j.run({ value: O[I], issues: [] }, N);
      if (x instanceof Promise) w.push(x.then((T) => jY(T, V, I)));
      else jY(x, V, I);
    }
    if (B.length) V.issues.push({ code: "unrecognized_keys", keys: B, input: O, inst: $ });
    if (!w.length) return V;
    return Promise.all(w).then(() => {
      return V;
    });
  };
});
function JN($, X, J, Q) {
  for (let Y of $) if (Y.issues.length === 0) return X.value = Y.value, X;
  return X.issues.push({ code: "invalid_union", input: X.value, inst: J, errors: $.map((Y) => Y.issues.map((W) => D6(W, Q, E$()))) }), X;
}
var TX = q("$ZodUnion", ($, X) => {
  d.init($, X), G$($._zod, "optin", () => X.options.some((J) => J._zod.optin === "optional") ? "optional" : void 0), G$($._zod, "optout", () => X.options.some((J) => J._zod.optout === "optional") ? "optional" : void 0), G$($._zod, "values", () => {
    if (X.options.every((J) => J._zod.values)) return new Set(X.options.flatMap((J) => Array.from(J._zod.values)));
    return;
  }), G$($._zod, "pattern", () => {
    if (X.options.every((J) => J._zod.pattern)) {
      let J = X.options.map((Q) => Q._zod.pattern);
      return new RegExp(`^(${J.map((Q) => RX(Q.source)).join("|")})$`);
    }
    return;
  }), $._zod.parse = (J, Q) => {
    let Y = false, W = [];
    for (let z8 of X.options) {
      let G = z8._zod.run({ value: J.value, issues: [] }, Q);
      if (G instanceof Promise) W.push(G), Y = true;
      else {
        if (G.issues.length === 0) return G;
        W.push(G);
      }
    }
    if (!Y) return JN(W, J, $, Q);
    return Promise.all(W).then((z8) => {
      return JN(z8, J, $, Q);
    });
  };
});
var tY = q("$ZodDiscriminatedUnion", ($, X) => {
  TX.init($, X);
  let J = $._zod.parse;
  G$($._zod, "propValues", () => {
    let Y = {};
    for (let W of X.options) {
      let z8 = W._zod.propValues;
      if (!z8 || Object.keys(z8).length === 0) throw Error(`Invalid discriminated union option at index "${X.options.indexOf(W)}"`);
      for (let [G, U] of Object.entries(z8)) {
        if (!Y[G]) Y[G] = /* @__PURE__ */ new Set();
        for (let H of U) Y[G].add(H);
      }
    }
    return Y;
  });
  let Q = PX(() => {
    let Y = X.options, W = /* @__PURE__ */ new Map();
    for (let z8 of Y) {
      let G = z8._zod.propValues[X.discriminator];
      if (!G || G.size === 0) throw Error(`Invalid discriminated union option at index "${X.options.indexOf(z8)}"`);
      for (let U of G) {
        if (W.has(U)) throw Error(`Duplicate discriminator value "${String(U)}"`);
        W.set(U, z8);
      }
    }
    return W;
  });
  $._zod.parse = (Y, W) => {
    let z8 = Y.value;
    if (!I0(z8)) return Y.issues.push({ code: "invalid_type", expected: "object", input: z8, inst: $ }), Y;
    let G = Q.value.get(z8 == null ? void 0 : z8[X.discriminator]);
    if (G) return G._zod.run(Y, W);
    if (X.unionFallback) return J(Y, W);
    return Y.issues.push({ code: "invalid_union", errors: [], note: "No matching discriminator", input: z8, path: [X.discriminator], inst: $ }), Y;
  };
});
var aY = q("$ZodIntersection", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = J.value, W = X.left._zod.run({ value: Y, issues: [] }, Q), z8 = X.right._zod.run({ value: Y, issues: [] }, Q);
    if (W instanceof Promise || z8 instanceof Promise) return Promise.all([W, z8]).then(([U, H]) => {
      return YN(J, U, H);
    });
    return YN(J, W, z8);
  };
});
function kz($, X) {
  if ($ === X) return { valid: true, data: $ };
  if ($ instanceof Date && X instanceof Date && +$ === +X) return { valid: true, data: $ };
  if (b0($) && b0(X)) {
    let J = Object.keys(X), Q = Object.keys($).filter((W) => J.indexOf(W) !== -1), Y = { ...$, ...X };
    for (let W of Q) {
      let z8 = kz($[W], X[W]);
      if (!z8.valid) return { valid: false, mergeErrorPath: [W, ...z8.mergeErrorPath] };
      Y[W] = z8.data;
    }
    return { valid: true, data: Y };
  }
  if (Array.isArray($) && Array.isArray(X)) {
    if ($.length !== X.length) return { valid: false, mergeErrorPath: [] };
    let J = [];
    for (let Q = 0; Q < $.length; Q++) {
      let Y = $[Q], W = X[Q], z8 = kz(Y, W);
      if (!z8.valid) return { valid: false, mergeErrorPath: [Q, ...z8.mergeErrorPath] };
      J.push(z8.data);
    }
    return { valid: true, data: J };
  }
  return { valid: false, mergeErrorPath: [] };
}
function YN($, X, J) {
  if (X.issues.length) $.issues.push(...X.issues);
  if (J.issues.length) $.issues.push(...J.issues);
  if (R1($)) return $;
  let Q = kz(X.value, J.value);
  if (!Q.valid) throw Error(`Unmergable intersection. Error path: ${JSON.stringify(Q.mergeErrorPath)}`);
  return $.value = Q.data, $;
}
var i4 = q("$ZodTuple", ($, X) => {
  d.init($, X);
  let J = X.items, Q = J.length - [...J].reverse().findIndex((Y) => Y._zod.optin !== "optional");
  $._zod.parse = (Y, W) => {
    let z8 = Y.value;
    if (!Array.isArray(z8)) return Y.issues.push({ input: z8, inst: $, expected: "tuple", code: "invalid_type" }), Y;
    Y.value = [];
    let G = [];
    if (!X.rest) {
      let H = z8.length > J.length, K = z8.length < Q - 1;
      if (H || K) return Y.issues.push({ input: z8, inst: $, origin: "array", ...H ? { code: "too_big", maximum: J.length } : { code: "too_small", minimum: J.length } }), Y;
    }
    let U = -1;
    for (let H of J) {
      if (U++, U >= z8.length) {
        if (U >= Q) continue;
      }
      let K = H._zod.run({ value: z8[U], issues: [] }, W);
      if (K instanceof Promise) G.push(K.then((V) => FY(V, Y, U)));
      else FY(K, Y, U);
    }
    if (X.rest) {
      let H = z8.slice(J.length);
      for (let K of H) {
        U++;
        let V = X.rest._zod.run({ value: K, issues: [] }, W);
        if (V instanceof Promise) G.push(V.then((N) => FY(N, Y, U)));
        else FY(V, Y, U);
      }
    }
    if (G.length) return Promise.all(G).then(() => Y);
    return Y;
  };
});
function FY($, X, J) {
  if ($.issues.length) X.issues.push(...z6(J, $.issues));
  X.value[J] = $.value;
}
var sY = q("$ZodRecord", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = J.value;
    if (!b0(Y)) return J.issues.push({ expected: "record", code: "invalid_type", input: Y, inst: $ }), J;
    let W = [];
    if (X.keyType._zod.values) {
      let z8 = X.keyType._zod.values;
      J.value = {};
      for (let U of z8) if (typeof U === "string" || typeof U === "number" || typeof U === "symbol") {
        let H = X.valueType._zod.run({ value: Y[U], issues: [] }, Q);
        if (H instanceof Promise) W.push(H.then((K) => {
          if (K.issues.length) J.issues.push(...z6(U, K.issues));
          J.value[U] = K.value;
        }));
        else {
          if (H.issues.length) J.issues.push(...z6(U, H.issues));
          J.value[U] = H.value;
        }
      }
      let G;
      for (let U in Y) if (!z8.has(U)) G = G != null ? G : [], G.push(U);
      if (G && G.length > 0) J.issues.push({ code: "unrecognized_keys", input: Y, inst: $, keys: G });
    } else {
      J.value = {};
      for (let z8 of Reflect.ownKeys(Y)) {
        if (z8 === "__proto__") continue;
        let G = X.keyType._zod.run({ value: z8, issues: [] }, Q);
        if (G instanceof Promise) throw Error("Async schemas not supported in object keys currently");
        if (G.issues.length) {
          J.issues.push({ origin: "record", code: "invalid_key", issues: G.issues.map((H) => D6(H, Q, E$())), input: z8, path: [z8], inst: $ }), J.value[G.value] = G.value;
          continue;
        }
        let U = X.valueType._zod.run({ value: Y[z8], issues: [] }, Q);
        if (U instanceof Promise) W.push(U.then((H) => {
          if (H.issues.length) J.issues.push(...z6(z8, H.issues));
          J.value[G.value] = H.value;
        }));
        else {
          if (U.issues.length) J.issues.push(...z6(z8, U.issues));
          J.value[G.value] = U.value;
        }
      }
    }
    if (W.length) return Promise.all(W).then(() => J);
    return J;
  };
});
var eY = q("$ZodMap", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = J.value;
    if (!(Y instanceof Map)) return J.issues.push({ expected: "map", code: "invalid_type", input: Y, inst: $ }), J;
    let W = [];
    J.value = /* @__PURE__ */ new Map();
    for (let [z8, G] of Y) {
      let U = X.keyType._zod.run({ value: z8, issues: [] }, Q), H = X.valueType._zod.run({ value: G, issues: [] }, Q);
      if (U instanceof Promise || H instanceof Promise) W.push(Promise.all([U, H]).then(([K, V]) => {
        QN(K, V, J, z8, Y, $, Q);
      }));
      else QN(U, H, J, z8, Y, $, Q);
    }
    if (W.length) return Promise.all(W).then(() => J);
    return J;
  };
});
function QN($, X, J, Q, Y, W, z8) {
  if ($.issues.length) if (EX.has(typeof Q)) J.issues.push(...z6(Q, $.issues));
  else J.issues.push({ origin: "map", code: "invalid_key", input: Y, inst: W, issues: $.issues.map((G) => D6(G, z8, E$())) });
  if (X.issues.length) if (EX.has(typeof Q)) J.issues.push(...z6(Q, X.issues));
  else J.issues.push({ origin: "map", code: "invalid_element", input: Y, inst: W, key: Q, issues: X.issues.map((G) => D6(G, z8, E$())) });
  J.value.set($.value, X.value);
}
var $7 = q("$ZodSet", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = J.value;
    if (!(Y instanceof Set)) return J.issues.push({ input: Y, inst: $, expected: "set", code: "invalid_type" }), J;
    let W = [];
    J.value = /* @__PURE__ */ new Set();
    for (let z8 of Y) {
      let G = X.valueType._zod.run({ value: z8, issues: [] }, Q);
      if (G instanceof Promise) W.push(G.then((U) => WN(U, J)));
      else WN(G, J);
    }
    if (W.length) return Promise.all(W).then(() => J);
    return J;
  };
});
function WN($, X) {
  if ($.issues.length) X.issues.push(...$.issues);
  X.value.add($.value);
}
var X7 = q("$ZodEnum", ($, X) => {
  d.init($, X);
  let J = ZX(X.entries);
  $._zod.values = new Set(J), $._zod.pattern = new RegExp(`^(${J.filter((Q) => EX.has(typeof Q)).map((Q) => typeof Q === "string" ? D4(Q) : Q.toString()).join("|")})$`), $._zod.parse = (Q, Y) => {
    let W = Q.value;
    if ($._zod.values.has(W)) return Q;
    return Q.issues.push({ code: "invalid_value", values: J, input: W, inst: $ }), Q;
  };
});
var J7 = q("$ZodLiteral", ($, X) => {
  d.init($, X), $._zod.values = new Set(X.values), $._zod.pattern = new RegExp(`^(${X.values.map((J) => typeof J === "string" ? D4(J) : J ? J.toString() : String(J)).join("|")})$`), $._zod.parse = (J, Q) => {
    let Y = J.value;
    if ($._zod.values.has(Y)) return J;
    return J.issues.push({ code: "invalid_value", values: X.values, input: Y, inst: $ }), J;
  };
});
var Y7 = q("$ZodFile", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = J.value;
    if (Y instanceof File) return J;
    return J.issues.push({ expected: "file", code: "invalid_type", input: Y, inst: $ }), J;
  };
});
var C0 = q("$ZodTransform", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = X.transform(J.value, J);
    if (Q.async) return (Y instanceof Promise ? Y : Promise.resolve(Y)).then((z8) => {
      return J.value = z8, J;
    });
    if (Y instanceof Promise) throw new L4();
    return J.value = Y, J;
  };
});
var Q7 = q("$ZodOptional", ($, X) => {
  d.init($, X), $._zod.optin = "optional", $._zod.optout = "optional", G$($._zod, "values", () => {
    return X.innerType._zod.values ? /* @__PURE__ */ new Set([...X.innerType._zod.values, void 0]) : void 0;
  }), G$($._zod, "pattern", () => {
    let J = X.innerType._zod.pattern;
    return J ? new RegExp(`^(${RX(J.source)})?$`) : void 0;
  }), $._zod.parse = (J, Q) => {
    if (X.innerType._zod.optin === "optional") return X.innerType._zod.run(J, Q);
    if (J.value === void 0) return J;
    return X.innerType._zod.run(J, Q);
  };
});
var W7 = q("$ZodNullable", ($, X) => {
  d.init($, X), G$($._zod, "optin", () => X.innerType._zod.optin), G$($._zod, "optout", () => X.innerType._zod.optout), G$($._zod, "pattern", () => {
    let J = X.innerType._zod.pattern;
    return J ? new RegExp(`^(${RX(J.source)}|null)$`) : void 0;
  }), G$($._zod, "values", () => {
    return X.innerType._zod.values ? /* @__PURE__ */ new Set([...X.innerType._zod.values, null]) : void 0;
  }), $._zod.parse = (J, Q) => {
    if (J.value === null) return J;
    return X.innerType._zod.run(J, Q);
  };
});
var z7 = q("$ZodDefault", ($, X) => {
  d.init($, X), $._zod.optin = "optional", G$($._zod, "values", () => X.innerType._zod.values), $._zod.parse = (J, Q) => {
    if (J.value === void 0) return J.value = X.defaultValue, J;
    let Y = X.innerType._zod.run(J, Q);
    if (Y instanceof Promise) return Y.then((W) => zN(W, X));
    return zN(Y, X);
  };
});
function zN($, X) {
  if ($.value === void 0) $.value = X.defaultValue;
  return $;
}
var G7 = q("$ZodPrefault", ($, X) => {
  d.init($, X), $._zod.optin = "optional", G$($._zod, "values", () => X.innerType._zod.values), $._zod.parse = (J, Q) => {
    if (J.value === void 0) J.value = X.defaultValue;
    return X.innerType._zod.run(J, Q);
  };
});
var U7 = q("$ZodNonOptional", ($, X) => {
  d.init($, X), G$($._zod, "values", () => {
    let J = X.innerType._zod.values;
    return J ? new Set([...J].filter((Q) => Q !== void 0)) : void 0;
  }), $._zod.parse = (J, Q) => {
    let Y = X.innerType._zod.run(J, Q);
    if (Y instanceof Promise) return Y.then((W) => GN(W, $));
    return GN(Y, $);
  };
});
function GN($, X) {
  if (!$.issues.length && $.value === void 0) $.issues.push({ code: "invalid_type", expected: "nonoptional", input: $.value, inst: X });
  return $;
}
var H7 = q("$ZodSuccess", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    let Y = X.innerType._zod.run(J, Q);
    if (Y instanceof Promise) return Y.then((W) => {
      return J.value = W.issues.length === 0, J;
    });
    return J.value = Y.issues.length === 0, J;
  };
});
var K7 = q("$ZodCatch", ($, X) => {
  d.init($, X), $._zod.optin = "optional", G$($._zod, "optout", () => X.innerType._zod.optout), G$($._zod, "values", () => X.innerType._zod.values), $._zod.parse = (J, Q) => {
    let Y = X.innerType._zod.run(J, Q);
    if (Y instanceof Promise) return Y.then((W) => {
      if (J.value = W.value, W.issues.length) J.value = X.catchValue({ ...J, error: { issues: W.issues.map((z8) => D6(z8, Q, E$())) }, input: J.value }), J.issues = [];
      return J;
    });
    if (J.value = Y.value, Y.issues.length) J.value = X.catchValue({ ...J, error: { issues: Y.issues.map((W) => D6(W, Q, E$())) }, input: J.value }), J.issues = [];
    return J;
  };
});
var V7 = q("$ZodNaN", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    if (typeof J.value !== "number" || !Number.isNaN(J.value)) return J.issues.push({ input: J.value, inst: $, expected: "nan", code: "invalid_type" }), J;
    return J;
  };
});
var k0 = q("$ZodPipe", ($, X) => {
  d.init($, X), G$($._zod, "values", () => X.in._zod.values), G$($._zod, "optin", () => X.in._zod.optin), G$($._zod, "optout", () => X.out._zod.optout), $._zod.parse = (J, Q) => {
    let Y = X.in._zod.run(J, Q);
    if (Y instanceof Promise) return Y.then((W) => UN(W, X, Q));
    return UN(Y, X, Q);
  };
});
function UN($, X, J) {
  if (R1($)) return $;
  return X.out._zod.run({ value: $.value, issues: $.issues }, J);
}
var N7 = q("$ZodReadonly", ($, X) => {
  d.init($, X), G$($._zod, "propValues", () => X.innerType._zod.propValues), G$($._zod, "values", () => X.innerType._zod.values), G$($._zod, "optin", () => X.innerType._zod.optin), G$($._zod, "optout", () => X.innerType._zod.optout), $._zod.parse = (J, Q) => {
    let Y = X.innerType._zod.run(J, Q);
    if (Y instanceof Promise) return Y.then(HN);
    return HN(Y);
  };
});
function HN($) {
  return $.value = Object.freeze($.value), $;
}
var O7 = q("$ZodTemplateLiteral", ($, X) => {
  d.init($, X);
  let J = [];
  for (let Q of X.parts) if (Q instanceof d) {
    if (!Q._zod.pattern) throw Error(`Invalid template literal part, no pattern found: ${[...Q._zod.traits].shift()}`);
    let Y = Q._zod.pattern instanceof RegExp ? Q._zod.pattern.source : Q._zod.pattern;
    if (!Y) throw Error(`Invalid template literal part: ${Q._zod.traits}`);
    let W = Y.startsWith("^") ? 1 : 0, z8 = Y.endsWith("$") ? Y.length - 1 : Y.length;
    J.push(Y.slice(W, z8));
  } else if (Q === null || _W.has(typeof Q)) J.push(D4(`${Q}`));
  else throw Error(`Invalid template literal part: ${Q}`);
  $._zod.pattern = new RegExp(`^${J.join("")}$`), $._zod.parse = (Q, Y) => {
    if (typeof Q.value !== "string") return Q.issues.push({ input: Q.value, inst: $, expected: "template_literal", code: "invalid_type" }), Q;
    if ($._zod.pattern.lastIndex = 0, !$._zod.pattern.test(Q.value)) return Q.issues.push({ input: Q.value, inst: $, code: "invalid_format", format: "template_literal", pattern: $._zod.pattern.source }), Q;
    return Q;
  };
});
var w7 = q("$ZodPromise", ($, X) => {
  d.init($, X), $._zod.parse = (J, Q) => {
    return Promise.resolve(J.value).then((Y) => X.innerType._zod.run({ value: Y, issues: [] }, Q));
  };
});
var B7 = q("$ZodLazy", ($, X) => {
  d.init($, X), G$($._zod, "innerType", () => X.getter()), G$($._zod, "pattern", () => $._zod.innerType._zod.pattern), G$($._zod, "propValues", () => $._zod.innerType._zod.propValues), G$($._zod, "optin", () => $._zod.innerType._zod.optin), G$($._zod, "optout", () => $._zod.innerType._zod.optout), $._zod.parse = (J, Q) => {
    return $._zod.innerType._zod.run(J, Q);
  };
});
var q7 = q("$ZodCustom", ($, X) => {
  A$.init($, X), d.init($, X), $._zod.parse = (J, Q) => {
    return J;
  }, $._zod.check = (J) => {
    let Q = J.value, Y = X.fn(Q);
    if (Y instanceof Promise) return Y.then((W) => KN(W, J, Q, $));
    KN(Y, J, Q, $);
    return;
  };
});
function KN($, X, J, Q) {
  var _a3;
  if (!$) {
    let Y = { code: "custom", input: J, inst: Q, path: [...(_a3 = Q._zod.def.path) != null ? _a3 : []], continue: !Q._zod.def.abort };
    if (Q._zod.def.params) Y.params = Q._zod.def.params;
    X.issues.push(fW(Y));
  }
}
var _0 = {};
H1(_0, { zhTW: () => M3, zhCN: () => F3, vi: () => j3, ur: () => D3, ua: () => L3, tr: () => q3, th: () => B3, ta: () => w3, sv: () => O3, sl: () => N3, ru: () => V3, pt: () => K3, ps: () => U3, pl: () => H3, ota: () => G3, no: () => z3, nl: () => W3, ms: () => Q3, mk: () => Y3, ko: () => J3, kh: () => X3, ja: () => $3, it: () => ez, id: () => sz, hu: () => az, he: () => tz, frCA: () => oz, fr: () => rz, fi: () => nz, fa: () => iz, es: () => dz, eo: () => pz, en: () => yX, de: () => cz, cs: () => lz, ca: () => mz, be: () => uz, az: () => hz, ar: () => gz });
var CI = () => {
  let $ = { string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }, set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "number";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0645\u062F\u062E\u0644", email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A", url: "\u0631\u0627\u0628\u0637", emoji: "\u0625\u064A\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO", time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO", duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO", ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4", ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6", cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4", cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6", base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded", base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded", json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON", e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164", jwt: "JWT", template_literal: "\u0645\u062F\u062E\u0644" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${Y.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${S(Y.values[0])}`;
        return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${(_a3 = Y.origin) != null ? _a3 : "\u0627\u0644\u0642\u064A\u0645\u0629"} ${W} ${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u0639\u0646\u0635\u0631"}`;
        return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${(_c = Y.origin) != null ? _c : "\u0627\u0644\u0642\u064A\u0645\u0629"} ${W} ${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${Y.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${W} ${Y.minimum.toString()} ${z8.unit}`;
        return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${Y.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${W} ${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${Y.prefix}"`;
        if (W.format === "ends_with") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${W.suffix}"`;
        if (W.format === "includes") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${W.includes}"`;
        if (W.format === "regex") return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${W.pattern}`;
        return `${(_d2 = Q[W.format]) != null ? _d2 : Y.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;
      }
      case "not_multiple_of":
        return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${Y.divisor}`;
      case "unrecognized_keys":
        return `\u0645\u0639\u0631\u0641${Y.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${Y.keys.length > 1 ? "\u0629" : ""}: ${M(Y.keys, "\u060C ")}`;
      case "invalid_key":
        return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${Y.origin}`;
      case "invalid_union":
        return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
      case "invalid_element":
        return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${Y.origin}`;
      default:
        return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
    }
  };
};
function gz() {
  return { localeError: CI() };
}
var kI = () => {
  let $ = { string: { unit: "simvol", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "element", verb: "olmal\u0131d\u0131r" }, set: { unit: "element", verb: "olmal\u0131d\u0131r" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "number";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { 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 (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${Y.expected}, daxil olan ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${S(Y.values[0])}`;
        return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${(_a3 = Y.origin) != null ? _a3 : "d\u0259y\u0259r"} ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "element"}`;
        return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${(_c = Y.origin) != null ? _c : "d\u0259y\u0259r"} ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${Y.origin} ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${Y.origin} ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Yanl\u0131\u015F m\u0259tn: "${W.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;
        if (W.format === "ends_with") return `Yanl\u0131\u015F m\u0259tn: "${W.suffix}" il\u0259 bitm\u0259lidir`;
        if (W.format === "includes") return `Yanl\u0131\u015F m\u0259tn: "${W.includes}" daxil olmal\u0131d\u0131r`;
        if (W.format === "regex") return `Yanl\u0131\u015F m\u0259tn: ${W.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;
        return `Yanl\u0131\u015F ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `Yanl\u0131\u015F \u0259d\u0259d: ${Y.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan a\xE7ar${Y.keys.length > 1 ? "lar" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `${Y.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
      case "invalid_union":
        return "Yanl\u0131\u015F d\u0259y\u0259r";
      case "invalid_element":
        return `${Y.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;
      default:
        return "Yanl\u0131\u015F d\u0259y\u0259r";
    }
  };
};
function hz() {
  return { localeError: kI() };
}
function wN($, X, J, Q) {
  let Y = Math.abs($), W = Y % 10, z8 = Y % 100;
  if (z8 >= 11 && z8 <= 19) return Q;
  if (W === 1) return X;
  if (W >= 2 && W <= 4) return J;
  return Q;
}
var _I = () => {
  let $ = { string: { unit: { one: "\u0441\u0456\u043C\u0432\u0430\u043B", few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B", many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u044B", many: "\u0431\u0430\u0439\u0442\u0430\u045E" }, verb: "\u043C\u0435\u0446\u044C" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u043B\u0456\u043A";
      case "object": {
        if (Array.isArray(Y)) return "\u043C\u0430\u0441\u0456\u045E";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0443\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0430\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0447\u0430\u0441", duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441", cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D", base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64", base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url", json_string: "JSON \u0440\u0430\u0434\u043E\u043A", e164: "\u043D\u0443\u043C\u0430\u0440 E.164", jwt: "JWT", template_literal: "\u0443\u0432\u043E\u0434" };
  return (Y) => {
    var _a3, _b2, _c;
    switch (Y.code) {
      case "invalid_type":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${Y.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${S(Y.values[0])}`;
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) {
          let G = Number(Y.maximum), U = wN(G, z8.unit.one, z8.unit.few, z8.unit.many);
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${(_a3 = Y.origin) != null ? _a3 : "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${z8.verb} ${W}${Y.maximum.toString()} ${U}`;
        }
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${(_b2 = Y.origin) != null ? _b2 : "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) {
          let G = Number(Y.minimum), U = wN(G, z8.unit.one, z8.unit.few, z8.unit.many);
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${Y.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${z8.verb} ${W}${Y.minimum.toString()} ${U}`;
        }
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${Y.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${W.prefix}"`;
        if (W.format === "ends_with") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${W.suffix}"`;
        if (W.format === "includes") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${W.includes}"`;
        if (W.format === "regex") return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${W.pattern}`;
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${(_c = Q[W.format]) != null ? _c : Y.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${Y.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${Y.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${Y.origin}`;
      case "invalid_union":
        return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";
      case "invalid_element":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${Y.origin}`;
      default:
        return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";
    }
  };
};
function uz() {
  return { localeError: _I() };
}
var xI = () => {
  let $ = { string: { unit: "car\xE0cters", verb: "contenir" }, file: { unit: "bytes", verb: "contenir" }, array: { unit: "elements", verb: "contenir" }, set: { unit: "elements", verb: "contenir" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "number";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "entrada", email: "adre\xE7a electr\xF2nica", 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: "data i hora ISO", date: "data ISO", time: "hora ISO", duration: "durada ISO", ipv4: "adre\xE7a IPv4", ipv6: "adre\xE7a IPv6", cidrv4: "rang IPv4", cidrv6: "rang IPv6", base64: "cadena codificada en base64", base64url: "cadena codificada en base64url", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Tipus inv\xE0lid: s'esperava ${Y.expected}, s'ha rebut ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Valor inv\xE0lid: s'esperava ${S(Y.values[0])}`;
        return `Opci\xF3 inv\xE0lida: s'esperava una de ${M(Y.values, " o ")}`;
      case "too_big": {
        let W = Y.inclusive ? "com a m\xE0xim" : "menys de", z8 = X(Y.origin);
        if (z8) return `Massa gran: s'esperava que ${(_a3 = Y.origin) != null ? _a3 : "el valor"} contingu\xE9s ${W} ${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elements"}`;
        return `Massa gran: s'esperava que ${(_c = Y.origin) != null ? _c : "el valor"} fos ${W} ${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? "com a m\xEDnim" : "m\xE9s de", z8 = X(Y.origin);
        if (z8) return `Massa petit: s'esperava que ${Y.origin} contingu\xE9s ${W} ${Y.minimum.toString()} ${z8.unit}`;
        return `Massa petit: s'esperava que ${Y.origin} fos ${W} ${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Format inv\xE0lid: ha de comen\xE7ar amb "${W.prefix}"`;
        if (W.format === "ends_with") return `Format inv\xE0lid: ha d'acabar amb "${W.suffix}"`;
        if (W.format === "includes") return `Format inv\xE0lid: ha d'incloure "${W.includes}"`;
        if (W.format === "regex") return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${W.pattern}`;
        return `Format inv\xE0lid per a ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${Y.divisor}`;
      case "unrecognized_keys":
        return `Clau${Y.keys.length > 1 ? "s" : ""} no reconeguda${Y.keys.length > 1 ? "s" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Clau inv\xE0lida a ${Y.origin}`;
      case "invalid_union":
        return "Entrada inv\xE0lida";
      case "invalid_element":
        return `Element inv\xE0lid a ${Y.origin}`;
      default:
        return "Entrada inv\xE0lida";
    }
  };
};
function mz() {
  return { localeError: xI() };
}
var TI = () => {
  let $ = { string: { unit: "znak\u016F", verb: "m\xEDt" }, file: { unit: "bajt\u016F", verb: "m\xEDt" }, array: { unit: "prvk\u016F", verb: "m\xEDt" }, set: { unit: "prvk\u016F", verb: "m\xEDt" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u010D\xEDslo";
      case "string":
        return "\u0159et\u011Bzec";
      case "boolean":
        return "boolean";
      case "bigint":
        return "bigint";
      case "function":
        return "funkce";
      case "symbol":
        return "symbol";
      case "undefined":
        return "undefined";
      case "object": {
        if (Array.isArray(Y)) return "pole";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "regul\xE1rn\xED v\xFDraz", email: "e-mailov\xE1 adresa", 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: "datum a \u010Das ve form\xE1tu ISO", date: "datum ve form\xE1tu ISO", time: "\u010Das ve form\xE1tu ISO", duration: "doba trv\xE1n\xED ISO", ipv4: "IPv4 adresa", ipv6: "IPv6 adresa", cidrv4: "rozsah IPv4", cidrv6: "rozsah IPv6", base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64", base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url", json_string: "\u0159et\u011Bzec ve form\xE1tu JSON", e164: "\u010D\xEDslo E.164", jwt: "JWT", template_literal: "vstup" };
  return (Y) => {
    var _a3, _b2, _c, _d2, _e, _f, _g;
    switch (Y.code) {
      case "invalid_type":
        return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${Y.expected}, obdr\u017Eeno ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${S(Y.values[0])}`;
        return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${(_a3 = Y.origin) != null ? _a3 : "hodnota"} mus\xED m\xEDt ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "prvk\u016F"}`;
        return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${(_c = Y.origin) != null ? _c : "hodnota"} mus\xED b\xFDt ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${(_d2 = Y.origin) != null ? _d2 : "hodnota"} mus\xED m\xEDt ${W}${Y.minimum.toString()} ${(_e = z8.unit) != null ? _e : "prvk\u016F"}`;
        return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${(_f = Y.origin) != null ? _f : "hodnota"} mus\xED b\xFDt ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${W.prefix}"`;
        if (W.format === "ends_with") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${W.suffix}"`;
        if (W.format === "includes") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${W.includes}"`;
        if (W.format === "regex") return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${W.pattern}`;
        return `Neplatn\xFD form\xE1t ${(_g = Q[W.format]) != null ? _g : Y.format}`;
      }
      case "not_multiple_of":
        return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${Y.divisor}`;
      case "unrecognized_keys":
        return `Nezn\xE1m\xE9 kl\xED\u010De: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Neplatn\xFD kl\xED\u010D v ${Y.origin}`;
      case "invalid_union":
        return "Neplatn\xFD vstup";
      case "invalid_element":
        return `Neplatn\xE1 hodnota v ${Y.origin}`;
      default:
        return "Neplatn\xFD vstup";
    }
  };
};
function lz() {
  return { localeError: TI() };
}
var yI = () => {
  let $ = { string: { unit: "Zeichen", verb: "zu haben" }, file: { unit: "Bytes", verb: "zu haben" }, array: { unit: "Elemente", verb: "zu haben" }, set: { unit: "Elemente", verb: "zu haben" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "Zahl";
      case "object": {
        if (Array.isArray(Y)) return "Array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "Eingabe", email: "E-Mail-Adresse", 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-Datum und -Uhrzeit", date: "ISO-Datum", time: "ISO-Uhrzeit", duration: "ISO-Dauer", ipv4: "IPv4-Adresse", ipv6: "IPv6-Adresse", cidrv4: "IPv4-Bereich", cidrv6: "IPv6-Bereich", base64: "Base64-codierter String", base64url: "Base64-URL-codierter String", json_string: "JSON-String", e164: "E.164-Nummer", jwt: "JWT", template_literal: "Eingabe" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Ung\xFCltige Eingabe: erwartet ${Y.expected}, erhalten ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Ung\xFCltige Eingabe: erwartet ${S(Y.values[0])}`;
        return `Ung\xFCltige Option: erwartet eine von ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Zu gro\xDF: erwartet, dass ${(_a3 = Y.origin) != null ? _a3 : "Wert"} ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "Elemente"} hat`;
        return `Zu gro\xDF: erwartet, dass ${(_c = Y.origin) != null ? _c : "Wert"} ${W}${Y.maximum.toString()} ist`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Zu klein: erwartet, dass ${Y.origin} ${W}${Y.minimum.toString()} ${z8.unit} hat`;
        return `Zu klein: erwartet, dass ${Y.origin} ${W}${Y.minimum.toString()} ist`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Ung\xFCltiger String: muss mit "${W.prefix}" beginnen`;
        if (W.format === "ends_with") return `Ung\xFCltiger String: muss mit "${W.suffix}" enden`;
        if (W.format === "includes") return `Ung\xFCltiger String: muss "${W.includes}" enthalten`;
        if (W.format === "regex") return `Ung\xFCltiger String: muss dem Muster ${W.pattern} entsprechen`;
        return `Ung\xFCltig: ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `Ung\xFCltige Zahl: muss ein Vielfaches von ${Y.divisor} sein`;
      case "unrecognized_keys":
        return `${Y.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Ung\xFCltiger Schl\xFCssel in ${Y.origin}`;
      case "invalid_union":
        return "Ung\xFCltige Eingabe";
      case "invalid_element":
        return `Ung\xFCltiger Wert in ${Y.origin}`;
      default:
        return "Ung\xFCltige Eingabe";
    }
  };
};
function cz() {
  return { localeError: yI() };
}
var fI = ($) => {
  let X = typeof $;
  switch (X) {
    case "number":
      return Number.isNaN($) ? "NaN" : "number";
    case "object": {
      if (Array.isArray($)) return "array";
      if ($ === null) return "null";
      if (Object.getPrototypeOf($) !== Object.prototype && $.constructor) return $.constructor.name;
    }
  }
  return X;
};
var gI = () => {
  let $ = { 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 X(Q) {
    var _a3;
    return (_a3 = $[Q]) != null ? _a3 : null;
  }
  let J = { 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 (Q) => {
    var _a3, _b2, _c, _d2;
    switch (Q.code) {
      case "invalid_type":
        return `Invalid input: expected ${Q.expected}, received ${fI(Q.input)}`;
      case "invalid_value":
        if (Q.values.length === 1) return `Invalid input: expected ${S(Q.values[0])}`;
        return `Invalid option: expected one of ${M(Q.values, "|")}`;
      case "too_big": {
        let Y = Q.inclusive ? "<=" : "<", W = X(Q.origin);
        if (W) return `Too big: expected ${(_a3 = Q.origin) != null ? _a3 : "value"} to have ${Y}${Q.maximum.toString()} ${(_b2 = W.unit) != null ? _b2 : "elements"}`;
        return `Too big: expected ${(_c = Q.origin) != null ? _c : "value"} to be ${Y}${Q.maximum.toString()}`;
      }
      case "too_small": {
        let Y = Q.inclusive ? ">=" : ">", W = X(Q.origin);
        if (W) return `Too small: expected ${Q.origin} to have ${Y}${Q.minimum.toString()} ${W.unit}`;
        return `Too small: expected ${Q.origin} to be ${Y}${Q.minimum.toString()}`;
      }
      case "invalid_format": {
        let Y = Q;
        if (Y.format === "starts_with") return `Invalid string: must start with "${Y.prefix}"`;
        if (Y.format === "ends_with") return `Invalid string: must end with "${Y.suffix}"`;
        if (Y.format === "includes") return `Invalid string: must include "${Y.includes}"`;
        if (Y.format === "regex") return `Invalid string: must match pattern ${Y.pattern}`;
        return `Invalid ${(_d2 = J[Y.format]) != null ? _d2 : Q.format}`;
      }
      case "not_multiple_of":
        return `Invalid number: must be a multiple of ${Q.divisor}`;
      case "unrecognized_keys":
        return `Unrecognized key${Q.keys.length > 1 ? "s" : ""}: ${M(Q.keys, ", ")}`;
      case "invalid_key":
        return `Invalid key in ${Q.origin}`;
      case "invalid_union":
        return "Invalid input";
      case "invalid_element":
        return `Invalid value in ${Q.origin}`;
      default:
        return "Invalid input";
    }
  };
};
function yX() {
  return { localeError: gI() };
}
var hI = ($) => {
  let X = typeof $;
  switch (X) {
    case "number":
      return Number.isNaN($) ? "NaN" : "nombro";
    case "object": {
      if (Array.isArray($)) return "tabelo";
      if ($ === null) return "senvalora";
      if (Object.getPrototypeOf($) !== Object.prototype && $.constructor) return $.constructor.name;
    }
  }
  return X;
};
var uI = () => {
  let $ = { string: { unit: "karaktrojn", verb: "havi" }, file: { unit: "bajtojn", verb: "havi" }, array: { unit: "elementojn", verb: "havi" }, set: { unit: "elementojn", verb: "havi" } };
  function X(Q) {
    var _a3;
    return (_a3 = $[Q]) != null ? _a3 : null;
  }
  let J = { regex: "enigo", email: "retadreso", url: "URL", emoji: "emo\u011Dio", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-datotempo", date: "ISO-dato", time: "ISO-tempo", duration: "ISO-da\u016Dro", ipv4: "IPv4-adreso", ipv6: "IPv6-adreso", cidrv4: "IPv4-rango", cidrv6: "IPv6-rango", base64: "64-ume kodita karaktraro", base64url: "URL-64-ume kodita karaktraro", json_string: "JSON-karaktraro", e164: "E.164-nombro", jwt: "JWT", template_literal: "enigo" };
  return (Q) => {
    var _a3, _b2, _c, _d2;
    switch (Q.code) {
      case "invalid_type":
        return `Nevalida enigo: atendi\u011Dis ${Q.expected}, ricevi\u011Dis ${hI(Q.input)}`;
      case "invalid_value":
        if (Q.values.length === 1) return `Nevalida enigo: atendi\u011Dis ${S(Q.values[0])}`;
        return `Nevalida opcio: atendi\u011Dis unu el ${M(Q.values, "|")}`;
      case "too_big": {
        let Y = Q.inclusive ? "<=" : "<", W = X(Q.origin);
        if (W) return `Tro granda: atendi\u011Dis ke ${(_a3 = Q.origin) != null ? _a3 : "valoro"} havu ${Y}${Q.maximum.toString()} ${(_b2 = W.unit) != null ? _b2 : "elementojn"}`;
        return `Tro granda: atendi\u011Dis ke ${(_c = Q.origin) != null ? _c : "valoro"} havu ${Y}${Q.maximum.toString()}`;
      }
      case "too_small": {
        let Y = Q.inclusive ? ">=" : ">", W = X(Q.origin);
        if (W) return `Tro malgranda: atendi\u011Dis ke ${Q.origin} havu ${Y}${Q.minimum.toString()} ${W.unit}`;
        return `Tro malgranda: atendi\u011Dis ke ${Q.origin} estu ${Y}${Q.minimum.toString()}`;
      }
      case "invalid_format": {
        let Y = Q;
        if (Y.format === "starts_with") return `Nevalida karaktraro: devas komenci\u011Di per "${Y.prefix}"`;
        if (Y.format === "ends_with") return `Nevalida karaktraro: devas fini\u011Di per "${Y.suffix}"`;
        if (Y.format === "includes") return `Nevalida karaktraro: devas inkluzivi "${Y.includes}"`;
        if (Y.format === "regex") return `Nevalida karaktraro: devas kongrui kun la modelo ${Y.pattern}`;
        return `Nevalida ${(_d2 = J[Y.format]) != null ? _d2 : Q.format}`;
      }
      case "not_multiple_of":
        return `Nevalida nombro: devas esti oblo de ${Q.divisor}`;
      case "unrecognized_keys":
        return `Nekonata${Q.keys.length > 1 ? "j" : ""} \u015Dlosilo${Q.keys.length > 1 ? "j" : ""}: ${M(Q.keys, ", ")}`;
      case "invalid_key":
        return `Nevalida \u015Dlosilo en ${Q.origin}`;
      case "invalid_union":
        return "Nevalida enigo";
      case "invalid_element":
        return `Nevalida valoro en ${Q.origin}`;
      default:
        return "Nevalida enigo";
    }
  };
};
function pz() {
  return { localeError: uI() };
}
var mI = () => {
  let $ = { string: { unit: "caracteres", verb: "tener" }, file: { unit: "bytes", verb: "tener" }, array: { unit: "elementos", verb: "tener" }, set: { unit: "elementos", verb: "tener" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "n\xFAmero";
      case "object": {
        if (Array.isArray(Y)) return "arreglo";
        if (Y === null) return "nulo";
        if (Object.getPrototypeOf(Y) !== Object.prototype) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "entrada", email: "direcci\xF3n de correo electr\xF3nico", 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: "fecha y hora ISO", date: "fecha ISO", time: "hora ISO", duration: "duraci\xF3n ISO", ipv4: "direcci\xF3n IPv4", ipv6: "direcci\xF3n IPv6", cidrv4: "rango IPv4", cidrv6: "rango IPv6", base64: "cadena codificada en base64", base64url: "URL codificada en base64", json_string: "cadena JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Entrada inv\xE1lida: se esperaba ${Y.expected}, recibido ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Entrada inv\xE1lida: se esperaba ${S(Y.values[0])}`;
        return `Opci\xF3n inv\xE1lida: se esperaba una de ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Demasiado grande: se esperaba que ${(_a3 = Y.origin) != null ? _a3 : "valor"} tuviera ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elementos"}`;
        return `Demasiado grande: se esperaba que ${(_c = Y.origin) != null ? _c : "valor"} fuera ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Demasiado peque\xF1o: se esperaba que ${Y.origin} tuviera ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `Demasiado peque\xF1o: se esperaba que ${Y.origin} fuera ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Cadena inv\xE1lida: debe comenzar con "${W.prefix}"`;
        if (W.format === "ends_with") return `Cadena inv\xE1lida: debe terminar en "${W.suffix}"`;
        if (W.format === "includes") return `Cadena inv\xE1lida: debe incluir "${W.includes}"`;
        if (W.format === "regex") return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${W.pattern}`;
        return `Inv\xE1lido ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${Y.divisor}`;
      case "unrecognized_keys":
        return `Llave${Y.keys.length > 1 ? "s" : ""} desconocida${Y.keys.length > 1 ? "s" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Llave inv\xE1lida en ${Y.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido en ${Y.origin}`;
      default:
        return "Entrada inv\xE1lida";
    }
  };
};
function dz() {
  return { localeError: mI() };
}
var lI = () => {
  let $ = { string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }, set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u0639\u062F\u062F";
      case "object": {
        if (Array.isArray(Y)) return "\u0622\u0631\u0627\u06CC\u0647";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0648\u0631\u0648\u062F\u06CC", email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644", url: "URL", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648", time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648", ipv4: "IPv4 \u0622\u062F\u0631\u0633", ipv6: "IPv6 \u0622\u062F\u0631\u0633", cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647", cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647", base64: "base64-encoded \u0631\u0634\u062A\u0647", base64url: "base64url-encoded \u0631\u0634\u062A\u0647", json_string: "JSON \u0631\u0634\u062A\u0647", e164: "E.164 \u0639\u062F\u062F", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u06CC" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${Y.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${J(Y.input)} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${S(Y.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;
        return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${M(Y.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${(_a3 = Y.origin) != null ? _a3 : "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;
        return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${(_c = Y.origin) != null ? _c : "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${W}${Y.maximum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${Y.origin} \u0628\u0627\u06CC\u062F ${W}${Y.minimum.toString()} ${z8.unit} \u0628\u0627\u0634\u062F`;
        return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${Y.origin} \u0628\u0627\u06CC\u062F ${W}${Y.minimum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${W.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;
        if (W.format === "ends_with") return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${W.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;
        if (W.format === "includes") return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${W.includes}" \u0628\u0627\u0634\u062F`;
        if (W.format === "regex") return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${W.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;
        return `${(_d2 = Q[W.format]) != null ? _d2 : Y.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
      }
      case "not_multiple_of":
        return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${Y.divisor} \u0628\u0627\u0634\u062F`;
      case "unrecognized_keys":
        return `\u06A9\u0644\u06CC\u062F${Y.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${Y.origin}`;
      case "invalid_union":
        return "\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";
      case "invalid_element":
        return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${Y.origin}`;
      default:
        return "\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631";
    }
  };
};
function iz() {
  return { localeError: lI() };
}
var cI = () => {
  let $ = { string: { unit: "merkki\xE4", subject: "merkkijonon" }, file: { unit: "tavua", subject: "tiedoston" }, array: { unit: "alkiota", subject: "listan" }, set: { unit: "alkiota", subject: "joukon" }, number: { unit: "", subject: "luvun" }, bigint: { unit: "", subject: "suuren kokonaisluvun" }, int: { unit: "", subject: "kokonaisluvun" }, date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "number";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "s\xE4\xE4nn\xF6llinen lauseke", email: "s\xE4hk\xF6postiosoite", url: "URL-osoite", emoji: "emoji", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO-aikaleima", date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4", time: "ISO-aika", duration: "ISO-kesto", ipv4: "IPv4-osoite", ipv6: "IPv6-osoite", cidrv4: "IPv4-alue", cidrv6: "IPv6-alue", base64: "base64-koodattu merkkijono", base64url: "base64url-koodattu merkkijono", json_string: "JSON-merkkijono", e164: "E.164-luku", jwt: "JWT", template_literal: "templaattimerkkijono" };
  return (Y) => {
    var _a3;
    switch (Y.code) {
      case "invalid_type":
        return `Virheellinen tyyppi: odotettiin ${Y.expected}, oli ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Virheellinen sy\xF6te: t\xE4ytyy olla ${S(Y.values[0])}`;
        return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Liian suuri: ${z8.subject} t\xE4ytyy olla ${W}${Y.maximum.toString()} ${z8.unit}`.trim();
        return `Liian suuri: arvon t\xE4ytyy olla ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Liian pieni: ${z8.subject} t\xE4ytyy olla ${W}${Y.minimum.toString()} ${z8.unit}`.trim();
        return `Liian pieni: arvon t\xE4ytyy olla ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${W.prefix}"`;
        if (W.format === "ends_with") return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${W.suffix}"`;
        if (W.format === "includes") return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${W.includes}"`;
        if (W.format === "regex") return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${W.pattern}`;
        return `Virheellinen ${(_a3 = Q[W.format]) != null ? _a3 : Y.format}`;
      }
      case "not_multiple_of":
        return `Virheellinen luku: t\xE4ytyy olla luvun ${Y.divisor} monikerta`;
      case "unrecognized_keys":
        return `${Y.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return "Virheellinen avain tietueessa";
      case "invalid_union":
        return "Virheellinen unioni";
      case "invalid_element":
        return "Virheellinen arvo joukossa";
      default:
        return "Virheellinen sy\xF6te";
    }
  };
};
function nz() {
  return { localeError: cI() };
}
var pI = () => {
  let $ = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "nombre";
      case "object": {
        if (Array.isArray(Y)) return "tableau";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "entr\xE9e", email: "adresse e-mail", 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: "date et heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Entr\xE9e invalide : ${Y.expected} attendu, ${J(Y.input)} re\xE7u`;
      case "invalid_value":
        if (Y.values.length === 1) return `Entr\xE9e invalide : ${S(Y.values[0])} attendu`;
        return `Option invalide : une valeur parmi ${M(Y.values, "|")} attendue`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Trop grand : ${(_a3 = Y.origin) != null ? _a3 : "valeur"} doit ${z8.verb} ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\xE9l\xE9ment(s)"}`;
        return `Trop grand : ${(_c = Y.origin) != null ? _c : "valeur"} doit \xEAtre ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Trop petit : ${Y.origin} doit ${z8.verb} ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `Trop petit : ${Y.origin} doit \xEAtre ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Cha\xEEne invalide : doit commencer par "${W.prefix}"`;
        if (W.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${W.suffix}"`;
        if (W.format === "includes") return `Cha\xEEne invalide : doit inclure "${W.includes}"`;
        if (W.format === "regex") return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${W.pattern}`;
        return `${(_d2 = Q[W.format]) != null ? _d2 : Y.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${Y.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${Y.keys.length > 1 ? "s" : ""} non reconnue${Y.keys.length > 1 ? "s" : ""} : ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${Y.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${Y.origin}`;
      default:
        return "Entr\xE9e invalide";
    }
  };
};
function rz() {
  return { localeError: pI() };
}
var dI = () => {
  let $ = { string: { unit: "caract\xE8res", verb: "avoir" }, file: { unit: "octets", verb: "avoir" }, array: { unit: "\xE9l\xE9ments", verb: "avoir" }, set: { unit: "\xE9l\xE9ments", verb: "avoir" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "number";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "entr\xE9e", email: "adresse courriel", 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: "date-heure ISO", date: "date ISO", time: "heure ISO", duration: "dur\xE9e ISO", ipv4: "adresse IPv4", ipv6: "adresse IPv6", cidrv4: "plage IPv4", cidrv6: "plage IPv6", base64: "cha\xEEne encod\xE9e en base64", base64url: "cha\xEEne encod\xE9e en base64url", json_string: "cha\xEEne JSON", e164: "num\xE9ro E.164", jwt: "JWT", template_literal: "entr\xE9e" };
  return (Y) => {
    var _a3, _b2, _c;
    switch (Y.code) {
      case "invalid_type":
        return `Entr\xE9e invalide : attendu ${Y.expected}, re\xE7u ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Entr\xE9e invalide : attendu ${S(Y.values[0])}`;
        return `Option invalide : attendu l'une des valeurs suivantes ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "\u2264" : "<", z8 = X(Y.origin);
        if (z8) return `Trop grand : attendu que ${(_a3 = Y.origin) != null ? _a3 : "la valeur"} ait ${W}${Y.maximum.toString()} ${z8.unit}`;
        return `Trop grand : attendu que ${(_b2 = Y.origin) != null ? _b2 : "la valeur"} soit ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? "\u2265" : ">", z8 = X(Y.origin);
        if (z8) return `Trop petit : attendu que ${Y.origin} ait ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `Trop petit : attendu que ${Y.origin} soit ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Cha\xEEne invalide : doit commencer par "${W.prefix}"`;
        if (W.format === "ends_with") return `Cha\xEEne invalide : doit se terminer par "${W.suffix}"`;
        if (W.format === "includes") return `Cha\xEEne invalide : doit inclure "${W.includes}"`;
        if (W.format === "regex") return `Cha\xEEne invalide : doit correspondre au motif ${W.pattern}`;
        return `${(_c = Q[W.format]) != null ? _c : Y.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${Y.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${Y.keys.length > 1 ? "s" : ""} non reconnue${Y.keys.length > 1 ? "s" : ""} : ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${Y.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${Y.origin}`;
      default:
        return "Entr\xE9e invalide";
    }
  };
};
function oz() {
  return { localeError: dI() };
}
var iI = () => {
  let $ = { string: { unit: "\u05D0\u05D5\u05EA\u05D9\u05D5\u05EA", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" }, set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", verb: "\u05DC\u05DB\u05DC\u05D5\u05DC" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "number";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u05E7\u05DC\u05D8", email: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", url: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", emoji: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", date: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", time: "\u05D6\u05DE\u05DF ISO", duration: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", ipv4: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", ipv6: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", cidrv4: "\u05D8\u05D5\u05D5\u05D7 IPv4", cidrv6: "\u05D8\u05D5\u05D5\u05D7 IPv6", base64: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", base64url: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", json_string: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", e164: "\u05DE\u05E1\u05E4\u05E8 E.164", jwt: "JWT", template_literal: "\u05E7\u05DC\u05D8" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${Y.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA ${S(Y.values[0])}`;
        return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05D0\u05D7\u05EA \u05DE\u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA  ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${(_a3 = Y.origin) != null ? _a3 : "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elements"}`;
        return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${(_c = Y.origin) != null ? _c : "value"} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${Y.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${Y.origin} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1"${W.prefix}"`;
        if (W.format === "ends_with") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${W.suffix}"`;
        if (W.format === "includes") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${W.includes}"`;
        if (W.format === "regex") return `\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05E0\u05D4: \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${W.pattern}`;
        return `${(_d2 = Q[W.format]) != null ? _d2 : Y.format} \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
      }
      case "not_multiple_of":
        return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${Y.divisor}`;
      case "unrecognized_keys":
        return `\u05DE\u05E4\u05EA\u05D7${Y.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${Y.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\u05DE\u05E4\u05EA\u05D7 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${Y.origin}`;
      case "invalid_union":
        return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";
      case "invalid_element":
        return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${Y.origin}`;
      default:
        return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";
    }
  };
};
function tz() {
  return { localeError: iI() };
}
var nI = () => {
  let $ = { string: { unit: "karakter", verb: "legyen" }, file: { unit: "byte", verb: "legyen" }, array: { unit: "elem", verb: "legyen" }, set: { unit: "elem", verb: "legyen" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "sz\xE1m";
      case "object": {
        if (Array.isArray(Y)) return "t\xF6mb";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "bemenet", email: "email c\xEDm", 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 id\u0151b\xE9lyeg", date: "ISO d\xE1tum", time: "ISO id\u0151", duration: "ISO id\u0151intervallum", ipv4: "IPv4 c\xEDm", ipv6: "IPv6 c\xEDm", cidrv4: "IPv4 tartom\xE1ny", cidrv6: "IPv6 tartom\xE1ny", base64: "base64-k\xF3dolt string", base64url: "base64url-k\xF3dolt string", json_string: "JSON string", e164: "E.164 sz\xE1m", jwt: "JWT", template_literal: "bemenet" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${Y.expected}, a kapott \xE9rt\xE9k ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${S(Y.values[0])}`;
        return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `T\xFAl nagy: ${(_a3 = Y.origin) != null ? _a3 : "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elem"}`;
        return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${(_c = Y.origin) != null ? _c : "\xE9rt\xE9k"} t\xFAl nagy: ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${Y.origin} m\xE9rete t\xFAl kicsi ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${Y.origin} t\xFAl kicsi ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\xC9rv\xE9nytelen string: "${W.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;
        if (W.format === "ends_with") return `\xC9rv\xE9nytelen string: "${W.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;
        if (W.format === "includes") return `\xC9rv\xE9nytelen string: "${W.includes}" \xE9rt\xE9ket kell tartalmaznia`;
        if (W.format === "regex") return `\xC9rv\xE9nytelen string: ${W.pattern} mint\xE1nak kell megfelelnie`;
        return `\xC9rv\xE9nytelen ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\xC9rv\xE9nytelen sz\xE1m: ${Y.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;
      case "unrecognized_keys":
        return `Ismeretlen kulcs${Y.keys.length > 1 ? "s" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\xC9rv\xE9nytelen kulcs ${Y.origin}`;
      case "invalid_union":
        return "\xC9rv\xE9nytelen bemenet";
      case "invalid_element":
        return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${Y.origin}`;
      default:
        return "\xC9rv\xE9nytelen bemenet";
    }
  };
};
function az() {
  return { localeError: nI() };
}
var rI = () => {
  let $ = { string: { unit: "karakter", verb: "memiliki" }, file: { unit: "byte", verb: "memiliki" }, array: { unit: "item", verb: "memiliki" }, set: { unit: "item", verb: "memiliki" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "number";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "input", email: "alamat email", 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: "tanggal dan waktu format ISO", date: "tanggal format ISO", time: "jam format ISO", duration: "durasi format ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "rentang alamat IPv4", cidrv6: "rentang alamat IPv6", base64: "string dengan enkode base64", base64url: "string dengan enkode base64url", json_string: "string JSON", e164: "angka E.164", jwt: "JWT", template_literal: "input" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Input tidak valid: diharapkan ${Y.expected}, diterima ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Input tidak valid: diharapkan ${S(Y.values[0])}`;
        return `Pilihan tidak valid: diharapkan salah satu dari ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Terlalu besar: diharapkan ${(_a3 = Y.origin) != null ? _a3 : "value"} memiliki ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elemen"}`;
        return `Terlalu besar: diharapkan ${(_c = Y.origin) != null ? _c : "value"} menjadi ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Terlalu kecil: diharapkan ${Y.origin} memiliki ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `Terlalu kecil: diharapkan ${Y.origin} menjadi ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `String tidak valid: harus dimulai dengan "${W.prefix}"`;
        if (W.format === "ends_with") return `String tidak valid: harus berakhir dengan "${W.suffix}"`;
        if (W.format === "includes") return `String tidak valid: harus menyertakan "${W.includes}"`;
        if (W.format === "regex") return `String tidak valid: harus sesuai pola ${W.pattern}`;
        return `${(_d2 = Q[W.format]) != null ? _d2 : Y.format} tidak valid`;
      }
      case "not_multiple_of":
        return `Angka tidak valid: harus kelipatan dari ${Y.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali ${Y.keys.length > 1 ? "s" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak valid di ${Y.origin}`;
      case "invalid_union":
        return "Input tidak valid";
      case "invalid_element":
        return `Nilai tidak valid di ${Y.origin}`;
      default:
        return "Input tidak valid";
    }
  };
};
function sz() {
  return { localeError: rI() };
}
var oI = () => {
  let $ = { string: { unit: "caratteri", verb: "avere" }, file: { unit: "byte", verb: "avere" }, array: { unit: "elementi", verb: "avere" }, set: { unit: "elementi", verb: "avere" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "numero";
      case "object": {
        if (Array.isArray(Y)) return "vettore";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "input", email: "indirizzo email", 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: "data e ora ISO", date: "data ISO", time: "ora ISO", duration: "durata ISO", ipv4: "indirizzo IPv4", ipv6: "indirizzo IPv6", cidrv4: "intervallo IPv4", cidrv6: "intervallo IPv6", base64: "stringa codificata in base64", base64url: "URL codificata in base64", json_string: "stringa JSON", e164: "numero E.164", jwt: "JWT", template_literal: "input" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Input non valido: atteso ${Y.expected}, ricevuto ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Input non valido: atteso ${S(Y.values[0])}`;
        return `Opzione non valida: atteso uno tra ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Troppo grande: ${(_a3 = Y.origin) != null ? _a3 : "valore"} deve avere ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elementi"}`;
        return `Troppo grande: ${(_c = Y.origin) != null ? _c : "valore"} deve essere ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Troppo piccolo: ${Y.origin} deve avere ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `Troppo piccolo: ${Y.origin} deve essere ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Stringa non valida: deve iniziare con "${W.prefix}"`;
        if (W.format === "ends_with") return `Stringa non valida: deve terminare con "${W.suffix}"`;
        if (W.format === "includes") return `Stringa non valida: deve includere "${W.includes}"`;
        if (W.format === "regex") return `Stringa non valida: deve corrispondere al pattern ${W.pattern}`;
        return `Invalid ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `Numero non valido: deve essere un multiplo di ${Y.divisor}`;
      case "unrecognized_keys":
        return `Chiav${Y.keys.length > 1 ? "i" : "e"} non riconosciut${Y.keys.length > 1 ? "e" : "a"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Chiave non valida in ${Y.origin}`;
      case "invalid_union":
        return "Input non valido";
      case "invalid_element":
        return `Valore non valido in ${Y.origin}`;
      default:
        return "Input non valido";
    }
  };
};
function ez() {
  return { localeError: oI() };
}
var tI = () => {
  let $ = { string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" }, file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" }, array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }, set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u6570\u5024";
      case "object": {
        if (Array.isArray(Y)) return "\u914D\u5217";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u5165\u529B\u5024", email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9", url: "URL", emoji: "\u7D75\u6587\u5B57", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u6642", date: "ISO\u65E5\u4ED8", time: "ISO\u6642\u523B", duration: "ISO\u671F\u9593", ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9", ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9", cidrv4: "IPv4\u7BC4\u56F2", cidrv6: "IPv6\u7BC4\u56F2", base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217", json_string: "JSON\u6587\u5B57\u5217", e164: "E.164\u756A\u53F7", jwt: "JWT", template_literal: "\u5165\u529B\u5024" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u7121\u52B9\u306A\u5165\u529B: ${Y.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${J(Y.input)}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u7121\u52B9\u306A\u5165\u529B: ${S(Y.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;
        return `\u7121\u52B9\u306A\u9078\u629E: ${M(Y.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      case "too_big": {
        let W = Y.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044", z8 = X(Y.origin);
        if (z8) return `\u5927\u304D\u3059\u304E\u308B\u5024: ${(_a3 = Y.origin) != null ? _a3 : "\u5024"}\u306F${Y.maximum.toString()}${(_b2 = z8.unit) != null ? _b2 : "\u8981\u7D20"}${W}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5927\u304D\u3059\u304E\u308B\u5024: ${(_c = Y.origin) != null ? _c : "\u5024"}\u306F${Y.maximum.toString()}${W}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "too_small": {
        let W = Y.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044", z8 = X(Y.origin);
        if (z8) return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${Y.origin}\u306F${Y.minimum.toString()}${z8.unit}${W}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${Y.origin}\u306F${Y.minimum.toString()}${W}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${W.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        if (W.format === "ends_with") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${W.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        if (W.format === "includes") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${W.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        if (W.format === "regex") return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${W.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u7121\u52B9\u306A${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u52B9\u306A\u6570\u5024: ${Y.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      case "unrecognized_keys":
        return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${Y.keys.length > 1 ? "\u7FA4" : ""}: ${M(Y.keys, "\u3001")}`;
      case "invalid_key":
        return `${Y.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;
      case "invalid_union":
        return "\u7121\u52B9\u306A\u5165\u529B";
      case "invalid_element":
        return `${Y.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;
      default:
        return "\u7121\u52B9\u306A\u5165\u529B";
    }
  };
};
function $3() {
  return { localeError: tI() };
}
var aI = () => {
  let $ = { string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }, set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "\u1798\u17B7\u1793\u1798\u17C2\u1793\u1787\u17B6\u179B\u17C1\u1781 (NaN)" : "\u179B\u17C1\u1781";
      case "object": {
        if (Array.isArray(Y)) return "\u17A2\u17B6\u179A\u17C1 (Array)";
        if (Y === null) return "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B", email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B", url: "URL", emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO", date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO", time: "\u1798\u17C9\u17C4\u1784 ISO", duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO", ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4", cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6", base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64", base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url", json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON", e164: "\u179B\u17C1\u1781 E.164", jwt: "JWT", template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${Y.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${S(Y.values[0])}`;
        return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${(_a3 = Y.origin) != null ? _a3 : "\u178F\u1798\u17D2\u179B\u17C3"} ${W} ${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u1792\u17B6\u178F\u17BB"}`;
        return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${(_c = Y.origin) != null ? _c : "\u178F\u1798\u17D2\u179B\u17C3"} ${W} ${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${Y.origin} ${W} ${Y.minimum.toString()} ${z8.unit}`;
        return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${Y.origin} ${W} ${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${W.prefix}"`;
        if (W.format === "ends_with") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${W.suffix}"`;
        if (W.format === "includes") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${W.includes}"`;
        if (W.format === "regex") return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${W.pattern}`;
        return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${Y.divisor}`;
      case "unrecognized_keys":
        return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${Y.origin}`;
      case "invalid_union":
        return "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";
      case "invalid_element":
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${Y.origin}`;
      default:
        return "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C";
    }
  };
};
function X3() {
  return { localeError: aI() };
}
var sI = () => {
  let $ = { string: { unit: "\uBB38\uC790", verb: "to have" }, file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" }, array: { unit: "\uAC1C", verb: "to have" }, set: { unit: "\uAC1C", verb: "to have" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "number";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\uC785\uB825", email: "\uC774\uBA54\uC77C \uC8FC\uC18C", url: "URL", emoji: "\uC774\uBAA8\uC9C0", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04", date: "ISO \uB0A0\uC9DC", time: "ISO \uC2DC\uAC04", duration: "ISO \uAE30\uAC04", ipv4: "IPv4 \uC8FC\uC18C", ipv6: "IPv6 \uC8FC\uC18C", cidrv4: "IPv4 \uBC94\uC704", cidrv6: "IPv6 \uBC94\uC704", base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4", json_string: "JSON \uBB38\uC790\uC5F4", e164: "E.164 \uBC88\uD638", jwt: "JWT", template_literal: "\uC785\uB825" };
  return (Y) => {
    var _a3, _b2, _c, _d2, _e, _f, _g;
    switch (Y.code) {
      case "invalid_type":
        return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${Y.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${J(Y.input)}\uC785\uB2C8\uB2E4`;
      case "invalid_value":
        if (Y.values.length === 1) return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${S(Y.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;
        return `\uC798\uBABB\uB41C \uC635\uC158: ${M(Y.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "too_big": {
        let W = Y.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC", z8 = W === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4", G = X(Y.origin), U = (_a3 = G == null ? void 0 : G.unit) != null ? _a3 : "\uC694\uC18C";
        if (G) return `${(_b2 = Y.origin) != null ? _b2 : "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${Y.maximum.toString()}${U} ${W}${z8}`;
        return `${(_c = Y.origin) != null ? _c : "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${Y.maximum.toString()} ${W}${z8}`;
      }
      case "too_small": {
        let W = Y.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC", z8 = W === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4", G = X(Y.origin), U = (_d2 = G == null ? void 0 : G.unit) != null ? _d2 : "\uC694\uC18C";
        if (G) return `${(_e = Y.origin) != null ? _e : "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${Y.minimum.toString()}${U} ${W}${z8}`;
        return `${(_f = Y.origin) != null ? _f : "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${Y.minimum.toString()} ${W}${z8}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${W.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;
        if (W.format === "ends_with") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${W.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;
        if (W.format === "includes") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${W.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;
        if (W.format === "regex") return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${W.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;
        return `\uC798\uBABB\uB41C ${(_g = Q[W.format]) != null ? _g : Y.format}`;
      }
      case "not_multiple_of":
        return `\uC798\uBABB\uB41C \uC22B\uC790: ${Y.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "unrecognized_keys":
        return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\uC798\uBABB\uB41C \uD0A4: ${Y.origin}`;
      case "invalid_union":
        return "\uC798\uBABB\uB41C \uC785\uB825";
      case "invalid_element":
        return `\uC798\uBABB\uB41C \uAC12: ${Y.origin}`;
      default:
        return "\uC798\uBABB\uB41C \uC785\uB825";
    }
  };
};
function J3() {
  return { localeError: sI() };
}
var eI = () => {
  let $ = { string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }, set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u0431\u0440\u043E\u0458";
      case "object": {
        if (Array.isArray(Y)) return "\u043D\u0438\u0437\u0430";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0432\u043D\u0435\u0441", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430", url: "URL", emoji: "\u0435\u043C\u043E\u045F\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435", date: "ISO \u0434\u0430\u0442\u0443\u043C", time: "ISO \u0432\u0440\u0435\u043C\u0435", duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430", cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433", cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433", base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430", json_string: "JSON \u043D\u0438\u0437\u0430", e164: "E.164 \u0431\u0440\u043E\u0458", jwt: "JWT", template_literal: "\u0432\u043D\u0435\u0441" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${Y.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Invalid input: expected ${S(Y.values[0])}`;
        return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${(_a3 = Y.origin) != null ? _a3 : "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;
        return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${(_c = Y.origin) != null ? _c : "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${Y.origin} \u0434\u0430 \u0438\u043C\u0430 ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${Y.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${W.prefix}"`;
        if (W.format === "ends_with") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${W.suffix}"`;
        if (W.format === "includes") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${W.includes}"`;
        if (W.format === "regex") return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${W.pattern}`;
        return `Invalid ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${Y.divisor}`;
      case "unrecognized_keys":
        return `${Y.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${Y.origin}`;
      case "invalid_union":
        return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";
      case "invalid_element":
        return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${Y.origin}`;
      default:
        return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";
    }
  };
};
function Y3() {
  return { localeError: eI() };
}
var $b = () => {
  let $ = { string: { unit: "aksara", verb: "mempunyai" }, file: { unit: "bait", verb: "mempunyai" }, array: { unit: "elemen", verb: "mempunyai" }, set: { unit: "elemen", verb: "mempunyai" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "nombor";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "input", email: "alamat e-mel", 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: "tarikh masa ISO", date: "tarikh ISO", time: "masa ISO", duration: "tempoh ISO", ipv4: "alamat IPv4", ipv6: "alamat IPv6", cidrv4: "julat IPv4", cidrv6: "julat IPv6", base64: "string dikodkan base64", base64url: "string dikodkan base64url", json_string: "string JSON", e164: "nombor E.164", jwt: "JWT", template_literal: "input" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Input tidak sah: dijangka ${Y.expected}, diterima ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Input tidak sah: dijangka ${S(Y.values[0])}`;
        return `Pilihan tidak sah: dijangka salah satu daripada ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Terlalu besar: dijangka ${(_a3 = Y.origin) != null ? _a3 : "nilai"} ${z8.verb} ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elemen"}`;
        return `Terlalu besar: dijangka ${(_c = Y.origin) != null ? _c : "nilai"} adalah ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Terlalu kecil: dijangka ${Y.origin} ${z8.verb} ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `Terlalu kecil: dijangka ${Y.origin} adalah ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `String tidak sah: mesti bermula dengan "${W.prefix}"`;
        if (W.format === "ends_with") return `String tidak sah: mesti berakhir dengan "${W.suffix}"`;
        if (W.format === "includes") return `String tidak sah: mesti mengandungi "${W.includes}"`;
        if (W.format === "regex") return `String tidak sah: mesti sepadan dengan corak ${W.pattern}`;
        return `${(_d2 = Q[W.format]) != null ? _d2 : Y.format} tidak sah`;
      }
      case "not_multiple_of":
        return `Nombor tidak sah: perlu gandaan ${Y.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak sah dalam ${Y.origin}`;
      case "invalid_union":
        return "Input tidak sah";
      case "invalid_element":
        return `Nilai tidak sah dalam ${Y.origin}`;
      default:
        return "Input tidak sah";
    }
  };
};
function Q3() {
  return { localeError: $b() };
}
var Xb = () => {
  let $ = { string: { unit: "tekens" }, file: { unit: "bytes" }, array: { unit: "elementen" }, set: { unit: "elementen" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "getal";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "invoer", email: "emailadres", 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 datum en tijd", date: "ISO datum", time: "ISO tijd", duration: "ISO duur", ipv4: "IPv4-adres", ipv6: "IPv6-adres", cidrv4: "IPv4-bereik", cidrv6: "IPv6-bereik", base64: "base64-gecodeerde tekst", base64url: "base64 URL-gecodeerde tekst", json_string: "JSON string", e164: "E.164-nummer", jwt: "JWT", template_literal: "invoer" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Ongeldige invoer: verwacht ${Y.expected}, ontving ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Ongeldige invoer: verwacht ${S(Y.values[0])}`;
        return `Ongeldige optie: verwacht \xE9\xE9n van ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Te lang: verwacht dat ${(_a3 = Y.origin) != null ? _a3 : "waarde"} ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elementen"} bevat`;
        return `Te lang: verwacht dat ${(_c = Y.origin) != null ? _c : "waarde"} ${W}${Y.maximum.toString()} is`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Te kort: verwacht dat ${Y.origin} ${W}${Y.minimum.toString()} ${z8.unit} bevat`;
        return `Te kort: verwacht dat ${Y.origin} ${W}${Y.minimum.toString()} is`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Ongeldige tekst: moet met "${W.prefix}" beginnen`;
        if (W.format === "ends_with") return `Ongeldige tekst: moet op "${W.suffix}" eindigen`;
        if (W.format === "includes") return `Ongeldige tekst: moet "${W.includes}" bevatten`;
        if (W.format === "regex") return `Ongeldige tekst: moet overeenkomen met patroon ${W.pattern}`;
        return `Ongeldig: ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `Ongeldig getal: moet een veelvoud van ${Y.divisor} zijn`;
      case "unrecognized_keys":
        return `Onbekende key${Y.keys.length > 1 ? "s" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Ongeldige key in ${Y.origin}`;
      case "invalid_union":
        return "Ongeldige invoer";
      case "invalid_element":
        return `Ongeldige waarde in ${Y.origin}`;
      default:
        return "Ongeldige invoer";
    }
  };
};
function W3() {
  return { localeError: Xb() };
}
var Jb = () => {
  let $ = { string: { unit: "tegn", verb: "\xE5 ha" }, file: { unit: "bytes", verb: "\xE5 ha" }, array: { unit: "elementer", verb: "\xE5 inneholde" }, set: { unit: "elementer", verb: "\xE5 inneholde" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "tall";
      case "object": {
        if (Array.isArray(Y)) return "liste";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "input", email: "e-postadresse", 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 dato- og klokkeslett", date: "ISO-dato", time: "ISO-klokkeslett", duration: "ISO-varighet", ipv4: "IPv4-omr\xE5de", ipv6: "IPv6-omr\xE5de", cidrv4: "IPv4-spekter", cidrv6: "IPv6-spekter", base64: "base64-enkodet streng", base64url: "base64url-enkodet streng", json_string: "JSON-streng", e164: "E.164-nummer", jwt: "JWT", template_literal: "input" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Ugyldig input: forventet ${Y.expected}, fikk ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Ugyldig verdi: forventet ${S(Y.values[0])}`;
        return `Ugyldig valg: forventet en av ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `For stor(t): forventet ${(_a3 = Y.origin) != null ? _a3 : "value"} til \xE5 ha ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elementer"}`;
        return `For stor(t): forventet ${(_c = Y.origin) != null ? _c : "value"} til \xE5 ha ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `For lite(n): forventet ${Y.origin} til \xE5 ha ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `For lite(n): forventet ${Y.origin} til \xE5 ha ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Ugyldig streng: m\xE5 starte med "${W.prefix}"`;
        if (W.format === "ends_with") return `Ugyldig streng: m\xE5 ende med "${W.suffix}"`;
        if (W.format === "includes") return `Ugyldig streng: m\xE5 inneholde "${W.includes}"`;
        if (W.format === "regex") return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${W.pattern}`;
        return `Ugyldig ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${Y.divisor}`;
      case "unrecognized_keys":
        return `${Y.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8kkel i ${Y.origin}`;
      case "invalid_union":
        return "Ugyldig input";
      case "invalid_element":
        return `Ugyldig verdi i ${Y.origin}`;
      default:
        return "Ugyldig input";
    }
  };
};
function z3() {
  return { localeError: Jb() };
}
var Yb = () => {
  let $ = { string: { unit: "harf", verb: "olmal\u0131d\u0131r" }, file: { unit: "bayt", verb: "olmal\u0131d\u0131r" }, array: { unit: "unsur", verb: "olmal\u0131d\u0131r" }, set: { unit: "unsur", verb: "olmal\u0131d\u0131r" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "numara";
      case "object": {
        if (Array.isArray(Y)) return "saf";
        if (Y === null) return "gayb";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "giren", email: "epostag\xE2h", 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 heng\xE2m\u0131", date: "ISO tarihi", time: "ISO zaman\u0131", duration: "ISO m\xFCddeti", ipv4: "IPv4 ni\u015F\xE2n\u0131", ipv6: "IPv6 ni\u015F\xE2n\u0131", cidrv4: "IPv4 menzili", cidrv6: "IPv6 menzili", base64: "base64-\u015Fifreli metin", base64url: "base64url-\u015Fifreli metin", json_string: "JSON metin", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "giren" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `F\xE2sit giren: umulan ${Y.expected}, al\u0131nan ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `F\xE2sit giren: umulan ${S(Y.values[0])}`;
        return `F\xE2sit tercih: m\xFBteberler ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Fazla b\xFCy\xFCk: ${(_a3 = Y.origin) != null ? _a3 : "value"}, ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elements"} sahip olmal\u0131yd\u0131.`;
        return `Fazla b\xFCy\xFCk: ${(_c = Y.origin) != null ? _c : "value"}, ${W}${Y.maximum.toString()} olmal\u0131yd\u0131.`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Fazla k\xFC\xE7\xFCk: ${Y.origin}, ${W}${Y.minimum.toString()} ${z8.unit} sahip olmal\u0131yd\u0131.`;
        return `Fazla k\xFC\xE7\xFCk: ${Y.origin}, ${W}${Y.minimum.toString()} olmal\u0131yd\u0131.`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `F\xE2sit metin: "${W.prefix}" ile ba\u015Flamal\u0131.`;
        if (W.format === "ends_with") return `F\xE2sit metin: "${W.suffix}" ile bitmeli.`;
        if (W.format === "includes") return `F\xE2sit metin: "${W.includes}" ihtiv\xE2 etmeli.`;
        if (W.format === "regex") return `F\xE2sit metin: ${W.pattern} nak\u015F\u0131na uymal\u0131.`;
        return `F\xE2sit ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `F\xE2sit say\u0131: ${Y.divisor} kat\u0131 olmal\u0131yd\u0131.`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar ${Y.keys.length > 1 ? "s" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `${Y.origin} i\xE7in tan\u0131nmayan anahtar var.`;
      case "invalid_union":
        return "Giren tan\u0131namad\u0131.";
      case "invalid_element":
        return `${Y.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;
      default:
        return "K\u0131ymet tan\u0131namad\u0131.";
    }
  };
};
function G3() {
  return { localeError: Yb() };
}
var Qb = () => {
  let $ = { string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" }, array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }, set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u0639\u062F\u062F";
      case "object": {
        if (Array.isArray(Y)) return "\u0627\u0631\u06D0";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0648\u0631\u0648\u062F\u064A", email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9", url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A", date: "\u0646\u06D0\u067C\u0647", time: "\u0648\u062E\u062A", duration: "\u0645\u0648\u062F\u0647", ipv4: "\u062F IPv4 \u067E\u062A\u0647", ipv6: "\u062F IPv6 \u067E\u062A\u0647", cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647", cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647", base64: "base64-encoded \u0645\u062A\u0646", base64url: "base64url-encoded \u0645\u062A\u0646", json_string: "JSON \u0645\u062A\u0646", e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647", jwt: "JWT", template_literal: "\u0648\u0631\u0648\u062F\u064A" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${Y.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${J(Y.input)} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${S(Y.values[0])} \u0648\u0627\u06CC`;
        return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${M(Y.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${(_a3 = Y.origin) != null ? _a3 : "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;
        return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${(_c = Y.origin) != null ? _c : "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${W}${Y.maximum.toString()} \u0648\u064A`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${Y.origin} \u0628\u0627\u06CC\u062F ${W}${Y.minimum.toString()} ${z8.unit} \u0648\u0644\u0631\u064A`;
        return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${Y.origin} \u0628\u0627\u06CC\u062F ${W}${Y.minimum.toString()} \u0648\u064A`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${W.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;
        if (W.format === "ends_with") return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${W.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;
        if (W.format === "includes") return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${W.includes}" \u0648\u0644\u0631\u064A`;
        if (W.format === "regex") return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${W.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;
        return `${(_d2 = Q[W.format]) != null ? _d2 : Y.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;
      }
      case "not_multiple_of":
        return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${Y.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;
      case "unrecognized_keys":
        return `\u0646\u0627\u0633\u0645 ${Y.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${Y.origin} \u06A9\u06D0`;
      case "invalid_union":
        return "\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";
      case "invalid_element":
        return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${Y.origin} \u06A9\u06D0`;
      default:
        return "\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A";
    }
  };
};
function U3() {
  return { localeError: Qb() };
}
var Wb = () => {
  let $ = { string: { unit: "znak\xF3w", verb: "mie\u0107" }, file: { unit: "bajt\xF3w", verb: "mie\u0107" }, array: { unit: "element\xF3w", verb: "mie\u0107" }, set: { unit: "element\xF3w", verb: "mie\u0107" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "liczba";
      case "object": {
        if (Array.isArray(Y)) return "tablica";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "wyra\u017Cenie", email: "adres email", 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: "data i godzina w formacie ISO", date: "data w formacie ISO", time: "godzina w formacie ISO", duration: "czas trwania ISO", ipv4: "adres IPv4", ipv6: "adres IPv6", cidrv4: "zakres IPv4", cidrv6: "zakres IPv6", base64: "ci\u0105g znak\xF3w zakodowany w formacie base64", base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url", json_string: "ci\u0105g znak\xF3w w formacie JSON", e164: "liczba E.164", jwt: "JWT", template_literal: "wej\u015Bcie" };
  return (Y) => {
    var _a3, _b2, _c, _d2, _e, _f, _g;
    switch (Y.code) {
      case "invalid_type":
        return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${Y.expected}, otrzymano ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${S(Y.values[0])}`;
        return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${(_a3 = Y.origin) != null ? _a3 : "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "element\xF3w"}`;
        return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${(_c = Y.origin) != null ? _c : "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${(_d2 = Y.origin) != null ? _d2 : "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${W}${Y.minimum.toString()} ${(_e = z8.unit) != null ? _e : "element\xF3w"}`;
        return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${(_f = Y.origin) != null ? _f : "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${W.prefix}"`;
        if (W.format === "ends_with") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${W.suffix}"`;
        if (W.format === "includes") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${W.includes}"`;
        if (W.format === "regex") return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${W.pattern}`;
        return `Nieprawid\u0142ow(y/a/e) ${(_g = Q[W.format]) != null ? _g : Y.format}`;
      }
      case "not_multiple_of":
        return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${Y.divisor}`;
      case "unrecognized_keys":
        return `Nierozpoznane klucze${Y.keys.length > 1 ? "s" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Nieprawid\u0142owy klucz w ${Y.origin}`;
      case "invalid_union":
        return "Nieprawid\u0142owe dane wej\u015Bciowe";
      case "invalid_element":
        return `Nieprawid\u0142owa warto\u015B\u0107 w ${Y.origin}`;
      default:
        return "Nieprawid\u0142owe dane wej\u015Bciowe";
    }
  };
};
function H3() {
  return { localeError: Wb() };
}
var zb = () => {
  let $ = { string: { unit: "caracteres", verb: "ter" }, file: { unit: "bytes", verb: "ter" }, array: { unit: "itens", verb: "ter" }, set: { unit: "itens", verb: "ter" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "n\xFAmero";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "nulo";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "padr\xE3o", email: "endere\xE7o de e-mail", 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: "data e hora ISO", date: "data ISO", time: "hora ISO", duration: "dura\xE7\xE3o ISO", ipv4: "endere\xE7o IPv4", ipv6: "endere\xE7o IPv6", cidrv4: "faixa de IPv4", cidrv6: "faixa de IPv6", base64: "texto codificado em base64", base64url: "URL codificada em base64", json_string: "texto JSON", e164: "n\xFAmero E.164", jwt: "JWT", template_literal: "entrada" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Tipo inv\xE1lido: esperado ${Y.expected}, recebido ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Entrada inv\xE1lida: esperado ${S(Y.values[0])}`;
        return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Muito grande: esperado que ${(_a3 = Y.origin) != null ? _a3 : "valor"} tivesse ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elementos"}`;
        return `Muito grande: esperado que ${(_c = Y.origin) != null ? _c : "valor"} fosse ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Muito pequeno: esperado que ${Y.origin} tivesse ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `Muito pequeno: esperado que ${Y.origin} fosse ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Texto inv\xE1lido: deve come\xE7ar com "${W.prefix}"`;
        if (W.format === "ends_with") return `Texto inv\xE1lido: deve terminar com "${W.suffix}"`;
        if (W.format === "includes") return `Texto inv\xE1lido: deve incluir "${W.includes}"`;
        if (W.format === "regex") return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${W.pattern}`;
        return `${(_d2 = Q[W.format]) != null ? _d2 : Y.format} inv\xE1lido`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${Y.divisor}`;
      case "unrecognized_keys":
        return `Chave${Y.keys.length > 1 ? "s" : ""} desconhecida${Y.keys.length > 1 ? "s" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Chave inv\xE1lida em ${Y.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido em ${Y.origin}`;
      default:
        return "Campo inv\xE1lido";
    }
  };
};
function K3() {
  return { localeError: zb() };
}
function BN($, X, J, Q) {
  let Y = Math.abs($), W = Y % 10, z8 = Y % 100;
  if (z8 >= 11 && z8 <= 19) return Q;
  if (W === 1) return X;
  if (W >= 2 && W <= 4) return J;
  return Q;
}
var Gb = () => {
  let $ = { string: { unit: { one: "\u0441\u0438\u043C\u0432\u043E\u043B", few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, file: { unit: { one: "\u0431\u0430\u0439\u0442", few: "\u0431\u0430\u0439\u0442\u0430", many: "\u0431\u0430\u0439\u0442" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, array: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" }, set: { unit: { one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442", few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430", many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432" }, verb: "\u0438\u043C\u0435\u0442\u044C" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E";
      case "object": {
        if (Array.isArray(Y)) return "\u043C\u0430\u0441\u0441\u0438\u0432";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0432\u0432\u043E\u0434", email: "email \u0430\u0434\u0440\u0435\u0441", url: "URL", emoji: "\u044D\u043C\u043E\u0434\u0437\u0438", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F", date: "ISO \u0434\u0430\u0442\u0430", time: "ISO \u0432\u0440\u0435\u043C\u044F", duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C", ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441", ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441", cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D", base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64", base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url", json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0432\u043E\u0434" };
  return (Y) => {
    var _a3, _b2, _c;
    switch (Y.code) {
      case "invalid_type":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${Y.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${S(Y.values[0])}`;
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) {
          let G = Number(Y.maximum), U = BN(G, z8.unit.one, z8.unit.few, z8.unit.many);
          return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${(_a3 = Y.origin) != null ? _a3 : "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${W}${Y.maximum.toString()} ${U}`;
        }
        return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${(_b2 = Y.origin) != null ? _b2 : "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) {
          let G = Number(Y.minimum), U = BN(G, z8.unit.one, z8.unit.few, z8.unit.many);
          return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${Y.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${W}${Y.minimum.toString()} ${U}`;
        }
        return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${Y.origin} \u0431\u0443\u0434\u0435\u0442 ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${W.prefix}"`;
        if (W.format === "ends_with") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${W.suffix}"`;
        if (W.format === "includes") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${W.includes}"`;
        if (W.format === "regex") return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${W.pattern}`;
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${(_c = Q[W.format]) != null ? _c : Y.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${Y.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${Y.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${Y.keys.length > 1 ? "\u0438" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${Y.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";
      case "invalid_element":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${Y.origin}`;
      default:
        return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";
    }
  };
};
function V3() {
  return { localeError: Gb() };
}
var Ub = () => {
  let $ = { string: { unit: "znakov", verb: "imeti" }, file: { unit: "bajtov", verb: "imeti" }, array: { unit: "elementov", verb: "imeti" }, set: { unit: "elementov", verb: "imeti" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u0161tevilo";
      case "object": {
        if (Array.isArray(Y)) return "tabela";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "vnos", email: "e-po\u0161tni naslov", 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 datum in \u010Das", date: "ISO datum", time: "ISO \u010Das", duration: "ISO trajanje", ipv4: "IPv4 naslov", ipv6: "IPv6 naslov", cidrv4: "obseg IPv4", cidrv6: "obseg IPv6", base64: "base64 kodiran niz", base64url: "base64url kodiran niz", json_string: "JSON niz", e164: "E.164 \u0161tevilka", jwt: "JWT", template_literal: "vnos" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `Neveljaven vnos: pri\u010Dakovano ${Y.expected}, prejeto ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Neveljaven vnos: pri\u010Dakovano ${S(Y.values[0])}`;
        return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Preveliko: pri\u010Dakovano, da bo ${(_a3 = Y.origin) != null ? _a3 : "vrednost"} imelo ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "elementov"}`;
        return `Preveliko: pri\u010Dakovano, da bo ${(_c = Y.origin) != null ? _c : "vrednost"} ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Premajhno: pri\u010Dakovano, da bo ${Y.origin} imelo ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `Premajhno: pri\u010Dakovano, da bo ${Y.origin} ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Neveljaven niz: mora se za\u010Deti z "${W.prefix}"`;
        if (W.format === "ends_with") return `Neveljaven niz: mora se kon\u010Dati z "${W.suffix}"`;
        if (W.format === "includes") return `Neveljaven niz: mora vsebovati "${W.includes}"`;
        if (W.format === "regex") return `Neveljaven niz: mora ustrezati vzorcu ${W.pattern}`;
        return `Neveljaven ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${Y.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznan${Y.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Neveljaven klju\u010D v ${Y.origin}`;
      case "invalid_union":
        return "Neveljaven vnos";
      case "invalid_element":
        return `Neveljavna vrednost v ${Y.origin}`;
      default:
        return "Neveljaven vnos";
    }
  };
};
function N3() {
  return { localeError: Ub() };
}
var Hb = () => {
  let $ = { string: { unit: "tecken", verb: "att ha" }, file: { unit: "bytes", verb: "att ha" }, array: { unit: "objekt", verb: "att inneh\xE5lla" }, set: { unit: "objekt", verb: "att inneh\xE5lla" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "antal";
      case "object": {
        if (Array.isArray(Y)) return "lista";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "regulj\xE4rt uttryck", email: "e-postadress", 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-datum och tid", date: "ISO-datum", time: "ISO-tid", duration: "ISO-varaktighet", ipv4: "IPv4-intervall", ipv6: "IPv6-intervall", cidrv4: "IPv4-spektrum", cidrv6: "IPv6-spektrum", base64: "base64-kodad str\xE4ng", base64url: "base64url-kodad str\xE4ng", json_string: "JSON-str\xE4ng", e164: "E.164-nummer", jwt: "JWT", template_literal: "mall-literal" };
  return (Y) => {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h;
    switch (Y.code) {
      case "invalid_type":
        return `Ogiltig inmatning: f\xF6rv\xE4ntat ${Y.expected}, fick ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `Ogiltig inmatning: f\xF6rv\xE4ntat ${S(Y.values[0])}`;
        return `Ogiltigt val: f\xF6rv\xE4ntade en av ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `F\xF6r stor(t): f\xF6rv\xE4ntade ${(_a3 = Y.origin) != null ? _a3 : "v\xE4rdet"} att ha ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "element"}`;
        return `F\xF6r stor(t): f\xF6rv\xE4ntat ${(_c = Y.origin) != null ? _c : "v\xE4rdet"} att ha ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `F\xF6r lite(t): f\xF6rv\xE4ntade ${(_d2 = Y.origin) != null ? _d2 : "v\xE4rdet"} att ha ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `F\xF6r lite(t): f\xF6rv\xE4ntade ${(_e = Y.origin) != null ? _e : "v\xE4rdet"} att ha ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${W.prefix}"`;
        if (W.format === "ends_with") return `Ogiltig str\xE4ng: m\xE5ste sluta med "${W.suffix}"`;
        if (W.format === "includes") return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${W.includes}"`;
        if (W.format === "regex") return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${W.pattern}"`;
        return `Ogiltig(t) ${(_f = Q[W.format]) != null ? _f : Y.format}`;
      }
      case "not_multiple_of":
        return `Ogiltigt tal: m\xE5ste vara en multipel av ${Y.divisor}`;
      case "unrecognized_keys":
        return `${Y.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Ogiltig nyckel i ${(_g = Y.origin) != null ? _g : "v\xE4rdet"}`;
      case "invalid_union":
        return "Ogiltig input";
      case "invalid_element":
        return `Ogiltigt v\xE4rde i ${(_h = Y.origin) != null ? _h : "v\xE4rdet"}`;
      default:
        return "Ogiltig input";
    }
  };
};
function O3() {
  return { localeError: Hb() };
}
var Kb = () => {
  let $ = { string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }, set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "\u0B8E\u0BA3\u0BCD \u0B85\u0BB2\u0BCD\u0BB2\u0BBE\u0BA4\u0BA4\u0BC1" : "\u0B8E\u0BA3\u0BCD";
      case "object": {
        if (Array.isArray(Y)) return "\u0B85\u0BA3\u0BBF";
        if (Y === null) return "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1", email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", 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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF", time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD", duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1", ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF", cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1", base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD", base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD", json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD", e164: "E.164 \u0B8E\u0BA3\u0BCD", jwt: "JWT", template_literal: "input" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Y.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${S(Y.values[0])}`;
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${M(Y.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${(_a3 = Y.origin) != null ? _a3 : "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${(_c = Y.origin) != null ? _c : "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${W}${Y.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Y.origin} ${W}${Y.minimum.toString()} ${z8.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${Y.origin} ${W}${Y.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${W.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (W.format === "ends_with") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${W.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (W.format === "includes") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${W.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (W.format === "regex") return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${W.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${Y.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      case "unrecognized_keys":
        return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${Y.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `${Y.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;
      case "invalid_union":
        return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";
      case "invalid_element":
        return `${Y.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;
      default:
        return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";
    }
  };
};
function w3() {
  return { localeError: Kb() };
}
var Vb = () => {
  let $ = { string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }, set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "\u0E44\u0E21\u0E48\u0E43\u0E0A\u0E48\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02 (NaN)" : "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02";
      case "object": {
        if (Array.isArray(Y)) return "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)";
        if (Y === null) return "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19", email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25", url: "URL", emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO", time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO", ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4", ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6", cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4", cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6", base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64", base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL", json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON", e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)", jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT", template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${Y.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${S(Y.values[0])}`;
        return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32", z8 = X(Y.origin);
        if (z8) return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${(_a3 = Y.origin) != null ? _a3 : "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${W} ${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
        return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${(_c = Y.origin) != null ? _c : "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${W} ${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32", z8 = X(Y.origin);
        if (z8) return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${Y.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${W} ${Y.minimum.toString()} ${z8.unit}`;
        return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${Y.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${W} ${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${W.prefix}"`;
        if (W.format === "ends_with") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${W.suffix}"`;
        if (W.format === "includes") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${W.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;
        if (W.format === "regex") return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${W.pattern}`;
        return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${Y.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;
      case "unrecognized_keys":
        return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${Y.origin}`;
      case "invalid_union":
        return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";
      case "invalid_element":
        return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${Y.origin}`;
      default:
        return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07";
    }
  };
};
function B3() {
  return { localeError: Vb() };
}
var Nb = ($) => {
  let X = typeof $;
  switch (X) {
    case "number":
      return Number.isNaN($) ? "NaN" : "number";
    case "object": {
      if (Array.isArray($)) return "array";
      if ($ === null) return "null";
      if (Object.getPrototypeOf($) !== Object.prototype && $.constructor) return $.constructor.name;
    }
  }
  return X;
};
var Ob = () => {
  let $ = { string: { unit: "karakter", verb: "olmal\u0131" }, file: { unit: "bayt", verb: "olmal\u0131" }, array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }, set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" } };
  function X(Q) {
    var _a3;
    return (_a3 = $[Q]) != null ? _a3 : null;
  }
  let J = { regex: "girdi", email: "e-posta adresi", 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 tarih ve saat", date: "ISO tarih", time: "ISO saat", duration: "ISO s\xFCre", ipv4: "IPv4 adresi", ipv6: "IPv6 adresi", cidrv4: "IPv4 aral\u0131\u011F\u0131", cidrv6: "IPv6 aral\u0131\u011F\u0131", base64: "base64 ile \u015Fifrelenmi\u015F metin", base64url: "base64url ile \u015Fifrelenmi\u015F metin", json_string: "JSON dizesi", e164: "E.164 say\u0131s\u0131", jwt: "JWT", template_literal: "\u015Eablon dizesi" };
  return (Q) => {
    var _a3, _b2, _c, _d2;
    switch (Q.code) {
      case "invalid_type":
        return `Ge\xE7ersiz de\u011Fer: beklenen ${Q.expected}, al\u0131nan ${Nb(Q.input)}`;
      case "invalid_value":
        if (Q.values.length === 1) return `Ge\xE7ersiz de\u011Fer: beklenen ${S(Q.values[0])}`;
        return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${M(Q.values, "|")}`;
      case "too_big": {
        let Y = Q.inclusive ? "<=" : "<", W = X(Q.origin);
        if (W) return `\xC7ok b\xFCy\xFCk: beklenen ${(_a3 = Q.origin) != null ? _a3 : "de\u011Fer"} ${Y}${Q.maximum.toString()} ${(_b2 = W.unit) != null ? _b2 : "\xF6\u011Fe"}`;
        return `\xC7ok b\xFCy\xFCk: beklenen ${(_c = Q.origin) != null ? _c : "de\u011Fer"} ${Y}${Q.maximum.toString()}`;
      }
      case "too_small": {
        let Y = Q.inclusive ? ">=" : ">", W = X(Q.origin);
        if (W) return `\xC7ok k\xFC\xE7\xFCk: beklenen ${Q.origin} ${Y}${Q.minimum.toString()} ${W.unit}`;
        return `\xC7ok k\xFC\xE7\xFCk: beklenen ${Q.origin} ${Y}${Q.minimum.toString()}`;
      }
      case "invalid_format": {
        let Y = Q;
        if (Y.format === "starts_with") return `Ge\xE7ersiz metin: "${Y.prefix}" ile ba\u015Flamal\u0131`;
        if (Y.format === "ends_with") return `Ge\xE7ersiz metin: "${Y.suffix}" ile bitmeli`;
        if (Y.format === "includes") return `Ge\xE7ersiz metin: "${Y.includes}" i\xE7ermeli`;
        if (Y.format === "regex") return `Ge\xE7ersiz metin: ${Y.pattern} desenine uymal\u0131`;
        return `Ge\xE7ersiz ${(_d2 = J[Y.format]) != null ? _d2 : Q.format}`;
      }
      case "not_multiple_of":
        return `Ge\xE7ersiz say\u0131: ${Q.divisor} ile tam b\xF6l\xFCnebilmeli`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar${Q.keys.length > 1 ? "lar" : ""}: ${M(Q.keys, ", ")}`;
      case "invalid_key":
        return `${Q.origin} i\xE7inde ge\xE7ersiz anahtar`;
      case "invalid_union":
        return "Ge\xE7ersiz de\u011Fer";
      case "invalid_element":
        return `${Q.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;
      default:
        return "Ge\xE7ersiz de\u011Fer";
    }
  };
};
function q3() {
  return { localeError: Ob() };
}
var wb = () => {
  let $ = { string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }, set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u0447\u0438\u0441\u043B\u043E";
      case "object": {
        if (Array.isArray(Y)) return "\u043C\u0430\u0441\u0438\u0432";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456", email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438", url: "URL", emoji: "\u0435\u043C\u043E\u0434\u0437\u0456", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO", date: "\u0434\u0430\u0442\u0430 ISO", time: "\u0447\u0430\u0441 ISO", duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO", ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4", ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6", cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4", cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6", base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64", base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url", json_string: "\u0440\u044F\u0434\u043E\u043A JSON", e164: "\u043D\u043E\u043C\u0435\u0440 E.164", jwt: "JWT", template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${Y.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${S(Y.values[0])}`;
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${(_a3 = Y.origin) != null ? _a3 : "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${z8.verb} ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${(_c = Y.origin) != null ? _c : "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${Y.origin} ${z8.verb} ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${Y.origin} \u0431\u0443\u0434\u0435 ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${W.prefix}"`;
        if (W.format === "ends_with") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${W.suffix}"`;
        if (W.format === "includes") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${W.includes}"`;
        if (W.format === "regex") return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${W.pattern}`;
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${Y.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${Y.keys.length > 1 ? "\u0456" : ""}: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${Y.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";
      case "invalid_element":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${Y.origin}`;
      default:
        return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";
    }
  };
};
function L3() {
  return { localeError: wb() };
}
var Bb = () => {
  let $ = { string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" }, file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" }, array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }, set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "\u0646\u0645\u0628\u0631";
      case "object": {
        if (Array.isArray(Y)) return "\u0622\u0631\u06D2";
        if (Y === null) return "\u0646\u0644";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0627\u0646 \u067E\u0679", email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633", url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644", emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC", uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4", uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6", nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC", guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2", ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC", xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC", ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC", datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645", date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E", time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A", duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A", ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633", ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633", cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C", cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C", base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF", json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF", e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631", jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC", template_literal: "\u0627\u0646 \u067E\u0679" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${Y.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${J(Y.input)} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${S(Y.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
        return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${M(Y.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${(_a3 = Y.origin) != null ? _a3 : "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
        return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${(_c = Y.origin) != null ? _c : "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${W}${Y.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${Y.origin} \u06A9\u06D2 ${W}${Y.minimum.toString()} ${z8.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
        return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${Y.origin} \u06A9\u0627 ${W}${Y.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${W.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        if (W.format === "ends_with") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${W.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        if (W.format === "includes") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${W.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        if (W.format === "regex") return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${W.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        return `\u063A\u0644\u0637 ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${Y.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
      case "unrecognized_keys":
        return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${Y.keys.length > 1 ? "\u0632" : ""}: ${M(Y.keys, "\u060C ")}`;
      case "invalid_key":
        return `${Y.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
      case "invalid_union":
        return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
      case "invalid_element":
        return `${Y.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;
      default:
        return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
    }
  };
};
function D3() {
  return { localeError: Bb() };
}
var qb = () => {
  let $ = { string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" }, file: { unit: "byte", verb: "c\xF3" }, array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }, set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "s\u1ED1";
      case "object": {
        if (Array.isArray(Y)) return "m\u1EA3ng";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u0111\u1EA7u v\xE0o", email: "\u0111\u1ECBa ch\u1EC9 email", 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: "ng\xE0y gi\u1EDD ISO", date: "ng\xE0y ISO", time: "gi\u1EDD ISO", duration: "kho\u1EA3ng th\u1EDDi gian ISO", ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4", ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6", cidrv4: "d\u1EA3i IPv4", cidrv6: "d\u1EA3i IPv6", base64: "chu\u1ED7i m\xE3 h\xF3a base64", base64url: "chu\u1ED7i m\xE3 h\xF3a base64url", json_string: "chu\u1ED7i JSON", e164: "s\u1ED1 E.164", jwt: "JWT", template_literal: "\u0111\u1EA7u v\xE0o" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${Y.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${S(Y.values[0])}`;
        return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${(_a3 = Y.origin) != null ? _a3 : "gi\xE1 tr\u1ECB"} ${z8.verb} ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "ph\u1EA7n t\u1EED"}`;
        return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${(_c = Y.origin) != null ? _c : "gi\xE1 tr\u1ECB"} ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${Y.origin} ${z8.verb} ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${Y.origin} ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${W.prefix}"`;
        if (W.format === "ends_with") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${W.suffix}"`;
        if (W.format === "includes") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${W.includes}"`;
        if (W.format === "regex") return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${W.pattern}`;
        return `${(_d2 = Q[W.format]) != null ? _d2 : Y.format} kh\xF4ng h\u1EE3p l\u1EC7`;
      }
      case "not_multiple_of":
        return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${Y.divisor}`;
      case "unrecognized_keys":
        return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${Y.origin}`;
      case "invalid_union":
        return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";
      case "invalid_element":
        return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${Y.origin}`;
      default:
        return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";
    }
  };
};
function j3() {
  return { localeError: qb() };
}
var Lb = () => {
  let $ = { string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" }, file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" }, array: { unit: "\u9879", verb: "\u5305\u542B" }, set: { unit: "\u9879", verb: "\u5305\u542B" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "\u975E\u6570\u5B57(NaN)" : "\u6570\u5B57";
      case "object": {
        if (Array.isArray(Y)) return "\u6570\u7EC4";
        if (Y === null) return "\u7A7A\u503C(null)";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u8F93\u5165", email: "\u7535\u5B50\u90AE\u4EF6", url: "URL", emoji: "\u8868\u60C5\u7B26\u53F7", uuid: "UUID", uuidv4: "UUIDv4", uuidv6: "UUIDv6", nanoid: "nanoid", guid: "GUID", cuid: "cuid", cuid2: "cuid2", ulid: "ULID", xid: "XID", ksuid: "KSUID", datetime: "ISO\u65E5\u671F\u65F6\u95F4", date: "ISO\u65E5\u671F", time: "ISO\u65F6\u95F4", duration: "ISO\u65F6\u957F", ipv4: "IPv4\u5730\u5740", ipv6: "IPv6\u5730\u5740", cidrv4: "IPv4\u7F51\u6BB5", cidrv6: "IPv6\u7F51\u6BB5", base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32", base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32", json_string: "JSON\u5B57\u7B26\u4E32", e164: "E.164\u53F7\u7801", jwt: "JWT", template_literal: "\u8F93\u5165" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${Y.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${S(Y.values[0])}`;
        return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${(_a3 = Y.origin) != null ? _a3 : "\u503C"} ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u4E2A\u5143\u7D20"}`;
        return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${(_c = Y.origin) != null ? _c : "\u503C"} ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${Y.origin} ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${Y.origin} ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${W.prefix}" \u5F00\u5934`;
        if (W.format === "ends_with") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${W.suffix}" \u7ED3\u5C3E`;
        if (W.format === "includes") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${W.includes}"`;
        if (W.format === "regex") return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${W.pattern}`;
        return `\u65E0\u6548${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${Y.divisor} \u7684\u500D\u6570`;
      case "unrecognized_keys":
        return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${M(Y.keys, ", ")}`;
      case "invalid_key":
        return `${Y.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;
      case "invalid_union":
        return "\u65E0\u6548\u8F93\u5165";
      case "invalid_element":
        return `${Y.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;
      default:
        return "\u65E0\u6548\u8F93\u5165";
    }
  };
};
function F3() {
  return { localeError: Lb() };
}
var Db = () => {
  let $ = { string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" }, file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" }, array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }, set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" } };
  function X(Y) {
    var _a3;
    return (_a3 = $[Y]) != null ? _a3 : null;
  }
  let J = (Y) => {
    let W = typeof Y;
    switch (W) {
      case "number":
        return Number.isNaN(Y) ? "NaN" : "number";
      case "object": {
        if (Array.isArray(Y)) return "array";
        if (Y === null) return "null";
        if (Object.getPrototypeOf(Y) !== Object.prototype && Y.constructor) return Y.constructor.name;
      }
    }
    return W;
  }, Q = { regex: "\u8F38\u5165", email: "\u90F5\u4EF6\u5730\u5740", 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 \u65E5\u671F\u6642\u9593", date: "ISO \u65E5\u671F", time: "ISO \u6642\u9593", duration: "ISO \u671F\u9593", ipv4: "IPv4 \u4F4D\u5740", ipv6: "IPv6 \u4F4D\u5740", cidrv4: "IPv4 \u7BC4\u570D", cidrv6: "IPv6 \u7BC4\u570D", base64: "base64 \u7DE8\u78BC\u5B57\u4E32", base64url: "base64url \u7DE8\u78BC\u5B57\u4E32", json_string: "JSON \u5B57\u4E32", e164: "E.164 \u6578\u503C", jwt: "JWT", template_literal: "\u8F38\u5165" };
  return (Y) => {
    var _a3, _b2, _c, _d2;
    switch (Y.code) {
      case "invalid_type":
        return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${Y.expected}\uFF0C\u4F46\u6536\u5230 ${J(Y.input)}`;
      case "invalid_value":
        if (Y.values.length === 1) return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${S(Y.values[0])}`;
        return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${M(Y.values, "|")}`;
      case "too_big": {
        let W = Y.inclusive ? "<=" : "<", z8 = X(Y.origin);
        if (z8) return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${(_a3 = Y.origin) != null ? _a3 : "\u503C"} \u61C9\u70BA ${W}${Y.maximum.toString()} ${(_b2 = z8.unit) != null ? _b2 : "\u500B\u5143\u7D20"}`;
        return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${(_c = Y.origin) != null ? _c : "\u503C"} \u61C9\u70BA ${W}${Y.maximum.toString()}`;
      }
      case "too_small": {
        let W = Y.inclusive ? ">=" : ">", z8 = X(Y.origin);
        if (z8) return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${Y.origin} \u61C9\u70BA ${W}${Y.minimum.toString()} ${z8.unit}`;
        return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${Y.origin} \u61C9\u70BA ${W}${Y.minimum.toString()}`;
      }
      case "invalid_format": {
        let W = Y;
        if (W.format === "starts_with") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${W.prefix}" \u958B\u982D`;
        if (W.format === "ends_with") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${W.suffix}" \u7D50\u5C3E`;
        if (W.format === "includes") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${W.includes}"`;
        if (W.format === "regex") return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${W.pattern}`;
        return `\u7121\u6548\u7684 ${(_d2 = Q[W.format]) != null ? _d2 : Y.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${Y.divisor} \u7684\u500D\u6578`;
      case "unrecognized_keys":
        return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${Y.keys.length > 1 ? "\u5011" : ""}\uFF1A${M(Y.keys, "\u3001")}`;
      case "invalid_key":
        return `${Y.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
      case "invalid_union":
        return "\u7121\u6548\u7684\u8F38\u5165\u503C";
      case "invalid_element":
        return `${Y.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;
      default:
        return "\u7121\u6548\u7684\u8F38\u5165\u503C";
    }
  };
};
function M3() {
  return { localeError: Db() };
}
var L7 = /* @__PURE__ */ Symbol("ZodOutput");
var D7 = /* @__PURE__ */ Symbol("ZodInput");
var fX = class {
  constructor() {
    this._map = /* @__PURE__ */ new WeakMap(), this._idmap = /* @__PURE__ */ new Map();
  }
  add($, ...X) {
    let J = X[0];
    if (this._map.set($, J), J && typeof J === "object" && "id" in J) {
      if (this._idmap.has(J.id)) throw Error(`ID ${J.id} already exists in the registry`);
      this._idmap.set(J.id, $);
    }
    return this;
  }
  remove($) {
    return this._map.delete($), this;
  }
  get($) {
    var _a3;
    let X = $._zod.parent;
    if (X) {
      let J = { ...(_a3 = this.get(X)) != null ? _a3 : {} };
      return delete J.id, { ...J, ...this._map.get($) };
    }
    return this._map.get($);
  }
  has($) {
    return this._map.has($);
  }
};
function gX() {
  return new fX();
}
var G6 = gX();
function j7($, X) {
  return new $({ type: "string", ...P(X) });
}
function A3($, X) {
  return new $({ type: "string", coerce: true, ...P(X) });
}
function hX($, X) {
  return new $({ type: "string", format: "email", check: "string_format", abort: false, ...P(X) });
}
function x0($, X) {
  return new $({ type: "string", format: "guid", check: "string_format", abort: false, ...P(X) });
}
function uX($, X) {
  return new $({ type: "string", format: "uuid", check: "string_format", abort: false, ...P(X) });
}
function mX($, X) {
  return new $({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v4", ...P(X) });
}
function lX($, X) {
  return new $({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v6", ...P(X) });
}
function cX($, X) {
  return new $({ type: "string", format: "uuid", check: "string_format", abort: false, version: "v7", ...P(X) });
}
function pX($, X) {
  return new $({ type: "string", format: "url", check: "string_format", abort: false, ...P(X) });
}
function dX($, X) {
  return new $({ type: "string", format: "emoji", check: "string_format", abort: false, ...P(X) });
}
function iX($, X) {
  return new $({ type: "string", format: "nanoid", check: "string_format", abort: false, ...P(X) });
}
function nX($, X) {
  return new $({ type: "string", format: "cuid", check: "string_format", abort: false, ...P(X) });
}
function rX($, X) {
  return new $({ type: "string", format: "cuid2", check: "string_format", abort: false, ...P(X) });
}
function oX($, X) {
  return new $({ type: "string", format: "ulid", check: "string_format", abort: false, ...P(X) });
}
function tX($, X) {
  return new $({ type: "string", format: "xid", check: "string_format", abort: false, ...P(X) });
}
function aX($, X) {
  return new $({ type: "string", format: "ksuid", check: "string_format", abort: false, ...P(X) });
}
function sX($, X) {
  return new $({ type: "string", format: "ipv4", check: "string_format", abort: false, ...P(X) });
}
function eX($, X) {
  return new $({ type: "string", format: "ipv6", check: "string_format", abort: false, ...P(X) });
}
function $9($, X) {
  return new $({ type: "string", format: "cidrv4", check: "string_format", abort: false, ...P(X) });
}
function X9($, X) {
  return new $({ type: "string", format: "cidrv6", check: "string_format", abort: false, ...P(X) });
}
function J9($, X) {
  return new $({ type: "string", format: "base64", check: "string_format", abort: false, ...P(X) });
}
function Y9($, X) {
  return new $({ type: "string", format: "base64url", check: "string_format", abort: false, ...P(X) });
}
function Q9($, X) {
  return new $({ type: "string", format: "e164", check: "string_format", abort: false, ...P(X) });
}
function W9($, X) {
  return new $({ type: "string", format: "jwt", check: "string_format", abort: false, ...P(X) });
}
var F7 = { Any: null, Minute: -1, Second: 0, Millisecond: 3, Microsecond: 6 };
function I3($, X) {
  return new $({ type: "string", format: "datetime", check: "string_format", offset: false, local: false, precision: null, ...P(X) });
}
function b3($, X) {
  return new $({ type: "string", format: "date", check: "string_format", ...P(X) });
}
function Z3($, X) {
  return new $({ type: "string", format: "time", check: "string_format", precision: null, ...P(X) });
}
function P3($, X) {
  return new $({ type: "string", format: "duration", check: "string_format", ...P(X) });
}
function M7($, X) {
  return new $({ type: "number", checks: [], ...P(X) });
}
function R3($, X) {
  return new $({ type: "number", coerce: true, checks: [], ...P(X) });
}
function A7($, X) {
  return new $({ type: "number", check: "number_format", abort: false, format: "safeint", ...P(X) });
}
function I7($, X) {
  return new $({ type: "number", check: "number_format", abort: false, format: "float32", ...P(X) });
}
function b7($, X) {
  return new $({ type: "number", check: "number_format", abort: false, format: "float64", ...P(X) });
}
function Z7($, X) {
  return new $({ type: "number", check: "number_format", abort: false, format: "int32", ...P(X) });
}
function P7($, X) {
  return new $({ type: "number", check: "number_format", abort: false, format: "uint32", ...P(X) });
}
function R7($, X) {
  return new $({ type: "boolean", ...P(X) });
}
function E3($, X) {
  return new $({ type: "boolean", coerce: true, ...P(X) });
}
function E7($, X) {
  return new $({ type: "bigint", ...P(X) });
}
function S3($, X) {
  return new $({ type: "bigint", coerce: true, ...P(X) });
}
function S7($, X) {
  return new $({ type: "bigint", check: "bigint_format", abort: false, format: "int64", ...P(X) });
}
function v7($, X) {
  return new $({ type: "bigint", check: "bigint_format", abort: false, format: "uint64", ...P(X) });
}
function C7($, X) {
  return new $({ type: "symbol", ...P(X) });
}
function k7($, X) {
  return new $({ type: "undefined", ...P(X) });
}
function _7($, X) {
  return new $({ type: "null", ...P(X) });
}
function x7($) {
  return new $({ type: "any" });
}
function k1($) {
  return new $({ type: "unknown" });
}
function T7($, X) {
  return new $({ type: "never", ...P(X) });
}
function y7($, X) {
  return new $({ type: "void", ...P(X) });
}
function f7($, X) {
  return new $({ type: "date", ...P(X) });
}
function v3($, X) {
  return new $({ type: "date", coerce: true, ...P(X) });
}
function g7($, X) {
  return new $({ type: "nan", ...P(X) });
}
function j4($, X) {
  return new qY({ check: "less_than", ...P(X), value: $, inclusive: false });
}
function b6($, X) {
  return new qY({ check: "less_than", ...P(X), value: $, inclusive: true });
}
function F4($, X) {
  return new LY({ check: "greater_than", ...P(X), value: $, inclusive: false });
}
function U6($, X) {
  return new LY({ check: "greater_than", ...P(X), value: $, inclusive: true });
}
function C3($) {
  return F4(0, $);
}
function k3($) {
  return j4(0, $);
}
function _3($) {
  return b6(0, $);
}
function x3($) {
  return U6(0, $);
}
function _1($, X) {
  return new Oz({ check: "multiple_of", ...P(X), value: $ });
}
function T0($, X) {
  return new qz({ check: "max_size", ...P(X), maximum: $ });
}
function x1($, X) {
  return new Lz({ check: "min_size", ...P(X), minimum: $ });
}
function z9($, X) {
  return new Dz({ check: "size_equals", ...P(X), size: $ });
}
function y0($, X) {
  return new jz({ check: "max_length", ...P(X), maximum: $ });
}
function n4($, X) {
  return new Fz({ check: "min_length", ...P(X), minimum: $ });
}
function f0($, X) {
  return new Mz({ check: "length_equals", ...P(X), length: $ });
}
function G9($, X) {
  return new Az({ check: "string_format", format: "regex", ...P(X), pattern: $ });
}
function U9($) {
  return new Iz({ check: "string_format", format: "lowercase", ...P($) });
}
function H9($) {
  return new bz({ check: "string_format", format: "uppercase", ...P($) });
}
function K9($, X) {
  return new Zz({ check: "string_format", format: "includes", ...P(X), includes: $ });
}
function V9($, X) {
  return new Pz({ check: "string_format", format: "starts_with", ...P(X), prefix: $ });
}
function N9($, X) {
  return new Rz({ check: "string_format", format: "ends_with", ...P(X), suffix: $ });
}
function T3($, X, J) {
  return new Ez({ check: "property", property: $, schema: X, ...P(J) });
}
function O9($, X) {
  return new Sz({ check: "mime_type", mime: $, ...P(X) });
}
function M4($) {
  return new vz({ check: "overwrite", tx: $ });
}
function w9($) {
  return M4((X) => X.normalize($));
}
function B9() {
  return M4(($) => $.trim());
}
function q9() {
  return M4(($) => $.toLowerCase());
}
function L9() {
  return M4(($) => $.toUpperCase());
}
function D9($, X, J) {
  return new $({ type: "array", element: X, ...P(J) });
}
function jb($, X, J) {
  return new $({ type: "union", options: X, ...P(J) });
}
function Fb($, X, J, Q) {
  return new $({ type: "union", options: J, discriminator: X, ...P(Q) });
}
function Mb($, X, J) {
  return new $({ type: "intersection", left: X, right: J });
}
function y3($, X, J, Q) {
  let Y = J instanceof d;
  return new $({ type: "tuple", items: X, rest: Y ? J : null, ...P(Y ? Q : J) });
}
function Ab($, X, J, Q) {
  return new $({ type: "record", keyType: X, valueType: J, ...P(Q) });
}
function Ib($, X, J, Q) {
  return new $({ type: "map", keyType: X, valueType: J, ...P(Q) });
}
function bb($, X, J) {
  return new $({ type: "set", valueType: X, ...P(J) });
}
function Zb($, X, J) {
  let Q = Array.isArray(X) ? Object.fromEntries(X.map((Y) => [Y, Y])) : X;
  return new $({ type: "enum", entries: Q, ...P(J) });
}
function Pb($, X, J) {
  return new $({ type: "enum", entries: X, ...P(J) });
}
function Rb($, X, J) {
  return new $({ type: "literal", values: Array.isArray(X) ? X : [X], ...P(J) });
}
function h7($, X) {
  return new $({ type: "file", ...P(X) });
}
function Eb($, X) {
  return new $({ type: "transform", transform: X });
}
function Sb($, X) {
  return new $({ type: "optional", innerType: X });
}
function vb($, X) {
  return new $({ type: "nullable", innerType: X });
}
function Cb($, X, J) {
  return new $({ type: "default", innerType: X, get defaultValue() {
    return typeof J === "function" ? J() : J;
  } });
}
function kb($, X, J) {
  return new $({ type: "nonoptional", innerType: X, ...P(J) });
}
function _b($, X) {
  return new $({ type: "success", innerType: X });
}
function xb($, X, J) {
  return new $({ type: "catch", innerType: X, catchValue: typeof J === "function" ? J : () => J });
}
function Tb($, X, J) {
  return new $({ type: "pipe", in: X, out: J });
}
function yb($, X) {
  return new $({ type: "readonly", innerType: X });
}
function fb($, X, J) {
  return new $({ type: "template_literal", parts: X, ...P(J) });
}
function gb($, X) {
  return new $({ type: "lazy", getter: X });
}
function hb($, X) {
  return new $({ type: "promise", innerType: X });
}
function u7($, X, J) {
  var _a3;
  let Q = P(J);
  return (_a3 = Q.abort) != null ? _a3 : Q.abort = true, new $({ type: "custom", check: "custom", fn: X, ...Q });
}
function m7($, X, J) {
  return new $({ type: "custom", check: "custom", fn: X, ...P(J) });
}
function l7($, X) {
  var _a3, _b2, _c, _d2, _e, _f;
  let J = P(X), Q = (_a3 = J.truthy) != null ? _a3 : ["true", "1", "yes", "on", "y", "enabled"], Y = (_b2 = J.falsy) != null ? _b2 : ["false", "0", "no", "off", "n", "disabled"];
  if (J.case !== "sensitive") Q = Q.map((w) => typeof w === "string" ? w.toLowerCase() : w), Y = Y.map((w) => typeof w === "string" ? w.toLowerCase() : w);
  let W = new Set(Q), z8 = new Set(Y), G = (_c = $.Pipe) != null ? _c : k0, U = (_d2 = $.Boolean) != null ? _d2 : S0, H = (_e = $.String) != null ? _e : d4, V = new ((_f = $.Transform) != null ? _f : C0)({ type: "transform", transform: (w, B) => {
    let D = w;
    if (J.case !== "sensitive") D = D.toLowerCase();
    if (W.has(D)) return true;
    else if (z8.has(D)) return false;
    else return B.issues.push({ code: "invalid_value", expected: "stringbool", values: [...W, ...z8], input: B.value, inst: V }), {};
  }, error: J.error }), N = new G({ type: "pipe", in: new H({ type: "string", error: J.error }), out: V, error: J.error });
  return new G({ type: "pipe", in: N, out: new U({ type: "boolean", error: J.error }), error: J.error });
}
function c7($, X, J, Q = {}) {
  let Y = P(Q), W = { ...P(Q), check: "string_format", type: "string", format: X, fn: typeof J === "function" ? J : (G) => J.test(G), ...Y };
  if (J instanceof RegExp) W.pattern = J;
  return new $(W);
}
var f3 = class {
  constructor($) {
    this._def = $, this.def = $;
  }
  implement($) {
    if (typeof $ !== "function") throw Error("implement() must be called with a function");
    let X = (...J) => {
      let Q = this._def.input ? E1(this._def.input, J, void 0, { callee: X }) : J;
      if (!Array.isArray(Q)) throw Error("Invalid arguments schema: not an array or tuple schema.");
      let Y = $(...Q);
      return this._def.output ? E1(this._def.output, Y, void 0, { callee: X }) : Y;
    };
    return X;
  }
  implementAsync($) {
    if (typeof $ !== "function") throw Error("implement() must be called with a function");
    let X = async (...J) => {
      let Q = this._def.input ? await S1(this._def.input, J, void 0, { callee: X }) : J;
      if (!Array.isArray(Q)) throw Error("Invalid arguments schema: not an array or tuple schema.");
      let Y = await $(...Q);
      return this._def.output ? S1(this._def.output, Y, void 0, { callee: X }) : Y;
    };
    return X;
  }
  input(...$) {
    let X = this.constructor;
    if (Array.isArray($[0])) return new X({ type: "function", input: new i4({ type: "tuple", items: $[0], rest: $[1] }), output: this._def.output });
    return new X({ type: "function", input: $[0], output: this._def.output });
  }
  output($) {
    return new this.constructor({ type: "function", input: this._def.input, output: $ });
  }
};
function p7($) {
  var _a3, _b2;
  return new f3({ type: "function", input: Array.isArray($ == null ? void 0 : $.input) ? y3(i4, $ == null ? void 0 : $.input) : (_a3 = $ == null ? void 0 : $.input) != null ? _a3 : D9(v0, k1(C1)), output: (_b2 = $ == null ? void 0 : $.output) != null ? _b2 : k1(C1) });
}
var d7 = class {
  constructor($) {
    var _a3, _b2, _c, _d2, _e;
    this.counter = 0, this.metadataRegistry = (_a3 = $ == null ? void 0 : $.metadata) != null ? _a3 : G6, this.target = (_b2 = $ == null ? void 0 : $.target) != null ? _b2 : "draft-2020-12", this.unrepresentable = (_c = $ == null ? void 0 : $.unrepresentable) != null ? _c : "throw", this.override = (_d2 = $ == null ? void 0 : $.override) != null ? _d2 : (() => {
    }), this.io = (_e = $ == null ? void 0 : $.io) != null ? _e : "output", this.seen = /* @__PURE__ */ new Map();
  }
  process($, X = { path: [], schemaPath: [] }) {
    var _a3, _b2, _c, _d2, _e;
    var J;
    let Q = $._zod.def, Y = { guid: "uuid", url: "uri", datetime: "date-time", json_string: "json-string", regex: "" }, W = this.seen.get($);
    if (W) {
      if (W.count++, X.schemaPath.includes($)) W.cycle = X.path;
      return W.schema;
    }
    let z8 = { schema: {}, count: 1, cycle: void 0, path: X.path };
    this.seen.set($, z8);
    let G = (_b2 = (_a3 = $._zod).toJSONSchema) == null ? void 0 : _b2.call(_a3);
    if (G) z8.schema = G;
    else {
      let K = { ...X, schemaPath: [...X.schemaPath, $], path: X.path }, V = $._zod.parent;
      if (V) z8.ref = V, this.process(V, K), this.seen.get(V).isParent = true;
      else {
        let N = z8.schema;
        switch (Q.type) {
          case "string": {
            let O = N;
            O.type = "string";
            let { minimum: w, maximum: B, format: D, patterns: j, contentEncoding: A } = $._zod.bag;
            if (typeof w === "number") O.minLength = w;
            if (typeof B === "number") O.maxLength = B;
            if (D) {
              if (O.format = (_c = Y[D]) != null ? _c : D, O.format === "") delete O.format;
            }
            if (A) O.contentEncoding = A;
            if (j && j.size > 0) {
              let I = [...j];
              if (I.length === 1) O.pattern = I[0].source;
              else if (I.length > 1) z8.schema.allOf = [...I.map((x) => ({ ...this.target === "draft-7" ? { type: "string" } : {}, pattern: x.source }))];
            }
            break;
          }
          case "number": {
            let O = N, { minimum: w, maximum: B, format: D, multipleOf: j, exclusiveMaximum: A, exclusiveMinimum: I } = $._zod.bag;
            if (typeof D === "string" && D.includes("int")) O.type = "integer";
            else O.type = "number";
            if (typeof I === "number") O.exclusiveMinimum = I;
            if (typeof w === "number") {
              if (O.minimum = w, typeof I === "number") if (I >= w) delete O.minimum;
              else delete O.exclusiveMinimum;
            }
            if (typeof A === "number") O.exclusiveMaximum = A;
            if (typeof B === "number") {
              if (O.maximum = B, typeof A === "number") if (A <= B) delete O.maximum;
              else delete O.exclusiveMaximum;
            }
            if (typeof j === "number") O.multipleOf = j;
            break;
          }
          case "boolean": {
            let O = N;
            O.type = "boolean";
            break;
          }
          case "bigint": {
            if (this.unrepresentable === "throw") throw Error("BigInt cannot be represented in JSON Schema");
            break;
          }
          case "symbol": {
            if (this.unrepresentable === "throw") throw Error("Symbols cannot be represented in JSON Schema");
            break;
          }
          case "null": {
            N.type = "null";
            break;
          }
          case "any":
            break;
          case "unknown":
            break;
          case "undefined":
          case "never": {
            N.not = {};
            break;
          }
          case "void": {
            if (this.unrepresentable === "throw") throw Error("Void cannot be represented in JSON Schema");
            break;
          }
          case "date": {
            if (this.unrepresentable === "throw") throw Error("Date cannot be represented in JSON Schema");
            break;
          }
          case "array": {
            let O = N, { minimum: w, maximum: B } = $._zod.bag;
            if (typeof w === "number") O.minItems = w;
            if (typeof B === "number") O.maxItems = B;
            O.type = "array", O.items = this.process(Q.element, { ...K, path: [...K.path, "items"] });
            break;
          }
          case "object": {
            let O = N;
            O.type = "object", O.properties = {};
            let w = Q.shape;
            for (let j in w) O.properties[j] = this.process(w[j], { ...K, path: [...K.path, "properties", j] });
            let B = new Set(Object.keys(w)), D = new Set([...B].filter((j) => {
              let A = Q.shape[j]._zod;
              if (this.io === "input") return A.optin === void 0;
              else return A.optout === void 0;
            }));
            if (D.size > 0) O.required = Array.from(D);
            if (((_d2 = Q.catchall) == null ? void 0 : _d2._zod.def.type) === "never") O.additionalProperties = false;
            else if (!Q.catchall) {
              if (this.io === "output") O.additionalProperties = false;
            } else if (Q.catchall) O.additionalProperties = this.process(Q.catchall, { ...K, path: [...K.path, "additionalProperties"] });
            break;
          }
          case "union": {
            let O = N;
            O.anyOf = Q.options.map((w, B) => this.process(w, { ...K, path: [...K.path, "anyOf", B] }));
            break;
          }
          case "intersection": {
            let O = N, w = this.process(Q.left, { ...K, path: [...K.path, "allOf", 0] }), B = this.process(Q.right, { ...K, path: [...K.path, "allOf", 1] }), D = (A) => "allOf" in A && Object.keys(A).length === 1, j = [...D(w) ? w.allOf : [w], ...D(B) ? B.allOf : [B]];
            O.allOf = j;
            break;
          }
          case "tuple": {
            let O = N;
            O.type = "array";
            let w = Q.items.map((j, A) => this.process(j, { ...K, path: [...K.path, "prefixItems", A] }));
            if (this.target === "draft-2020-12") O.prefixItems = w;
            else O.items = w;
            if (Q.rest) {
              let j = this.process(Q.rest, { ...K, path: [...K.path, "items"] });
              if (this.target === "draft-2020-12") O.items = j;
              else O.additionalItems = j;
            }
            if (Q.rest) O.items = this.process(Q.rest, { ...K, path: [...K.path, "items"] });
            let { minimum: B, maximum: D } = $._zod.bag;
            if (typeof B === "number") O.minItems = B;
            if (typeof D === "number") O.maxItems = D;
            break;
          }
          case "record": {
            let O = N;
            O.type = "object", O.propertyNames = this.process(Q.keyType, { ...K, path: [...K.path, "propertyNames"] }), O.additionalProperties = this.process(Q.valueType, { ...K, path: [...K.path, "additionalProperties"] });
            break;
          }
          case "map": {
            if (this.unrepresentable === "throw") throw Error("Map cannot be represented in JSON Schema");
            break;
          }
          case "set": {
            if (this.unrepresentable === "throw") throw Error("Set cannot be represented in JSON Schema");
            break;
          }
          case "enum": {
            let O = N, w = ZX(Q.entries);
            if (w.every((B) => typeof B === "number")) O.type = "number";
            if (w.every((B) => typeof B === "string")) O.type = "string";
            O.enum = w;
            break;
          }
          case "literal": {
            let O = N, w = [];
            for (let B of Q.values) if (B === void 0) {
              if (this.unrepresentable === "throw") throw Error("Literal `undefined` cannot be represented in JSON Schema");
            } else if (typeof B === "bigint") if (this.unrepresentable === "throw") throw Error("BigInt literals cannot be represented in JSON Schema");
            else w.push(Number(B));
            else w.push(B);
            if (w.length === 0) ;
            else if (w.length === 1) {
              let B = w[0];
              O.type = B === null ? "null" : typeof B, O.const = B;
            } else {
              if (w.every((B) => typeof B === "number")) O.type = "number";
              if (w.every((B) => typeof B === "string")) O.type = "string";
              if (w.every((B) => typeof B === "boolean")) O.type = "string";
              if (w.every((B) => B === null)) O.type = "null";
              O.enum = w;
            }
            break;
          }
          case "file": {
            let O = N, w = { type: "string", format: "binary", contentEncoding: "binary" }, { minimum: B, maximum: D, mime: j } = $._zod.bag;
            if (B !== void 0) w.minLength = B;
            if (D !== void 0) w.maxLength = D;
            if (j) if (j.length === 1) w.contentMediaType = j[0], Object.assign(O, w);
            else O.anyOf = j.map((A) => {
              return { ...w, contentMediaType: A };
            });
            else Object.assign(O, w);
            break;
          }
          case "transform": {
            if (this.unrepresentable === "throw") throw Error("Transforms cannot be represented in JSON Schema");
            break;
          }
          case "nullable": {
            let O = this.process(Q.innerType, K);
            N.anyOf = [O, { type: "null" }];
            break;
          }
          case "nonoptional": {
            this.process(Q.innerType, K), z8.ref = Q.innerType;
            break;
          }
          case "success": {
            let O = N;
            O.type = "boolean";
            break;
          }
          case "default": {
            this.process(Q.innerType, K), z8.ref = Q.innerType, N.default = JSON.parse(JSON.stringify(Q.defaultValue));
            break;
          }
          case "prefault": {
            if (this.process(Q.innerType, K), z8.ref = Q.innerType, this.io === "input") N._prefault = JSON.parse(JSON.stringify(Q.defaultValue));
            break;
          }
          case "catch": {
            this.process(Q.innerType, K), z8.ref = Q.innerType;
            let O;
            try {
              O = Q.catchValue(void 0);
            } catch (e2) {
              throw Error("Dynamic catch values are not supported in JSON Schema");
            }
            N.default = O;
            break;
          }
          case "nan": {
            if (this.unrepresentable === "throw") throw Error("NaN cannot be represented in JSON Schema");
            break;
          }
          case "template_literal": {
            let O = N, w = $._zod.pattern;
            if (!w) throw Error("Pattern not found in template literal");
            O.type = "string", O.pattern = w.source;
            break;
          }
          case "pipe": {
            let O = this.io === "input" ? Q.in._zod.def.type === "transform" ? Q.out : Q.in : Q.out;
            this.process(O, K), z8.ref = O;
            break;
          }
          case "readonly": {
            this.process(Q.innerType, K), z8.ref = Q.innerType, N.readOnly = true;
            break;
          }
          case "promise": {
            this.process(Q.innerType, K), z8.ref = Q.innerType;
            break;
          }
          case "optional": {
            this.process(Q.innerType, K), z8.ref = Q.innerType;
            break;
          }
          case "lazy": {
            let O = $._zod.innerType;
            this.process(O, K), z8.ref = O;
            break;
          }
          case "custom": {
            if (this.unrepresentable === "throw") throw Error("Custom types cannot be represented in JSON Schema");
            break;
          }
          default:
        }
      }
    }
    let U = this.metadataRegistry.get($);
    if (U) Object.assign(z8.schema, U);
    if (this.io === "input" && _$($)) delete z8.schema.examples, delete z8.schema.default;
    if (this.io === "input" && z8.schema._prefault) (_e = (J = z8.schema).default) != null ? _e : J.default = z8.schema._prefault;
    return delete z8.schema._prefault, this.seen.get($).schema;
  }
  emit($, X) {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h;
    let J = { cycles: (_a3 = X == null ? void 0 : X.cycles) != null ? _a3 : "ref", reused: (_b2 = X == null ? void 0 : X.reused) != null ? _b2 : "inline", external: (_c = X == null ? void 0 : X.external) != null ? _c : void 0 }, Q = this.seen.get($);
    if (!Q) throw Error("Unprocessed schema. This is a bug in Zod.");
    let Y = (H) => {
      var _a4, _b3, _c2, _d3;
      let K = this.target === "draft-2020-12" ? "$defs" : "definitions";
      if (J.external) {
        let w = (_a4 = J.external.registry.get(H[0])) == null ? void 0 : _a4.id;
        if (w) return { ref: J.external.uri(w) };
        let B = (_c2 = (_b3 = H[1].defId) != null ? _b3 : H[1].schema.id) != null ? _c2 : `schema${this.counter++}`;
        return H[1].defId = B, { defId: B, ref: `${J.external.uri("__shared")}#/${K}/${B}` };
      }
      if (H[1] === Q) return { ref: "#" };
      let N = `${"#"}/${K}/`, O = (_d3 = H[1].schema.id) != null ? _d3 : `__schema${this.counter++}`;
      return { defId: O, ref: N + O };
    }, W = (H) => {
      if (H[1].schema.$ref) return;
      let K = H[1], { ref: V, defId: N } = Y(H);
      if (K.def = { ...K.schema }, N) K.defId = N;
      let O = K.schema;
      for (let w in O) delete O[w];
      O.$ref = V;
    };
    for (let H of this.seen.entries()) {
      let K = H[1];
      if ($ === H[0]) {
        W(H);
        continue;
      }
      if (J.external) {
        let N = (_d2 = J.external.registry.get(H[0])) == null ? void 0 : _d2.id;
        if ($ !== H[0] && N) {
          W(H);
          continue;
        }
      }
      if ((_e = this.metadataRegistry.get(H[0])) == null ? void 0 : _e.id) {
        W(H);
        continue;
      }
      if (K.cycle) {
        if (J.cycles === "throw") throw Error(`Cycle detected: #/${(_f = K.cycle) == null ? void 0 : _f.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
        else if (J.cycles === "ref") W(H);
        continue;
      }
      if (K.count > 1) {
        if (J.reused === "ref") {
          W(H);
          continue;
        }
      }
    }
    let z8 = (H, K) => {
      var _a4, _b3, _c2;
      let V = this.seen.get(H), N = (_a4 = V.def) != null ? _a4 : V.schema, O = { ...N };
      if (V.ref === null) return;
      let w = V.ref;
      if (V.ref = null, w) {
        z8(w, K);
        let B = this.seen.get(w).schema;
        if (B.$ref && K.target === "draft-7") N.allOf = (_b3 = N.allOf) != null ? _b3 : [], N.allOf.push(B);
        else Object.assign(N, B), Object.assign(N, O);
      }
      if (!V.isParent) this.override({ zodSchema: H, jsonSchema: N, path: (_c2 = V.path) != null ? _c2 : [] });
    };
    for (let H of [...this.seen.entries()].reverse()) z8(H[0], { target: this.target });
    let G = {};
    if (this.target === "draft-2020-12") G.$schema = "https://json-schema.org/draft/2020-12/schema";
    else if (this.target === "draft-7") G.$schema = "http://json-schema.org/draft-07/schema#";
    else console.warn(`Invalid target: ${this.target}`);
    Object.assign(G, Q.def);
    let U = (_h = (_g = J.external) == null ? void 0 : _g.defs) != null ? _h : {};
    for (let H of this.seen.entries()) {
      let K = H[1];
      if (K.def && K.defId) U[K.defId] = K.def;
    }
    if (!J.external && Object.keys(U).length > 0) if (this.target === "draft-2020-12") G.$defs = U;
    else G.definitions = U;
    try {
      return JSON.parse(JSON.stringify(G));
    } catch (H) {
      throw Error("Error converting schema to JSON.");
    }
  }
};
function g0($, X) {
  if ($ instanceof fX) {
    let Q = new d7(X), Y = {};
    for (let G of $._idmap.entries()) {
      let [U, H] = G;
      Q.process(H);
    }
    let W = {}, z8 = { registry: $, uri: (X == null ? void 0 : X.uri) || ((G) => G), defs: Y };
    for (let G of $._idmap.entries()) {
      let [U, H] = G;
      W[U] = Q.emit(H, { ...X, external: z8 });
    }
    if (Object.keys(Y).length > 0) {
      let G = Q.target === "draft-2020-12" ? "$defs" : "definitions";
      W.__shared = { [G]: Y };
    }
    return { schemas: W };
  }
  let J = new d7(X);
  return J.process($), J.emit($, X);
}
function _$($, X) {
  let J = X != null ? X : { seen: /* @__PURE__ */ new Set() };
  if (J.seen.has($)) return false;
  J.seen.add($);
  let Y = $._zod.def;
  switch (Y.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 false;
    case "array":
      return _$(Y.element, J);
    case "object": {
      for (let W in Y.shape) if (_$(Y.shape[W], J)) return true;
      return false;
    }
    case "union": {
      for (let W of Y.options) if (_$(W, J)) return true;
      return false;
    }
    case "intersection":
      return _$(Y.left, J) || _$(Y.right, J);
    case "tuple": {
      for (let W of Y.items) if (_$(W, J)) return true;
      if (Y.rest && _$(Y.rest, J)) return true;
      return false;
    }
    case "record":
      return _$(Y.keyType, J) || _$(Y.valueType, J);
    case "map":
      return _$(Y.keyType, J) || _$(Y.valueType, J);
    case "set":
      return _$(Y.valueType, J);
    case "promise":
    case "optional":
    case "nonoptional":
    case "nullable":
    case "readonly":
      return _$(Y.innerType, J);
    case "lazy":
      return _$(Y.getter(), J);
    case "default":
      return _$(Y.innerType, J);
    case "prefault":
      return _$(Y.innerType, J);
    case "custom":
      return false;
    case "transform":
      return true;
    case "pipe":
      return _$(Y.in, J) || _$(Y.out, J);
    case "success":
      return false;
    case "catch":
      return false;
    default:
  }
  throw Error(`Unknown schema type: ${Y.type}`);
}
var qN = {};
var mb = q("ZodMiniType", ($, X) => {
  if (!$._zod) throw Error("Uninitialized schema in ZodMiniType.");
  d.init($, X), $.def = X, $.parse = (J, Q) => E1($, J, Q, { callee: $.parse }), $.safeParse = (J, Q) => l4($, J, Q), $.parseAsync = async (J, Q) => S1($, J, Q, { callee: $.parseAsync }), $.safeParseAsync = async (J, Q) => c4($, J, Q), $.check = (...J) => {
    var _a3;
    return $.clone({ ...X, checks: [...(_a3 = X.checks) != null ? _a3 : [], ...J.map((Q) => typeof Q === "function" ? { _zod: { check: Q, def: { check: "custom" }, onattach: [] } } : Q)] });
  }, $.clone = (J, Q) => p$($, J, Q), $.brand = () => $, $.register = (J, Q) => {
    return J.add($, Q), $;
  };
});
var lb = q("ZodMiniObject", ($, X) => {
  xX.init($, X), mb.init($, X), R.defineLazy($, "shape", () => X.shape);
});
var t4 = {};
H1(t4, { xid: () => WZ, void: () => PZ, uuidv7: () => sb, uuidv6: () => ab, uuidv4: () => tb, uuid: () => ob, url: () => eb, uppercase: () => H9, unknown: () => j$, union: () => K$, undefined: () => bZ, ulid: () => QZ, uint64: () => AZ, uint32: () => jZ, tuple: () => vZ, trim: () => B9, treeifyError: () => HY, transform: () => qG, toUpperCase: () => L9, toLowerCase: () => q9, toJSONSchema: () => g0, templateLiteral: () => hZ, symbol: () => IZ, superRefine: () => XO, success: () => fZ, stringbool: () => lZ, stringFormat: () => BZ, string: () => F, strictObject: () => SZ, startsWith: () => V9, size: () => z9, setErrorMap: () => dZ, set: () => _Z, safeParseAsync: () => i3, safeParse: () => d3, registry: () => gX, regexes: () => p4, regex: () => G9, refine: () => $O, record: () => V$, readonly: () => rN, property: () => T3, promise: () => uZ, prettifyError: () => KY, preprocess: () => UQ, prefault: () => mN, positive: () => C3, pipe: () => XQ, partialRecord: () => CZ, parseAsync: () => p3, parse: () => c3, overwrite: () => M4, optional: () => D$, object: () => _, number: () => z$, nullish: () => yZ, nullable: () => $Q, null: () => JQ, normalize: () => w9, nonpositive: () => _3, nonoptional: () => lN, nonnegative: () => x3, never: () => YQ, negative: () => k3, nativeEnum: () => xZ, nanoid: () => XZ, nan: () => gZ, multipleOf: () => _1, minSize: () => x1, minLength: () => n4, mime: () => O9, maxSize: () => T0, maxLength: () => y0, map: () => kZ, lte: () => b6, lt: () => j4, lowercase: () => U9, looseObject: () => d$, locales: () => _0, literal: () => g, length: () => f0, lazy: () => aN, ksuid: () => zZ, keyof: () => EZ, jwt: () => wZ, json: () => cZ, iso: () => u0, ipv6: () => UZ, ipv4: () => GZ, intersection: () => b9, int64: () => MZ, int32: () => DZ, int: () => n3, instanceof: () => mZ, includes: () => K9, guid: () => rb, gte: () => U6, gt: () => F4, globalRegistry: () => G6, getErrorMap: () => iZ, function: () => p7, formatError: () => R0, float64: () => LZ, float32: () => qZ, flattenError: () => P0, file: () => TZ, enum: () => a$, endsWith: () => N9, emoji: () => $Z, email: () => nb, e164: () => OZ, discriminatedUnion: () => zQ, date: () => RZ, custom: () => FG, cuid2: () => YZ, cuid: () => JZ, core: () => f6, config: () => E$, coerce: () => MG, clone: () => p$, cidrv6: () => KZ, cidrv4: () => HZ, check: () => eN, catch: () => dN, boolean: () => v$, bigint: () => FZ, base64url: () => NZ, base64: () => VZ, array: () => $$, any: () => ZZ, _default: () => hN, _ZodString: () => r3, ZodXID: () => JG, ZodVoid: () => EN, ZodUnknown: () => PN, ZodUnion: () => OG, ZodUndefined: () => IN, ZodUUID: () => A4, ZodURL: () => t3, ZodULID: () => XG, ZodType: () => s, ZodTuple: () => kN, ZodTransform: () => BG, ZodTemplateLiteral: () => oN, ZodSymbol: () => AN, ZodSuccess: () => cN, ZodStringFormat: () => L$, ZodString: () => F9, ZodSet: () => xN, ZodRecord: () => wG, ZodRealError: () => m0, ZodReadonly: () => nN, ZodPromise: () => sN, ZodPrefault: () => uN, ZodPipe: () => jG, ZodOptional: () => LG, ZodObject: () => WQ, ZodNumberFormat: () => l0, ZodNumber: () => M9, ZodNullable: () => fN, ZodNull: () => bN, ZodNonOptional: () => DG, ZodNever: () => RN, ZodNanoID: () => s3, ZodNaN: () => iN, ZodMap: () => _N, ZodLiteral: () => TN, ZodLazy: () => tN, ZodKSUID: () => YG, ZodJWT: () => VG, ZodIssueCode: () => pZ, ZodIntersection: () => CN, ZodISOTime: () => a7, ZodISODuration: () => s7, ZodISODateTime: () => o7, ZodISODate: () => t7, ZodIPv6: () => WG, ZodIPv4: () => QG, ZodGUID: () => e7, ZodFile: () => yN, ZodError: () => db, ZodEnum: () => j9, ZodEmoji: () => a3, ZodEmail: () => o3, ZodE164: () => KG, ZodDiscriminatedUnion: () => vN, ZodDefault: () => gN, ZodDate: () => QQ, ZodCustomStringFormat: () => MN, ZodCustom: () => GQ, ZodCatch: () => pN, ZodCUID2: () => $G, ZodCUID: () => e3, ZodCIDRv6: () => GG, ZodCIDRv4: () => zG, ZodBoolean: () => A9, ZodBigIntFormat: () => NG, ZodBigInt: () => I9, ZodBase64URL: () => HG, ZodBase64: () => UG, ZodArray: () => SN, ZodAny: () => ZN, TimePrecision: () => F7, NEVER: () => zY, $output: () => L7, $input: () => D7, $brand: () => GY });
var u0 = {};
H1(u0, { time: () => m3, duration: () => l3, datetime: () => h3, date: () => u3, ZodISOTime: () => a7, ZodISODuration: () => s7, ZodISODateTime: () => o7, ZodISODate: () => t7 });
var o7 = q("ZodISODateTime", ($, X) => {
  _z.init($, X), L$.init($, X);
});
function h3($) {
  return I3(o7, $);
}
var t7 = q("ZodISODate", ($, X) => {
  xz.init($, X), L$.init($, X);
});
function u3($) {
  return b3(t7, $);
}
var a7 = q("ZodISOTime", ($, X) => {
  Tz.init($, X), L$.init($, X);
});
function m3($) {
  return Z3(a7, $);
}
var s7 = q("ZodISODuration", ($, X) => {
  yz.init($, X), L$.init($, X);
});
function l3($) {
  return P3(s7, $);
}
var FN = ($, X) => {
  CX.init($, X), $.name = "ZodError", Object.defineProperties($, { format: { value: (J) => R0($, J) }, flatten: { value: (J) => P0($, J) }, addIssue: { value: (J) => $.issues.push(J) }, addIssues: { value: (J) => $.issues.push(...J) }, isEmpty: { get() {
    return $.issues.length === 0;
  } } });
};
var db = q("ZodError", FN);
var m0 = q("ZodError", FN, { Parent: Error });
var c3 = VY(m0);
var p3 = NY(m0);
var d3 = OY(m0);
var i3 = wY(m0);
var s = q("ZodType", ($, X) => {
  return d.init($, X), $.def = X, Object.defineProperty($, "_def", { value: X }), $.check = (...J) => {
    var _a3;
    return $.clone({ ...X, checks: [...(_a3 = X.checks) != null ? _a3 : [], ...J.map((Q) => typeof Q === "function" ? { _zod: { check: Q, def: { check: "custom" }, onattach: [] } } : Q)] });
  }, $.clone = (J, Q) => p$($, J, Q), $.brand = () => $, $.register = (J, Q) => {
    return J.add($, Q), $;
  }, $.parse = (J, Q) => c3($, J, Q, { callee: $.parse }), $.safeParse = (J, Q) => d3($, J, Q), $.parseAsync = async (J, Q) => p3($, J, Q, { callee: $.parseAsync }), $.safeParseAsync = async (J, Q) => i3($, J, Q), $.spa = $.safeParseAsync, $.refine = (J, Q) => $.check($O(J, Q)), $.superRefine = (J) => $.check(XO(J)), $.overwrite = (J) => $.check(M4(J)), $.optional = () => D$($), $.nullable = () => $Q($), $.nullish = () => D$($Q($)), $.nonoptional = (J) => lN($, J), $.array = () => $$($), $.or = (J) => K$([$, J]), $.and = (J) => b9($, J), $.transform = (J) => XQ($, qG(J)), $.default = (J) => hN($, J), $.prefault = (J) => mN($, J), $.catch = (J) => dN($, J), $.pipe = (J) => XQ($, J), $.readonly = () => rN($), $.describe = (J) => {
    let Q = $.clone();
    return G6.add(Q, { description: J }), Q;
  }, Object.defineProperty($, "description", { get() {
    var _a3;
    return (_a3 = G6.get($)) == null ? void 0 : _a3.description;
  }, configurable: true }), $.meta = (...J) => {
    if (J.length === 0) return G6.get($);
    let Q = $.clone();
    return G6.add(Q, J[0]), Q;
  }, $.isOptional = () => $.safeParse(void 0).success, $.isNullable = () => $.safeParse(null).success, $;
});
var r3 = q("_ZodString", ($, X) => {
  var _a3, _b2, _c;
  d4.init($, X), s.init($, X);
  let J = $._zod.bag;
  $.format = (_a3 = J.format) != null ? _a3 : null, $.minLength = (_b2 = J.minimum) != null ? _b2 : null, $.maxLength = (_c = J.maximum) != null ? _c : null, $.regex = (...Q) => $.check(G9(...Q)), $.includes = (...Q) => $.check(K9(...Q)), $.startsWith = (...Q) => $.check(V9(...Q)), $.endsWith = (...Q) => $.check(N9(...Q)), $.min = (...Q) => $.check(n4(...Q)), $.max = (...Q) => $.check(y0(...Q)), $.length = (...Q) => $.check(f0(...Q)), $.nonempty = (...Q) => $.check(n4(1, ...Q)), $.lowercase = (Q) => $.check(U9(Q)), $.uppercase = (Q) => $.check(H9(Q)), $.trim = () => $.check(B9()), $.normalize = (...Q) => $.check(w9(...Q)), $.toLowerCase = () => $.check(q9()), $.toUpperCase = () => $.check(L9());
});
var F9 = q("ZodString", ($, X) => {
  d4.init($, X), r3.init($, X), $.email = (J) => $.check(hX(o3, J)), $.url = (J) => $.check(pX(t3, J)), $.jwt = (J) => $.check(W9(VG, J)), $.emoji = (J) => $.check(dX(a3, J)), $.guid = (J) => $.check(x0(e7, J)), $.uuid = (J) => $.check(uX(A4, J)), $.uuidv4 = (J) => $.check(mX(A4, J)), $.uuidv6 = (J) => $.check(lX(A4, J)), $.uuidv7 = (J) => $.check(cX(A4, J)), $.nanoid = (J) => $.check(iX(s3, J)), $.guid = (J) => $.check(x0(e7, J)), $.cuid = (J) => $.check(nX(e3, J)), $.cuid2 = (J) => $.check(rX($G, J)), $.ulid = (J) => $.check(oX(XG, J)), $.base64 = (J) => $.check(J9(UG, J)), $.base64url = (J) => $.check(Y9(HG, J)), $.xid = (J) => $.check(tX(JG, J)), $.ksuid = (J) => $.check(aX(YG, J)), $.ipv4 = (J) => $.check(sX(QG, J)), $.ipv6 = (J) => $.check(eX(WG, J)), $.cidrv4 = (J) => $.check($9(zG, J)), $.cidrv6 = (J) => $.check(X9(GG, J)), $.e164 = (J) => $.check(Q9(KG, J)), $.datetime = (J) => $.check(h3(J)), $.date = (J) => $.check(u3(J)), $.time = (J) => $.check(m3(J)), $.duration = (J) => $.check(l3(J));
});
function F($) {
  return j7(F9, $);
}
var L$ = q("ZodStringFormat", ($, X) => {
  H$.init($, X), r3.init($, X);
});
var o3 = q("ZodEmail", ($, X) => {
  IY.init($, X), L$.init($, X);
});
function nb($) {
  return hX(o3, $);
}
var e7 = q("ZodGUID", ($, X) => {
  MY.init($, X), L$.init($, X);
});
function rb($) {
  return x0(e7, $);
}
var A4 = q("ZodUUID", ($, X) => {
  AY.init($, X), L$.init($, X);
});
function ob($) {
  return uX(A4, $);
}
function tb($) {
  return mX(A4, $);
}
function ab($) {
  return lX(A4, $);
}
function sb($) {
  return cX(A4, $);
}
var t3 = q("ZodURL", ($, X) => {
  bY.init($, X), L$.init($, X);
});
function eb($) {
  return pX(t3, $);
}
var a3 = q("ZodEmoji", ($, X) => {
  ZY.init($, X), L$.init($, X);
});
function $Z($) {
  return dX(a3, $);
}
var s3 = q("ZodNanoID", ($, X) => {
  PY.init($, X), L$.init($, X);
});
function XZ($) {
  return iX(s3, $);
}
var e3 = q("ZodCUID", ($, X) => {
  RY.init($, X), L$.init($, X);
});
function JZ($) {
  return nX(e3, $);
}
var $G = q("ZodCUID2", ($, X) => {
  EY.init($, X), L$.init($, X);
});
function YZ($) {
  return rX($G, $);
}
var XG = q("ZodULID", ($, X) => {
  SY.init($, X), L$.init($, X);
});
function QZ($) {
  return oX(XG, $);
}
var JG = q("ZodXID", ($, X) => {
  vY.init($, X), L$.init($, X);
});
function WZ($) {
  return tX(JG, $);
}
var YG = q("ZodKSUID", ($, X) => {
  CY.init($, X), L$.init($, X);
});
function zZ($) {
  return aX(YG, $);
}
var QG = q("ZodIPv4", ($, X) => {
  kY.init($, X), L$.init($, X);
});
function GZ($) {
  return sX(QG, $);
}
var WG = q("ZodIPv6", ($, X) => {
  _Y.init($, X), L$.init($, X);
});
function UZ($) {
  return eX(WG, $);
}
var zG = q("ZodCIDRv4", ($, X) => {
  xY.init($, X), L$.init($, X);
});
function HZ($) {
  return $9(zG, $);
}
var GG = q("ZodCIDRv6", ($, X) => {
  TY.init($, X), L$.init($, X);
});
function KZ($) {
  return X9(GG, $);
}
var UG = q("ZodBase64", ($, X) => {
  yY.init($, X), L$.init($, X);
});
function VZ($) {
  return J9(UG, $);
}
var HG = q("ZodBase64URL", ($, X) => {
  fY.init($, X), L$.init($, X);
});
function NZ($) {
  return Y9(HG, $);
}
var KG = q("ZodE164", ($, X) => {
  gY.init($, X), L$.init($, X);
});
function OZ($) {
  return Q9(KG, $);
}
var VG = q("ZodJWT", ($, X) => {
  hY.init($, X), L$.init($, X);
});
function wZ($) {
  return W9(VG, $);
}
var MN = q("ZodCustomStringFormat", ($, X) => {
  uY.init($, X), L$.init($, X);
});
function BZ($, X, J = {}) {
  return c7(MN, $, X, J);
}
var M9 = q("ZodNumber", ($, X) => {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i;
  kX.init($, X), s.init($, X), $.gt = (Q, Y) => $.check(F4(Q, Y)), $.gte = (Q, Y) => $.check(U6(Q, Y)), $.min = (Q, Y) => $.check(U6(Q, Y)), $.lt = (Q, Y) => $.check(j4(Q, Y)), $.lte = (Q, Y) => $.check(b6(Q, Y)), $.max = (Q, Y) => $.check(b6(Q, Y)), $.int = (Q) => $.check(n3(Q)), $.safe = (Q) => $.check(n3(Q)), $.positive = (Q) => $.check(F4(0, Q)), $.nonnegative = (Q) => $.check(U6(0, Q)), $.negative = (Q) => $.check(j4(0, Q)), $.nonpositive = (Q) => $.check(b6(0, Q)), $.multipleOf = (Q, Y) => $.check(_1(Q, Y)), $.step = (Q, Y) => $.check(_1(Q, Y)), $.finite = () => $;
  let J = $._zod.bag;
  $.minValue = (_c = Math.max((_a3 = J.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY, (_b2 = J.exclusiveMinimum) != null ? _b2 : Number.NEGATIVE_INFINITY)) != null ? _c : null, $.maxValue = (_f = Math.min((_d2 = J.maximum) != null ? _d2 : Number.POSITIVE_INFINITY, (_e = J.exclusiveMaximum) != null ? _e : Number.POSITIVE_INFINITY)) != null ? _f : null, $.isInt = ((_g = J.format) != null ? _g : "").includes("int") || Number.isSafeInteger((_h = J.multipleOf) != null ? _h : 0.5), $.isFinite = true, $.format = (_i = J.format) != null ? _i : null;
});
function z$($) {
  return M7(M9, $);
}
var l0 = q("ZodNumberFormat", ($, X) => {
  mY.init($, X), M9.init($, X);
});
function n3($) {
  return A7(l0, $);
}
function qZ($) {
  return I7(l0, $);
}
function LZ($) {
  return b7(l0, $);
}
function DZ($) {
  return Z7(l0, $);
}
function jZ($) {
  return P7(l0, $);
}
var A9 = q("ZodBoolean", ($, X) => {
  S0.init($, X), s.init($, X);
});
function v$($) {
  return R7(A9, $);
}
var I9 = q("ZodBigInt", ($, X) => {
  var _a3, _b2, _c;
  _X.init($, X), s.init($, X), $.gte = (Q, Y) => $.check(U6(Q, Y)), $.min = (Q, Y) => $.check(U6(Q, Y)), $.gt = (Q, Y) => $.check(F4(Q, Y)), $.gte = (Q, Y) => $.check(U6(Q, Y)), $.min = (Q, Y) => $.check(U6(Q, Y)), $.lt = (Q, Y) => $.check(j4(Q, Y)), $.lte = (Q, Y) => $.check(b6(Q, Y)), $.max = (Q, Y) => $.check(b6(Q, Y)), $.positive = (Q) => $.check(F4(BigInt(0), Q)), $.negative = (Q) => $.check(j4(BigInt(0), Q)), $.nonpositive = (Q) => $.check(b6(BigInt(0), Q)), $.nonnegative = (Q) => $.check(U6(BigInt(0), Q)), $.multipleOf = (Q, Y) => $.check(_1(Q, Y));
  let J = $._zod.bag;
  $.minValue = (_a3 = J.minimum) != null ? _a3 : null, $.maxValue = (_b2 = J.maximum) != null ? _b2 : null, $.format = (_c = J.format) != null ? _c : null;
});
function FZ($) {
  return E7(I9, $);
}
var NG = q("ZodBigIntFormat", ($, X) => {
  lY.init($, X), I9.init($, X);
});
function MZ($) {
  return S7(NG, $);
}
function AZ($) {
  return v7(NG, $);
}
var AN = q("ZodSymbol", ($, X) => {
  cY.init($, X), s.init($, X);
});
function IZ($) {
  return C7(AN, $);
}
var IN = q("ZodUndefined", ($, X) => {
  pY.init($, X), s.init($, X);
});
function bZ($) {
  return k7(IN, $);
}
var bN = q("ZodNull", ($, X) => {
  dY.init($, X), s.init($, X);
});
function JQ($) {
  return _7(bN, $);
}
var ZN = q("ZodAny", ($, X) => {
  iY.init($, X), s.init($, X);
});
function ZZ() {
  return x7(ZN);
}
var PN = q("ZodUnknown", ($, X) => {
  C1.init($, X), s.init($, X);
});
function j$() {
  return k1(PN);
}
var RN = q("ZodNever", ($, X) => {
  nY.init($, X), s.init($, X);
});
function YQ($) {
  return T7(RN, $);
}
var EN = q("ZodVoid", ($, X) => {
  rY.init($, X), s.init($, X);
});
function PZ($) {
  return y7(EN, $);
}
var QQ = q("ZodDate", ($, X) => {
  oY.init($, X), s.init($, X), $.min = (Q, Y) => $.check(U6(Q, Y)), $.max = (Q, Y) => $.check(b6(Q, Y));
  let J = $._zod.bag;
  $.minDate = J.minimum ? new Date(J.minimum) : null, $.maxDate = J.maximum ? new Date(J.maximum) : null;
});
function RZ($) {
  return f7(QQ, $);
}
var SN = q("ZodArray", ($, X) => {
  v0.init($, X), s.init($, X), $.element = X.element, $.min = (J, Q) => $.check(n4(J, Q)), $.nonempty = (J) => $.check(n4(1, J)), $.max = (J, Q) => $.check(y0(J, Q)), $.length = (J, Q) => $.check(f0(J, Q)), $.unwrap = () => $.element;
});
function $$($, X) {
  return D9(SN, $, X);
}
function EZ($) {
  let X = $._zod.def.shape;
  return g(Object.keys(X));
}
var WQ = q("ZodObject", ($, X) => {
  xX.init($, X), s.init($, X), R.defineLazy($, "shape", () => X.shape), $.keyof = () => a$(Object.keys($._zod.def.shape)), $.catchall = (J) => $.clone({ ...$._zod.def, catchall: J }), $.passthrough = () => $.clone({ ...$._zod.def, catchall: j$() }), $.loose = () => $.clone({ ...$._zod.def, catchall: j$() }), $.strict = () => $.clone({ ...$._zod.def, catchall: YQ() }), $.strip = () => $.clone({ ...$._zod.def, catchall: void 0 }), $.extend = (J) => {
    return R.extend($, J);
  }, $.merge = (J) => R.merge($, J), $.pick = (J) => R.pick($, J), $.omit = (J) => R.omit($, J), $.partial = (...J) => R.partial(LG, $, J[0]), $.required = (...J) => R.required(DG, $, J[0]);
});
function _($, X) {
  let J = { type: "object", get shape() {
    return R.assignProp(this, "shape", { ...$ }), this.shape;
  }, ...R.normalizeParams(X) };
  return new WQ(J);
}
function SZ($, X) {
  return new WQ({ type: "object", get shape() {
    return R.assignProp(this, "shape", { ...$ }), this.shape;
  }, catchall: YQ(), ...R.normalizeParams(X) });
}
function d$($, X) {
  return new WQ({ type: "object", get shape() {
    return R.assignProp(this, "shape", { ...$ }), this.shape;
  }, catchall: j$(), ...R.normalizeParams(X) });
}
var OG = q("ZodUnion", ($, X) => {
  TX.init($, X), s.init($, X), $.options = X.options;
});
function K$($, X) {
  return new OG({ type: "union", options: $, ...R.normalizeParams(X) });
}
var vN = q("ZodDiscriminatedUnion", ($, X) => {
  OG.init($, X), tY.init($, X);
});
function zQ($, X, J) {
  return new vN({ type: "union", options: X, discriminator: $, ...R.normalizeParams(J) });
}
var CN = q("ZodIntersection", ($, X) => {
  aY.init($, X), s.init($, X);
});
function b9($, X) {
  return new CN({ type: "intersection", left: $, right: X });
}
var kN = q("ZodTuple", ($, X) => {
  i4.init($, X), s.init($, X), $.rest = (J) => $.clone({ ...$._zod.def, rest: J });
});
function vZ($, X, J) {
  let Q = X instanceof d, Y = Q ? J : X;
  return new kN({ type: "tuple", items: $, rest: Q ? X : null, ...R.normalizeParams(Y) });
}
var wG = q("ZodRecord", ($, X) => {
  sY.init($, X), s.init($, X), $.keyType = X.keyType, $.valueType = X.valueType;
});
function V$($, X, J) {
  return new wG({ type: "record", keyType: $, valueType: X, ...R.normalizeParams(J) });
}
function CZ($, X, J) {
  return new wG({ type: "record", keyType: K$([$, YQ()]), valueType: X, ...R.normalizeParams(J) });
}
var _N = q("ZodMap", ($, X) => {
  eY.init($, X), s.init($, X), $.keyType = X.keyType, $.valueType = X.valueType;
});
function kZ($, X, J) {
  return new _N({ type: "map", keyType: $, valueType: X, ...R.normalizeParams(J) });
}
var xN = q("ZodSet", ($, X) => {
  $7.init($, X), s.init($, X), $.min = (...J) => $.check(x1(...J)), $.nonempty = (J) => $.check(x1(1, J)), $.max = (...J) => $.check(T0(...J)), $.size = (...J) => $.check(z9(...J));
});
function _Z($, X) {
  return new xN({ type: "set", valueType: $, ...R.normalizeParams(X) });
}
var j9 = q("ZodEnum", ($, X) => {
  X7.init($, X), s.init($, X), $.enum = X.entries, $.options = Object.values(X.entries);
  let J = new Set(Object.keys(X.entries));
  $.extract = (Q, Y) => {
    let W = {};
    for (let z8 of Q) if (J.has(z8)) W[z8] = X.entries[z8];
    else throw Error(`Key ${z8} not found in enum`);
    return new j9({ ...X, checks: [], ...R.normalizeParams(Y), entries: W });
  }, $.exclude = (Q, Y) => {
    let W = { ...X.entries };
    for (let z8 of Q) if (J.has(z8)) delete W[z8];
    else throw Error(`Key ${z8} not found in enum`);
    return new j9({ ...X, checks: [], ...R.normalizeParams(Y), entries: W });
  };
});
function a$($, X) {
  let J = Array.isArray($) ? Object.fromEntries($.map((Q) => [Q, Q])) : $;
  return new j9({ type: "enum", entries: J, ...R.normalizeParams(X) });
}
function xZ($, X) {
  return new j9({ type: "enum", entries: $, ...R.normalizeParams(X) });
}
var TN = q("ZodLiteral", ($, X) => {
  J7.init($, X), s.init($, X), $.values = new Set(X.values), Object.defineProperty($, "value", { get() {
    if (X.values.length > 1) throw Error("This schema contains multiple valid literal values. Use `.values` instead.");
    return X.values[0];
  } });
});
function g($, X) {
  return new TN({ type: "literal", values: Array.isArray($) ? $ : [$], ...R.normalizeParams(X) });
}
var yN = q("ZodFile", ($, X) => {
  Y7.init($, X), s.init($, X), $.min = (J, Q) => $.check(x1(J, Q)), $.max = (J, Q) => $.check(T0(J, Q)), $.mime = (J, Q) => $.check(O9(Array.isArray(J) ? J : [J], Q));
});
function TZ($) {
  return h7(yN, $);
}
var BG = q("ZodTransform", ($, X) => {
  C0.init($, X), s.init($, X), $._zod.parse = (J, Q) => {
    J.addIssue = (W) => {
      var _a3, _b2, _c, _d2;
      if (typeof W === "string") J.issues.push(R.issue(W, J.value, X));
      else {
        let z8 = W;
        if (z8.fatal) z8.continue = false;
        (_a3 = z8.code) != null ? _a3 : z8.code = "custom", (_b2 = z8.input) != null ? _b2 : z8.input = J.value, (_c = z8.inst) != null ? _c : z8.inst = $, (_d2 = z8.continue) != null ? _d2 : z8.continue = true, J.issues.push(R.issue(z8));
      }
    };
    let Y = X.transform(J.value, J);
    if (Y instanceof Promise) return Y.then((W) => {
      return J.value = W, J;
    });
    return J.value = Y, J;
  };
});
function qG($) {
  return new BG({ type: "transform", transform: $ });
}
var LG = q("ZodOptional", ($, X) => {
  Q7.init($, X), s.init($, X), $.unwrap = () => $._zod.def.innerType;
});
function D$($) {
  return new LG({ type: "optional", innerType: $ });
}
var fN = q("ZodNullable", ($, X) => {
  W7.init($, X), s.init($, X), $.unwrap = () => $._zod.def.innerType;
});
function $Q($) {
  return new fN({ type: "nullable", innerType: $ });
}
function yZ($) {
  return D$($Q($));
}
var gN = q("ZodDefault", ($, X) => {
  z7.init($, X), s.init($, X), $.unwrap = () => $._zod.def.innerType, $.removeDefault = $.unwrap;
});
function hN($, X) {
  return new gN({ type: "default", innerType: $, get defaultValue() {
    return typeof X === "function" ? X() : X;
  } });
}
var uN = q("ZodPrefault", ($, X) => {
  G7.init($, X), s.init($, X), $.unwrap = () => $._zod.def.innerType;
});
function mN($, X) {
  return new uN({ type: "prefault", innerType: $, get defaultValue() {
    return typeof X === "function" ? X() : X;
  } });
}
var DG = q("ZodNonOptional", ($, X) => {
  U7.init($, X), s.init($, X), $.unwrap = () => $._zod.def.innerType;
});
function lN($, X) {
  return new DG({ type: "nonoptional", innerType: $, ...R.normalizeParams(X) });
}
var cN = q("ZodSuccess", ($, X) => {
  H7.init($, X), s.init($, X), $.unwrap = () => $._zod.def.innerType;
});
function fZ($) {
  return new cN({ type: "success", innerType: $ });
}
var pN = q("ZodCatch", ($, X) => {
  K7.init($, X), s.init($, X), $.unwrap = () => $._zod.def.innerType, $.removeCatch = $.unwrap;
});
function dN($, X) {
  return new pN({ type: "catch", innerType: $, catchValue: typeof X === "function" ? X : () => X });
}
var iN = q("ZodNaN", ($, X) => {
  V7.init($, X), s.init($, X);
});
function gZ($) {
  return g7(iN, $);
}
var jG = q("ZodPipe", ($, X) => {
  k0.init($, X), s.init($, X), $.in = X.in, $.out = X.out;
});
function XQ($, X) {
  return new jG({ type: "pipe", in: $, out: X });
}
var nN = q("ZodReadonly", ($, X) => {
  N7.init($, X), s.init($, X);
});
function rN($) {
  return new nN({ type: "readonly", innerType: $ });
}
var oN = q("ZodTemplateLiteral", ($, X) => {
  O7.init($, X), s.init($, X);
});
function hZ($, X) {
  return new oN({ type: "template_literal", parts: $, ...R.normalizeParams(X) });
}
var tN = q("ZodLazy", ($, X) => {
  B7.init($, X), s.init($, X), $.unwrap = () => $._zod.def.getter();
});
function aN($) {
  return new tN({ type: "lazy", getter: $ });
}
var sN = q("ZodPromise", ($, X) => {
  w7.init($, X), s.init($, X), $.unwrap = () => $._zod.def.innerType;
});
function uZ($) {
  return new sN({ type: "promise", innerType: $ });
}
var GQ = q("ZodCustom", ($, X) => {
  q7.init($, X), s.init($, X);
});
function eN($, X) {
  let J = new A$({ check: "custom", ...R.normalizeParams(X) });
  return J._zod.check = $, J;
}
function FG($, X) {
  return u7(GQ, $ != null ? $ : (() => true), X);
}
function $O($, X = {}) {
  return m7(GQ, $, X);
}
function XO($, X) {
  let J = eN((Q) => {
    return Q.addIssue = (Y) => {
      var _a3, _b2, _c, _d2;
      if (typeof Y === "string") Q.issues.push(R.issue(Y, Q.value, J._zod.def));
      else {
        let W = Y;
        if (W.fatal) W.continue = false;
        (_a3 = W.code) != null ? _a3 : W.code = "custom", (_b2 = W.input) != null ? _b2 : W.input = Q.value, (_c = W.inst) != null ? _c : W.inst = J, (_d2 = W.continue) != null ? _d2 : W.continue = !J._zod.def.abort, Q.issues.push(R.issue(W));
      }
    }, $(Q.value, Q);
  }, X);
  return J;
}
function mZ($, X = { error: `Input not instance of ${$.name}` }) {
  let J = new GQ({ type: "custom", check: "custom", fn: (Q) => Q instanceof $, abort: true, ...R.normalizeParams(X) });
  return J._zod.bag.Class = $, J;
}
var lZ = (...$) => l7({ Pipe: jG, Boolean: A9, String: F9, Transform: BG }, ...$);
function cZ($) {
  let X = aN(() => {
    return K$([F($), z$(), v$(), JQ(), $$(X), V$(F(), X)]);
  });
  return X;
}
function UQ($, X) {
  return XQ(qG($), X);
}
var pZ = { invalid_type: "invalid_type", too_big: "too_big", too_small: "too_small", invalid_format: "invalid_format", not_multiple_of: "not_multiple_of", unrecognized_keys: "unrecognized_keys", invalid_union: "invalid_union", invalid_key: "invalid_key", invalid_element: "invalid_element", invalid_value: "invalid_value", custom: "custom" };
function dZ($) {
  E$({ customError: $ });
}
function iZ() {
  return E$().customError;
}
var MG = {};
H1(MG, { string: () => nZ, number: () => rZ, date: () => aZ, boolean: () => oZ, bigint: () => tZ });
function nZ($) {
  return A3(F9, $);
}
function rZ($) {
  return R3(M9, $);
}
function oZ($) {
  return E3(A9, $);
}
function tZ($) {
  return S3(I9, $);
}
function aZ($) {
  return v3(QQ, $);
}
E$(yX());
var a4 = "io.modelcontextprotocol/related-task";
var KQ = "2.0";
var x$ = FG(($) => $ !== null && (typeof $ === "object" || typeof $ === "function"));
var YO = K$([F(), z$().int()]);
var QO = F();
var wr = d$({ ttl: z$().optional(), pollInterval: z$().optional() });
var sZ = _({ ttl: z$().optional() });
var eZ = _({ taskId: F() });
var IG = d$({ progressToken: YO.optional(), [a4]: eZ.optional() });
var j6 = _({ _meta: IG.optional() });
var Z9 = j6.extend({ task: sZ.optional() });
var h$ = _({ method: F(), params: j6.loose().optional() });
var P6 = _({ _meta: IG.optional() });
var R6 = _({ method: F(), params: P6.loose().optional() });
var u$ = d$({ _meta: IG.optional() });
var VQ = K$([F(), z$().int()]);
var zO = _({ jsonrpc: g(KQ), id: VQ, ...h$.shape }).strict();
var GO = _({ jsonrpc: g(KQ), ...R6.shape }).strict();
var ZG = _({ jsonrpc: g(KQ), id: VQ, result: u$ }).strict();
var m;
(function($) {
  $[$.ConnectionClosed = -32e3] = "ConnectionClosed", $[$.RequestTimeout = -32001] = "RequestTimeout", $[$.ParseError = -32700] = "ParseError", $[$.InvalidRequest = -32600] = "InvalidRequest", $[$.MethodNotFound = -32601] = "MethodNotFound", $[$.InvalidParams = -32602] = "InvalidParams", $[$.InternalError = -32603] = "InternalError", $[$.UrlElicitationRequired = -32042] = "UrlElicitationRequired";
})(m || (m = {}));
var PG = _({ jsonrpc: g(KQ), id: VQ.optional(), error: _({ code: z$().int(), message: F(), data: j$().optional() }) }).strict();
var Br = K$([zO, GO, ZG, PG]);
var qr = K$([ZG, PG]);
var NQ = u$.strict();
var $P = P6.extend({ requestId: VQ.optional(), reason: F().optional() });
var OQ = R6.extend({ method: g("notifications/cancelled"), params: $P });
var XP = _({ src: F(), mimeType: F().optional(), sizes: $$(F()).optional(), theme: a$(["light", "dark"]).optional() });
var R9 = _({ icons: $$(XP).optional() });
var c0 = _({ name: F(), title: F().optional() });
var KO = c0.extend({ ...c0.shape, ...R9.shape, version: F(), websiteUrl: F().optional(), description: F().optional() });
var JP = b9(_({ applyDefaults: v$().optional() }), V$(F(), j$()));
var YP = UQ(($) => {
  if ($ && typeof $ === "object" && !Array.isArray($)) {
    if (Object.keys($).length === 0) return { form: {} };
  }
  return $;
}, b9(_({ form: JP.optional(), url: x$.optional() }), V$(F(), j$()).optional()));
var QP = d$({ list: x$.optional(), cancel: x$.optional(), requests: d$({ sampling: d$({ createMessage: x$.optional() }).optional(), elicitation: d$({ create: x$.optional() }).optional() }).optional() });
var WP = d$({ list: x$.optional(), cancel: x$.optional(), requests: d$({ tools: d$({ call: x$.optional() }).optional() }).optional() });
var zP = _({ experimental: V$(F(), x$).optional(), sampling: _({ context: x$.optional(), tools: x$.optional() }).optional(), elicitation: YP.optional(), roots: _({ listChanged: v$().optional() }).optional(), tasks: QP.optional(), extensions: V$(F(), x$).optional() });
var GP = j6.extend({ protocolVersion: F(), capabilities: zP, clientInfo: KO });
var RG = h$.extend({ method: g("initialize"), params: GP });
var UP = _({ experimental: V$(F(), x$).optional(), logging: x$.optional(), completions: x$.optional(), prompts: _({ listChanged: v$().optional() }).optional(), resources: _({ subscribe: v$().optional(), listChanged: v$().optional() }).optional(), tools: _({ listChanged: v$().optional() }).optional(), tasks: WP.optional(), extensions: V$(F(), x$).optional() });
var HP = u$.extend({ protocolVersion: F(), capabilities: UP, serverInfo: KO, instructions: F().optional() });
var EG = R6.extend({ method: g("notifications/initialized"), params: P6.optional() });
var wQ = h$.extend({ method: g("ping"), params: j6.optional() });
var KP = _({ progress: z$(), total: D$(z$()), message: D$(F()) });
var VP = _({ ...P6.shape, ...KP.shape, progressToken: YO });
var BQ = R6.extend({ method: g("notifications/progress"), params: VP });
var NP = j6.extend({ cursor: QO.optional() });
var E9 = h$.extend({ params: NP.optional() });
var S9 = u$.extend({ nextCursor: QO.optional() });
var OP = a$(["working", "input_required", "completed", "failed", "cancelled"]);
var v9 = _({ taskId: F(), status: OP, ttl: K$([z$(), JQ()]), createdAt: F(), lastUpdatedAt: F(), pollInterval: D$(z$()), statusMessage: D$(F()) });
var p0 = u$.extend({ task: v9 });
var wP = P6.merge(v9);
var C9 = R6.extend({ method: g("notifications/tasks/status"), params: wP });
var qQ = h$.extend({ method: g("tasks/get"), params: j6.extend({ taskId: F() }) });
var LQ = u$.merge(v9);
var DQ = h$.extend({ method: g("tasks/result"), params: j6.extend({ taskId: F() }) });
var Lr = u$.loose();
var jQ = E9.extend({ method: g("tasks/list") });
var FQ = S9.extend({ tasks: $$(v9) });
var MQ = h$.extend({ method: g("tasks/cancel"), params: j6.extend({ taskId: F() }) });
var VO = u$.merge(v9);
var NO = _({ uri: F(), mimeType: D$(F()), _meta: V$(F(), j$()).optional() });
var OO = NO.extend({ text: F() });
var SG = F().refine(($) => {
  try {
    return atob($), true;
  } catch (e2) {
    return false;
  }
}, { message: "Invalid Base64 string" });
var wO = NO.extend({ blob: SG });
var k9 = a$(["user", "assistant"]);
var d0 = _({ audience: $$(k9).optional(), priority: z$().min(0).max(1).optional(), lastModified: u0.datetime({ offset: true }).optional() });
var BO = _({ ...c0.shape, ...R9.shape, uri: F(), description: D$(F()), mimeType: D$(F()), size: D$(z$()), annotations: d0.optional(), _meta: D$(d$({})) });
var BP = _({ ...c0.shape, ...R9.shape, uriTemplate: F(), description: D$(F()), mimeType: D$(F()), annotations: d0.optional(), _meta: D$(d$({})) });
var AQ = E9.extend({ method: g("resources/list") });
var qP = S9.extend({ resources: $$(BO) });
var IQ = E9.extend({ method: g("resources/templates/list") });
var LP = S9.extend({ resourceTemplates: $$(BP) });
var vG = j6.extend({ uri: F() });
var DP = vG;
var bQ = h$.extend({ method: g("resources/read"), params: DP });
var jP = u$.extend({ contents: $$(K$([OO, wO])) });
var FP = R6.extend({ method: g("notifications/resources/list_changed"), params: P6.optional() });
var MP = vG;
var AP = h$.extend({ method: g("resources/subscribe"), params: MP });
var IP = vG;
var bP = h$.extend({ method: g("resources/unsubscribe"), params: IP });
var ZP = P6.extend({ uri: F() });
var PP = R6.extend({ method: g("notifications/resources/updated"), params: ZP });
var RP = _({ name: F(), description: D$(F()), required: D$(v$()) });
var EP = _({ ...c0.shape, ...R9.shape, description: D$(F()), arguments: D$($$(RP)), _meta: D$(d$({})) });
var ZQ = E9.extend({ method: g("prompts/list") });
var SP = S9.extend({ prompts: $$(EP) });
var vP = j6.extend({ name: F(), arguments: V$(F(), F()).optional() });
var PQ = h$.extend({ method: g("prompts/get"), params: vP });
var CG = _({ type: g("text"), text: F(), annotations: d0.optional(), _meta: V$(F(), j$()).optional() });
var kG = _({ type: g("image"), data: SG, mimeType: F(), annotations: d0.optional(), _meta: V$(F(), j$()).optional() });
var _G = _({ type: g("audio"), data: SG, mimeType: F(), annotations: d0.optional(), _meta: V$(F(), j$()).optional() });
var CP = _({ type: g("tool_use"), name: F(), id: F(), input: V$(F(), j$()), _meta: V$(F(), j$()).optional() });
var kP = _({ type: g("resource"), resource: K$([OO, wO]), annotations: d0.optional(), _meta: V$(F(), j$()).optional() });
var _P = BO.extend({ type: g("resource_link") });
var xG = K$([CG, kG, _G, _P, kP]);
var xP = _({ role: k9, content: xG });
var TP = u$.extend({ description: F().optional(), messages: $$(xP) });
var yP = R6.extend({ method: g("notifications/prompts/list_changed"), params: P6.optional() });
var fP = _({ title: F().optional(), readOnlyHint: v$().optional(), destructiveHint: v$().optional(), idempotentHint: v$().optional(), openWorldHint: v$().optional() });
var gP = _({ taskSupport: a$(["required", "optional", "forbidden"]).optional() });
var qO = _({ ...c0.shape, ...R9.shape, description: F().optional(), inputSchema: _({ type: g("object"), properties: V$(F(), x$).optional(), required: $$(F()).optional() }).catchall(j$()), outputSchema: _({ type: g("object"), properties: V$(F(), x$).optional(), required: $$(F()).optional() }).catchall(j$()).optional(), annotations: fP.optional(), execution: gP.optional(), _meta: V$(F(), j$()).optional() });
var RQ = E9.extend({ method: g("tools/list") });
var hP = S9.extend({ tools: $$(qO) });
var EQ = u$.extend({ content: $$(xG).default([]), structuredContent: V$(F(), j$()).optional(), isError: v$().optional() });
var Dr = EQ.or(u$.extend({ toolResult: j$() }));
var uP = Z9.extend({ name: F(), arguments: V$(F(), j$()).optional() });
var i0 = h$.extend({ method: g("tools/call"), params: uP });
var mP = R6.extend({ method: g("notifications/tools/list_changed"), params: P6.optional() });
var jr = _({ autoRefresh: v$().default(true), debounceMs: z$().int().nonnegative().default(300) });
var _9 = a$(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
var lP = j6.extend({ level: _9 });
var TG = h$.extend({ method: g("logging/setLevel"), params: lP });
var cP = P6.extend({ level: _9, logger: F().optional(), data: j$() });
var pP = R6.extend({ method: g("notifications/message"), params: cP });
var dP = _({ name: F().optional() });
var iP = _({ hints: $$(dP).optional(), costPriority: z$().min(0).max(1).optional(), speedPriority: z$().min(0).max(1).optional(), intelligencePriority: z$().min(0).max(1).optional() });
var nP = _({ mode: a$(["auto", "required", "none"]).optional() });
var rP = _({ type: g("tool_result"), toolUseId: F().describe("The unique identifier for the corresponding tool call."), content: $$(xG).default([]), structuredContent: _({}).loose().optional(), isError: v$().optional(), _meta: V$(F(), j$()).optional() });
var oP = zQ("type", [CG, kG, _G]);
var HQ = zQ("type", [CG, kG, _G, CP, rP]);
var tP = _({ role: k9, content: K$([HQ, $$(HQ)]), _meta: V$(F(), j$()).optional() });
var aP = Z9.extend({ messages: $$(tP), modelPreferences: iP.optional(), systemPrompt: F().optional(), includeContext: a$(["none", "thisServer", "allServers"]).optional(), temperature: z$().optional(), maxTokens: z$().int(), stopSequences: $$(F()).optional(), metadata: x$.optional(), tools: $$(qO).optional(), toolChoice: nP.optional() });
var sP = h$.extend({ method: g("sampling/createMessage"), params: aP });
var x9 = u$.extend({ model: F(), stopReason: D$(a$(["endTurn", "stopSequence", "maxTokens"]).or(F())), role: k9, content: oP });
var yG = u$.extend({ model: F(), stopReason: D$(a$(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(F())), role: k9, content: K$([HQ, $$(HQ)]) });
var eP = _({ type: g("boolean"), title: F().optional(), description: F().optional(), default: v$().optional() });
var $R = _({ type: g("string"), title: F().optional(), description: F().optional(), minLength: z$().optional(), maxLength: z$().optional(), format: a$(["email", "uri", "date", "date-time"]).optional(), default: F().optional() });
var XR = _({ type: a$(["number", "integer"]), title: F().optional(), description: F().optional(), minimum: z$().optional(), maximum: z$().optional(), default: z$().optional() });
var JR = _({ type: g("string"), title: F().optional(), description: F().optional(), enum: $$(F()), default: F().optional() });
var YR = _({ type: g("string"), title: F().optional(), description: F().optional(), oneOf: $$(_({ const: F(), title: F() })), default: F().optional() });
var QR = _({ type: g("string"), title: F().optional(), description: F().optional(), enum: $$(F()), enumNames: $$(F()).optional(), default: F().optional() });
var WR = K$([JR, YR]);
var zR = _({ type: g("array"), title: F().optional(), description: F().optional(), minItems: z$().optional(), maxItems: z$().optional(), items: _({ type: g("string"), enum: $$(F()) }), default: $$(F()).optional() });
var GR = _({ type: g("array"), title: F().optional(), description: F().optional(), minItems: z$().optional(), maxItems: z$().optional(), items: _({ anyOf: $$(_({ const: F(), title: F() })) }), default: $$(F()).optional() });
var UR = K$([zR, GR]);
var HR = K$([QR, WR, UR]);
var KR = K$([HR, eP, $R, XR]);
var VR = Z9.extend({ mode: g("form").optional(), message: F(), requestedSchema: _({ type: g("object"), properties: V$(F(), KR), required: $$(F()).optional() }) });
var NR = Z9.extend({ mode: g("url"), message: F(), elicitationId: F(), url: F().url() });
var OR = K$([VR, NR]);
var wR = h$.extend({ method: g("elicitation/create"), params: OR });
var BR = P6.extend({ elicitationId: F() });
var qR = R6.extend({ method: g("notifications/elicitation/complete"), params: BR });
var n0 = u$.extend({ action: a$(["accept", "decline", "cancel"]), content: UQ(($) => $ === null ? void 0 : $, V$(F(), K$([F(), z$(), v$(), $$(F())])).optional()) });
var LR = _({ type: g("ref/resource"), uri: F() });
var DR = _({ type: g("ref/prompt"), name: F() });
var jR = j6.extend({ ref: K$([DR, LR]), argument: _({ name: F(), value: F() }), context: _({ arguments: V$(F(), F()).optional() }).optional() });
var SQ = h$.extend({ method: g("completion/complete"), params: jR });
var FR = u$.extend({ completion: d$({ values: $$(F()).max(100), total: D$(z$().int()), hasMore: D$(v$()) }) });
var MR = _({ uri: F().startsWith("file://"), name: F().optional(), _meta: V$(F(), j$()).optional() });
var AR = h$.extend({ method: g("roots/list"), params: j6.optional() });
var fG = u$.extend({ roots: $$(MR) });
var IR = R6.extend({ method: g("notifications/roots/list_changed"), params: P6.optional() });
var Fr = K$([wQ, RG, SQ, TG, PQ, ZQ, AQ, IQ, bQ, AP, bP, i0, RQ, qQ, DQ, jQ, MQ]);
var Mr = K$([OQ, BQ, EG, IR, C9]);
var Ar = K$([NQ, x9, yG, n0, fG, LQ, FQ, p0]);
var Ir = K$([wQ, sP, wR, AR, qQ, DQ, jQ, MQ]);
var br = K$([OQ, BQ, pP, PP, FP, mP, yP, C9, qR]);
var Zr = K$([NQ, HP, FR, TP, SP, qP, LP, jP, EQ, hP, LQ, FQ, p0]);
var PR = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");
var yD = qH(hU(), 1);
var fD = qH(TD(), 1);
var uD;
(function($) {
  $.Completable = "McpCompletable";
})(uD || (uD = {}));
function rD($) {
  let X;
  return () => X != null ? X : X = $();
}
var aT = rD(() => t4.object({ session_id: t4.string(), ws_url: t4.string(), work_dir: t4.string().optional(), session_key: t4.string().optional() }));
async function Uy($, X) {
  try {
    await (0, import_promises.copyFile)($, X);
  } catch (J) {
    if (!JX(J)) throw J;
  }
}
async function Hy($, X) {
  var _a3;
  if (!$) return;
  let J = $;
  try {
    let Q = o$($);
    if ((_a3 = Q == null ? void 0 : Q.claudeAiOauth) == null ? void 0 : _a3.refreshToken) delete Q.claudeAiOauth.refreshToken, J = q$(Q);
  } catch (e2) {
  }
  await (0, import_promises.writeFile)(X, J, { mode: 384 });
}
function Ky() {
  if (process.platform !== "darwin") return Promise.resolve(void 0);
  let $ = gV(fV);
  return new Promise((X) => {
    (0, import_child_process.execFile)("security", ["find-generic-password", "-a", hV(), "-w", "-s", $], { encoding: "utf-8", timeout: 5e3 }, (J, Q) => X(J ? void 0 : Q.trim() || void 0));
  });
}
async function Yj($, X, J, Q, Y = 6e4) {
  var _a3, _b2, _c, _d2;
  if (!N$(X)) return;
  let W = (0, import_path.resolve)(J != null ? J : "."), z8 = A1(W), G = await K1($.load({ projectKey: z8, sessionId: X }), Y, `SessionStore.load() timed out after ${Y}ms for session ${X}`);
  if (!G || G.length === 0) return;
  let U = (0, import_path.join)((0, import_os.tmpdir)(), `claude-resume-${(0, import_crypto.randomUUID)()}`);
  try {
    let H = (0, import_path.join)(U, "projects", z8);
    await (0, import_promises.mkdir)(H, { recursive: true });
    let K = (0, import_path.join)(H, `${X}.jsonl`);
    await GX(K, G);
    let V = (_a3 = Q == null ? void 0 : Q.CLAUDE_CONFIG_DIR) != null ? _a3 : process.env.CLAUDE_CONFIG_DIR, N = V != null ? V : (0, import_path.join)((0, import_os.homedir)(), ".claude"), O;
    try {
      O = await (0, import_promises.readFile)((0, import_path.join)(N, ".credentials.json"), "utf-8");
    } catch (w) {
      if (!JX(w)) throw w;
    }
    if (!V && !((_b2 = Q == null ? void 0 : Q.ANTHROPIC_API_KEY) != null ? _b2 : process.env.ANTHROPIC_API_KEY) && !((_c = Q == null ? void 0 : Q.CLAUDE_CODE_OAUTH_TOKEN) != null ? _c : process.env.CLAUDE_CODE_OAUTH_TOKEN)) O = (_d2 = await Ky()) != null ? _d2 : O;
    if (await Hy(O, (0, import_path.join)(U, ".credentials.json")), await Uy((0, import_path.join)(V != null ? V : (0, import_os.homedir)(), ".claude.json"), (0, import_path.join)(U, ".claude.json")), $.listSubkeys) {
      let w = (0, import_path.join)(H, X), B = await K1($.listSubkeys({ projectKey: z8, sessionId: X }), Y, `SessionStore.listSubkeys() timed out after ${Y}ms for session ${X}`);
      for (let D of B) {
        let j = (0, import_path.resolve)(w, D + ".jsonl");
        if (!D || (0, import_path.isAbsolute)(D) || D.split(/[\\/]/).includes("..") || !j.startsWith(w + import_path.sep)) {
          f$(`[SessionStore] skipping unsafe subpath from listSubkeys: ${D}`, { level: "warn" });
          continue;
        }
        let A = await K1($.load({ projectKey: z8, sessionId: X, subpath: D }), Y, `SessionStore.load() timed out after ${Y}ms for session ${X} subpath ${D}`);
        if (!A || A.length === 0) continue;
        let I = [], x = [];
        for (let T of A) if (Wj(T)) I.push(T);
        else x.push(T);
        if (x.length > 0) await (0, import_promises.mkdir)((0, import_path.dirname)(j), { recursive: true }), await GX(j, x);
        if (I.length > 0) {
          let T = I.at(-1), U$ = (0, import_path.resolve)(w, D + ".meta.json");
          await (0, import_promises.mkdir)((0, import_path.dirname)(U$), { recursive: true });
          let { type: T$, ...n$ } = T;
          await (0, import_promises.writeFile)(U$, q$(n$), { mode: 384 });
        }
      }
    }
    return U;
  } catch (H) {
    throw await q5(U), H;
  }
}
function WH($, X, J, Q) {
  var _a3;
  let { systemPrompt: Y, settings: W, settingSources: z8, sandbox: G, ...U } = $ != null ? $ : {}, H, K, V;
  if (Y === void 0) H = "";
  else if (typeof Y === "string") H = Y;
  else if (Array.isArray(Y)) H = Y;
  else if (Y.type === "preset") K = Y.append, V = Y.excludeDynamicSections;
  let N = U.pathToClaudeCodeExecutable;
  if (!N) {
    let n6 = (0, import_url.fileURLToPath)(import_meta.url), Q4 = (0, import_module.createRequire)(n6), p1 = lJ((V8) => Q4.resolve(V8));
    if (p1) N = p1;
    else try {
      N = Q4.resolve("./cli.js");
    } catch (e2) {
      throw Error(`Native CLI binary for ${process.platform}-${process.arch} not found. Reinstall @anthropic-ai/claude-agent-sdk without --omit=optional, or set options.pathToClaudeCodeExecutable.`);
    }
  }
  process.env.CLAUDE_AGENT_SDK_VERSION = "0.2.112";
  let { abortController: O = d1(), additionalDirectories: w = [], agent: B, agents: D, allowedTools: j = [], betas: A, canUseTool: I, continue: x, cwd: T, debug: U$, debugFile: T$, disallowedTools: n$ = [], tools: X4, env: X6, executable: U1 = i1() ? "bun" : "node", executableArgs: l1 = [], extraArgs: J4 = {}, fallbackModel: z82, enableFileCheckpointing: p, toolConfig: G8, forkSession: D5, hooks: c1, includeHookEvents: U8, includePartialMessages: H8, onElicitation: GJ, persistSession: l$, sessionStore: v6, thinking: Y4, effort: Gj, maxThinkingTokens: j5, maxTurns: Uj, maxBudgetUsd: Hj, taskBudget: Kj, mcpServers: UH, model: Vj, outputFormat: HH, permissionMode: Nj = "default", allowDangerouslySkipPermissions: Oj = false, permissionPromptToolName: wj, plugins: Bj, getOAuthToken: KH, workload: VH, resume: qj, resumeSessionAt: Lj, sessionId: Dj, stderr: jj, strictMcpConfig: Fj } = U;
  if (v6 && l$ === false) throw Error("sessionStore cannot be used with persistSession: false -- the storage adapter requires local writes to mirror from. Use CLAUDE_CONFIG_DIR=/tmp for ephemeral local writes with external mirroring.");
  let NH = (HH == null ? void 0 : HH.type) === "json_schema" ? HH.schema : void 0, F6 = { ...process.env, ...X6 != null ? X6 : {} };
  if (!(X6 == null ? void 0 : X6.CLAUDE_CODE_ENTRYPOINT)) F6.CLAUDE_CODE_ENTRYPOINT = "sdk-ts";
  if (p) F6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING = "true";
  else if (!(X6 == null ? void 0 : X6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING)) delete F6.CLAUDE_CODE_ENABLE_SDK_FILE_CHECKPOINTING;
  if (KH) F6.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH = "1";
  else if (!(X6 == null ? void 0 : X6.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH)) delete F6.CLAUDE_CODE_SDK_HAS_OAUTH_REFRESH;
  if ((_a3 = G8 == null ? void 0 : G8.askUserQuestion) == null ? void 0 : _a3.previewFormat) F6.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT = G8.askUserQuestion.previewFormat;
  else if (!(X6 == null ? void 0 : X6.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT)) delete F6.CLAUDE_CODE_QUESTION_PREVIEW_FORMAT;
  for (let n6 of ["GITHUB_ACTIONS", "CLAUDECODE", "CLAUDE_CODE_SESSION_ID", "CLAUDE_CODE_EXECPATH"]) if (!(X6 == null ? void 0 : X6[n6])) delete F6[n6];
  let OH = {}, wH = /* @__PURE__ */ new Map();
  if (UH) for (let [n6, Q4] of Object.entries(UH)) if (Q4.type === "sdk" && Q4.instance) wH.set(n6, Q4.instance);
  else OH[n6] = Q4;
  let K8;
  if (Y4) switch (Y4.type) {
    case "adaptive":
      K8 = { type: "adaptive", display: Y4.display };
      break;
    case "enabled":
      K8 = { type: "enabled", budgetTokens: Y4.budgetTokens, display: Y4.display };
      break;
    case "disabled":
      K8 = { type: "disabled" };
      break;
  }
  else if (j5 !== void 0) K8 = j5 === 0 ? { type: "disabled" } : { type: "enabled", budgetTokens: j5 };
  if (J) F6.CLAUDE_CONFIG_DIR = J;
  let BH = new QX({ abortController: O, additionalDirectories: w, agent: B, betas: A, cwd: T, debug: U$, debugFile: T$, executable: U1, executableArgs: l1, extraArgs: VH ? { ...J4, workload: VH } : J4, pathToClaudeCodeExecutable: N, env: F6, forkSession: D5, stderr: jj, thinkingConfig: K8, effort: Gj, maxTurns: Uj, maxBudgetUsd: Hj, taskBudget: Kj, model: Vj, fallbackModel: z82, jsonSchema: NH, permissionMode: Nj, allowDangerouslySkipPermissions: Oj, permissionPromptToolName: wj, continueConversation: x, resume: qj, resumeSessionAt: Lj, sessionId: Dj, settings: typeof W === "object" ? q$(W) : W, settingSources: z8, allowedTools: j, disallowedTools: n$, tools: X4, mcpServers: OH, strictMcpConfig: Fj, canUseTool: !!I, hooks: !!c1, includeHookEvents: U8, includePartialMessages: H8, persistSession: l$, sessionMirror: !!v6, plugins: Bj, sandbox: G, spawnClaudeCodeProcess: U.spawnClaudeCodeProcess, deferSpawn: Q }), Mj = { systemPrompt: H, appendSystemPrompt: K, appendSubagentSystemPrompt: U.appendSubagentSystemPrompt, excludeDynamicSections: V, agents: D, promptSuggestions: U.promptSuggestions, agentProgressSummaries: U.agentProgressSummaries }, F5 = new WX(BH, X, I, c1, O, wH, NH, Mj, GJ, KH);
  if (v6) {
    let n6 = () => {
      var _a4;
      return (0, import_path.join)((_a4 = F6.CLAUDE_CONFIG_DIR) != null ? _a4 : (0, import_path.join)((0, import_os.homedir)(), ".claude"), "projects");
    }, Q4 = new HW(async (p1, V8) => {
      let N8 = eD(p1, n6());
      if (N8) await v6.append(N8, V8);
    }, void 0, (p1, V8) => {
      let N8 = eD(p1, n6());
      if (N8) F5.reportMirrorError(N8, V8.message);
    });
    F5.setTranscriptMirrorBatcher(Q4);
  }
  return { queryInstance: F5, transport: BH, abortController: O, processEnv: F6 };
}
function zH($, X, J, Q) {
  if (typeof J === "string") X.write(q$({ type: "user", session_id: "", message: { role: "user", content: [{ type: "text", text: J }] }, parent_tool_use_id: null }) + `
`);
  else $.streamInput(J).catch((Y) => Q.abort(Y));
}
var Vy = /* @__PURE__ */ new Set(["EBUSY", "EMFILE", "ENFILE", "ENOTEMPTY", "EPERM"]);
async function q5($) {
  var _a3;
  for (let X = 0; ; X++) try {
    return await (0, import_promises.rm)($, { recursive: true, force: true });
  } catch (J) {
    if (X >= 4 || !Vy.has((_a3 = _6(J)) != null ? _a3 : "")) return;
    await LH((X + 1) * 100);
  }
}
function Ny($, X) {
  $.waitForExit().catch(() => {
  }).finally(() => q5(X));
}
function E$$({ prompt: $, options: X }) {
  var _a3;
  if ((X == null ? void 0 : X.resume) && (X == null ? void 0 : X.sessionStore)) {
    let { queryInstance: W, transport: z8, abortController: G, processEnv: U } = WH({ ...X }, typeof $ === "string", void 0, true), H = (0, import_path.resolve)((_a3 = X.cwd) != null ? _a3 : ".");
    return Yj(X.sessionStore, X.resume, H, X.env, X.loadTimeoutMs).then((V) => {
      if (V) z8.updateEnv({ CLAUDE_CONFIG_DIR: V }), U.CLAUDE_CONFIG_DIR = V, W.addCleanupCallback(() => Ny(z8, V));
      if (!W.isClosed()) z8.spawn();
    }).catch((V) => {
      let N = f4(V);
      z8.spawnAbort(N), W.setError(N);
    }), zH(W, z8, $, G), W;
  }
  let { queryInstance: J, transport: Q, abortController: Y } = WH(X, typeof $ === "string");
  return zH(J, Q, $, Y), J;
}
function Wj($) {
  return typeof $ === "object" && $ !== null && "type" in $ && $.type === "agent_metadata";
}
function eD($, X) {
  let J = (0, import_path.relative)(X, $);
  if (J.startsWith("..") || (0, import_path.isAbsolute)(J)) return null;
  let Q = J.split(import_path.sep);
  if (Q.length < 2) return null;
  let Y = Q[0], W = Q[1];
  if (Q.length === 2 && W.endsWith(".jsonl")) return { projectKey: Y, sessionId: W.replace(/\.jsonl$/, "") };
  if (Q.length >= 4) {
    let z8 = Q.slice(2), G = z8.length - 1;
    return z8[G] = z8.at(-1).replace(/\.jsonl$/, ""), { projectKey: Y, sessionId: W, subpath: z8.join("/") };
  }
  return null;
}

// src/providers/claude/commands/probeRuntimeCommands.ts
init_env();
init_path();

// src/providers/claude/runtime/customSpawn.ts
var import_child_process4 = require("child_process");
init_env();
function createCustomSpawnFunction(enhancedPath) {
  return (options) => {
    let { command } = options;
    const { args, cwd, env, signal } = options;
    const shouldPipeStderr = !!(env == null ? void 0 : env.DEBUG_CLAUDE_AGENT_SDK);
    if (command === "node") {
      const nodeFullPath = findNodeExecutable(enhancedPath);
      if (nodeFullPath) {
        command = nodeFullPath;
      }
    }
    const child = (0, import_child_process4.spawn)(command, args, {
      cwd,
      env,
      stdio: ["pipe", "pipe", shouldPipeStderr ? "pipe" : "ignore"],
      windowsHide: true
    });
    if (signal) {
      if (signal.aborted) {
        child.kill();
      } else {
        signal.addEventListener("abort", () => child.kill(), { once: true });
      }
    }
    if (shouldPipeStderr && child.stderr && typeof child.stderr.on === "function") {
      child.stderr.on("data", () => {
      });
    }
    if (!child.stdin || !child.stdout) {
      throw new Error("Failed to create process streams");
    }
    return child;
  };
}

// src/core/providers/providerConfig.ts
function isRecord2(value) {
  return !!value && typeof value === "object" && !Array.isArray(value);
}
function getProviderConfig(settings11, providerId) {
  const candidate = settings11.providerConfigs;
  if (!isRecord2(candidate)) {
    return {};
  }
  const config2 = candidate[providerId];
  return isRecord2(config2) ? { ...config2 } : {};
}
function setProviderConfig(settings11, providerId, config2) {
  const current = settings11.providerConfigs;
  const nextConfigs = isRecord2(current) ? { ...current } : {};
  nextConfigs[providerId] = { ...config2 };
  settings11.providerConfigs = nextConfigs;
}

// src/core/providers/providerEnvironment.ts
init_env();
var SHARED_ENVIRONMENT_KEYS = /* @__PURE__ */ new Set([
  "PATH",
  "HTTP_PROXY",
  "HTTPS_PROXY",
  "NO_PROXY",
  "ALL_PROXY",
  "SSL_CERT_FILE",
  "SSL_CERT_DIR",
  "REQUESTS_CA_BUNDLE",
  "CURL_CA_BUNDLE",
  "NODE_EXTRA_CA_CERTS",
  "TMPDIR",
  "TMP",
  "TEMP"
]);
function resolveScopeProviderId(scope) {
  return scope.startsWith("provider:") ? scope.slice("provider:".length) : null;
}
function classifyEnvironmentKey(key) {
  const normalized = key.trim().toUpperCase();
  if (!normalized) {
    return { type: "shared-unknown" };
  }
  if (SHARED_ENVIRONMENT_KEYS.has(normalized)) {
    return { type: "shared-known" };
  }
  for (const providerId of ProviderRegistry.getRegisteredProviderIds()) {
    const patterns = ProviderRegistry.getEnvironmentKeyPatterns(providerId);
    if (patterns.some((pattern) => pattern.test(normalized))) {
      return { type: "provider", providerId };
    }
  }
  return { type: "shared-unknown" };
}
function extractEnvironmentKey(line) {
  const trimmed = line.trim();
  if (!trimmed || trimmed.startsWith("#")) {
    return null;
  }
  const normalized = trimmed.startsWith("export ") ? trimmed.slice(7) : trimmed;
  const eqIndex = normalized.indexOf("=");
  if (eqIndex <= 0) {
    return null;
  }
  const key = normalized.slice(0, eqIndex).trim();
  return key || null;
}
function appendLines(target, pendingDecorators, line) {
  target.push(...pendingDecorators, line);
}
function createClassifiedEnvironmentLines() {
  return {
    shared: [],
    providers: {},
    reviewKeys: /* @__PURE__ */ new Set()
  };
}
function joinEnvironmentLines(lines) {
  return lines.join("\n");
}
function hasMeaningfulEnvironmentContent(envText) {
  return envText.split(/\r?\n/).some((line) => {
    const trimmed = line.trim();
    return trimmed.length > 0 && !trimmed.startsWith("#");
  });
}
function getLegacyEnvironmentClassification(settings11) {
  const legacyEnvironmentVariables = settings11.environmentVariables;
  if (typeof legacyEnvironmentVariables !== "string" || legacyEnvironmentVariables.length === 0) {
    return {
      shared: "",
      providers: {},
      reviewKeys: []
    };
  }
  return classifyEnvironmentVariablesByOwnership(legacyEnvironmentVariables);
}
function classifyEnvironmentVariablesByOwnership(input) {
  var _a3;
  const result = createClassifiedEnvironmentLines();
  let pendingDecorators = [];
  for (const line of input.split(/\r?\n/)) {
    const trimmed = line.trim();
    if (!trimmed || trimmed.startsWith("#")) {
      pendingDecorators.push(line);
      continue;
    }
    const key = extractEnvironmentKey(line);
    if (!key) {
      appendLines(result.shared, pendingDecorators, line);
      pendingDecorators = [];
      continue;
    }
    const ownership = classifyEnvironmentKey(key);
    if (ownership.type === "provider") {
      const target = (_a3 = result.providers[ownership.providerId]) != null ? _a3 : [];
      appendLines(target, pendingDecorators, line);
      result.providers[ownership.providerId] = target;
    } else {
      appendLines(result.shared, pendingDecorators, line);
      if (ownership.type === "shared-unknown") {
        result.reviewKeys.add(key);
      }
    }
    pendingDecorators = [];
  }
  if (pendingDecorators.length > 0) {
    result.shared.push(...pendingDecorators);
  }
  return {
    shared: joinEnvironmentLines(result.shared),
    providers: Object.fromEntries(
      Object.entries(result.providers).map(([providerId, lines]) => [
        providerId,
        joinEnvironmentLines(lines != null ? lines : [])
      ])
    ),
    reviewKeys: Array.from(result.reviewKeys)
  };
}
function getSharedEnvironmentVariables(settings11) {
  const sharedEnvironmentVariables = settings11.sharedEnvironmentVariables;
  if (typeof sharedEnvironmentVariables === "string") {
    return sharedEnvironmentVariables;
  }
  return getLegacyEnvironmentClassification(settings11).shared;
}
function setSharedEnvironmentVariables(settings11, envText) {
  settings11.sharedEnvironmentVariables = envText;
  delete settings11.environmentVariables;
}
function getProviderEnvironmentVariables(settings11, providerId) {
  var _a3;
  const providerConfig = getProviderConfig(settings11, providerId);
  if (typeof providerConfig.environmentVariables === "string") {
    return providerConfig.environmentVariables;
  }
  return (_a3 = getLegacyEnvironmentClassification(settings11).providers[providerId]) != null ? _a3 : "";
}
function setProviderEnvironmentVariables(settings11, providerId, envText) {
  setProviderConfig(settings11, providerId, {
    ...getProviderConfig(settings11, providerId),
    environmentVariables: envText
  });
  delete settings11.environmentVariables;
}
function joinEnvironmentTexts(...parts) {
  const filtered = parts.filter((part) => typeof part === "string" && part.length > 0);
  if (filtered.length === 0) {
    return "";
  }
  return filtered.reduce((combined, part) => {
    if (!combined) {
      return part;
    }
    return combined.endsWith("\n") ? `${combined}${part}` : `${combined}
${part}`;
  }, "");
}
function getRuntimeEnvironmentText(settings11, providerId) {
  return joinEnvironmentTexts(
    getSharedEnvironmentVariables(settings11),
    getProviderEnvironmentVariables(settings11, providerId)
  );
}
function getRuntimeEnvironmentVariables(settings11, providerId) {
  return parseEnvironmentVariables(getRuntimeEnvironmentText(settings11, providerId));
}
function getEnvironmentVariablesForScope(settings11, scope) {
  var _a3;
  if (scope === "shared") {
    return getSharedEnvironmentVariables(settings11);
  }
  return getProviderEnvironmentVariables(settings11, (_a3 = resolveScopeProviderId(scope)) != null ? _a3 : "");
}
function setEnvironmentVariablesForScope(settings11, scope, envText) {
  if (scope === "shared") {
    setSharedEnvironmentVariables(settings11, envText);
    return;
  }
  const providerId = resolveScopeProviderId(scope);
  if (!providerId) {
    return;
  }
  setProviderEnvironmentVariables(settings11, providerId, envText);
}
function getEnvironmentReviewKeysForScope(envText, scope) {
  const reviewKeys = /* @__PURE__ */ new Set();
  const expectedProviderId = resolveScopeProviderId(scope);
  for (const line of envText.split(/\r?\n/)) {
    const key = extractEnvironmentKey(line);
    if (!key || reviewKeys.has(key)) {
      continue;
    }
    const ownership = classifyEnvironmentKey(key);
    if (scope === "shared") {
      if (ownership.type !== "shared-known") {
        reviewKeys.add(key);
      }
      continue;
    }
    if (ownership.type !== "provider" || ownership.providerId !== expectedProviderId) {
      reviewKeys.add(key);
    }
  }
  return Array.from(reviewKeys);
}
function inferEnvironmentSnippetScope(envText) {
  const classified = classifyEnvironmentVariablesByOwnership(envText);
  const nonEmptyScopes = [];
  if (hasMeaningfulEnvironmentContent(classified.shared)) {
    nonEmptyScopes.push("shared");
  }
  for (const [providerId, providerEnv] of Object.entries(classified.providers)) {
    if (providerEnv && hasMeaningfulEnvironmentContent(providerEnv)) {
      nonEmptyScopes.push(`provider:${providerId}`);
    }
  }
  return nonEmptyScopes.length === 1 ? nonEmptyScopes[0] : void 0;
}
function resolveEnvironmentSnippetScope(envText, fallbackScope) {
  const inferredScope = inferEnvironmentSnippetScope(envText);
  if (inferredScope) {
    return inferredScope;
  }
  return hasMeaningfulEnvironmentContent(envText) ? void 0 : fallbackScope;
}
function getEnvironmentScopeUpdates(envText, fallbackScope) {
  const classified = classifyEnvironmentVariablesByOwnership(envText);
  const updates = [];
  if (classified.shared.trim()) {
    updates.push({ scope: "shared", envText: classified.shared });
  }
  for (const [providerId, providerEnv] of Object.entries(classified.providers)) {
    if (!providerEnv || !providerEnv.trim()) {
      continue;
    }
    updates.push({
      scope: `provider:${providerId}`,
      envText: providerEnv
    });
  }
  if (updates.length > 0) {
    return updates;
  }
  if (fallbackScope) {
    return [{ scope: fallbackScope, envText }];
  }
  return [];
}

// src/providers/claude/settings.ts
var CLAUDE_SAFE_MODES = ["acceptEdits", "auto", "default"];
var DEFAULT_CLAUDE_PROVIDER_SETTINGS = Object.freeze({
  safeMode: "acceptEdits",
  cliPath: "",
  cliPathsByHost: {},
  loadUserSettings: true,
  enableChrome: false,
  enableBangBash: false,
  enableOpus1M: false,
  enableSonnet1M: false,
  customModels: "",
  lastModel: "haiku",
  environmentVariables: "",
  environmentHash: ""
});
function normalizeHostnameCliPaths(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return {};
  }
  const result = {};
  for (const [key, entry] of Object.entries(value)) {
    if (typeof entry === "string" && entry.trim()) {
      result[key] = entry.trim();
    }
  }
  return result;
}
function normalizeClaudeSafeMode(value) {
  return CLAUDE_SAFE_MODES.includes(value) ? value : void 0;
}
function getClaudeProviderSettings(settings11) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l, _m, _n, _o, _p2, _q, _r, _s, _t, _u, _v;
  const config2 = getProviderConfig(settings11, "claude");
  return {
    safeMode: (_b2 = (_a3 = normalizeClaudeSafeMode(config2.safeMode)) != null ? _a3 : normalizeClaudeSafeMode(settings11.claudeSafeMode)) != null ? _b2 : DEFAULT_CLAUDE_PROVIDER_SETTINGS.safeMode,
    cliPath: (_d2 = (_c = config2.cliPath) != null ? _c : settings11.claudeCliPath) != null ? _d2 : DEFAULT_CLAUDE_PROVIDER_SETTINGS.cliPath,
    cliPathsByHost: normalizeHostnameCliPaths((_e = config2.cliPathsByHost) != null ? _e : settings11.claudeCliPathsByHost),
    loadUserSettings: (_g = (_f = config2.loadUserSettings) != null ? _f : settings11.loadUserClaudeSettings) != null ? _g : DEFAULT_CLAUDE_PROVIDER_SETTINGS.loadUserSettings,
    enableChrome: (_i = (_h = config2.enableChrome) != null ? _h : settings11.enableChrome) != null ? _i : DEFAULT_CLAUDE_PROVIDER_SETTINGS.enableChrome,
    enableBangBash: (_k = (_j2 = config2.enableBangBash) != null ? _j2 : settings11.enableBangBash) != null ? _k : DEFAULT_CLAUDE_PROVIDER_SETTINGS.enableBangBash,
    enableOpus1M: (_m = (_l = config2.enableOpus1M) != null ? _l : settings11.enableOpus1M) != null ? _m : DEFAULT_CLAUDE_PROVIDER_SETTINGS.enableOpus1M,
    enableSonnet1M: (_o = (_n = config2.enableSonnet1M) != null ? _n : settings11.enableSonnet1M) != null ? _o : DEFAULT_CLAUDE_PROVIDER_SETTINGS.enableSonnet1M,
    customModels: (_p2 = config2.customModels) != null ? _p2 : DEFAULT_CLAUDE_PROVIDER_SETTINGS.customModels,
    lastModel: (_r = (_q = config2.lastModel) != null ? _q : settings11.lastClaudeModel) != null ? _r : DEFAULT_CLAUDE_PROVIDER_SETTINGS.lastModel,
    environmentVariables: (_t = (_s = config2.environmentVariables) != null ? _s : getProviderEnvironmentVariables(settings11, "claude")) != null ? _t : DEFAULT_CLAUDE_PROVIDER_SETTINGS.environmentVariables,
    environmentHash: (_v = (_u = config2.environmentHash) != null ? _u : settings11.lastEnvHash) != null ? _v : DEFAULT_CLAUDE_PROVIDER_SETTINGS.environmentHash
  };
}
function updateClaudeProviderSettings(settings11, updates) {
  var _a3;
  const current = getClaudeProviderSettings(settings11);
  const next = {
    ...current,
    ...updates,
    safeMode: "safeMode" in updates ? (_a3 = normalizeClaudeSafeMode(updates.safeMode)) != null ? _a3 : current.safeMode : current.safeMode
  };
  setProviderConfig(settings11, "claude", next);
  return next;
}

// src/providers/claude/commands/probeRuntimeCommands.ts
function mapSdkCommands(sdkCommands) {
  return sdkCommands.map((cmd) => ({
    id: `sdk:${cmd.name}`,
    name: cmd.name,
    description: cmd.description,
    argumentHint: cmd.argumentHint,
    content: "",
    source: "sdk"
  }));
}
async function probeRuntimeCommands(plugin) {
  const vaultPath = getVaultPath(plugin.app);
  if (!vaultPath) return [];
  const cliPath = plugin.getResolvedProviderCliPath("claude");
  if (!cliPath) return [];
  const customEnv = parseEnvironmentVariables(
    plugin.getActiveEnvironmentVariables("claude")
  );
  const enhancedPath = getEnhancedPath(customEnv.PATH, cliPath);
  const claudeSettings = getClaudeProviderSettings(
    plugin.settings
  );
  const abortController = new AbortController();
  let commands = [];
  const extraArgs = {
    ...claudeSettings.safeMode === "auto" ? { "enable-auto-mode": null } : {},
    ...claudeSettings.enableChrome ? { chrome: null } : {}
  };
  try {
    const conversation = E$$({
      prompt: "",
      options: {
        cwd: vaultPath,
        abortController,
        pathToClaudeCodeExecutable: cliPath,
        env: { ...process.env, ...customEnv, PATH: enhancedPath },
        permissionMode: "bypassPermissions",
        allowDangerouslySkipPermissions: true,
        settingSources: claudeSettings.loadUserSettings ? ["user", "project"] : ["project"],
        ...Object.keys(extraArgs).length > 0 ? { extraArgs } : {},
        spawnClaudeCodeProcess: createCustomSpawnFunction(enhancedPath),
        persistSession: false
      }
    });
    for await (const event of conversation) {
      if (event.type === "system" && event.subtype === "init") {
        try {
          const sdkCommands = await conversation.supportedCommands();
          commands = mapSdkCommands(sdkCommands);
        } catch (e2) {
        }
        abortController.abort();
        break;
      }
    }
  } catch (e2) {
  }
  return commands;
}

// src/providers/claude/plugins/PluginManager.ts
var fs5 = __toESM(require("fs"));
var import_obsidian2 = require("obsidian");
var os5 = __toESM(require("os"));
var path5 = __toESM(require("path"));
var INSTALLED_PLUGINS_PATH = path5.join(os5.homedir(), ".claude", "plugins", "installed_plugins.json");
var GLOBAL_SETTINGS_PATH = path5.join(os5.homedir(), ".claude", "settings.json");
function readJsonFile(filePath) {
  try {
    if (!fs5.existsSync(filePath)) {
      return null;
    }
    const content = fs5.readFileSync(filePath, "utf-8");
    return JSON.parse(content);
  } catch (e2) {
    return null;
  }
}
function normalizePathForComparison2(p) {
  try {
    const resolved = fs5.realpathSync(p);
    if (typeof resolved === "string" && resolved.length > 0) {
      return resolved;
    }
  } catch (e2) {
  }
  return path5.resolve(p);
}
function selectInstalledPluginEntry(entries, normalizedVaultPath) {
  var _a3;
  for (const entry of entries) {
    if (entry.scope !== "project") continue;
    if (!entry.projectPath) continue;
    if (normalizePathForComparison2(entry.projectPath) === normalizedVaultPath) {
      return entry;
    }
  }
  return (_a3 = entries.find((e2) => e2.scope === "user")) != null ? _a3 : null;
}
function extractPluginName(pluginId) {
  const atIndex = pluginId.indexOf("@");
  if (atIndex > 0) {
    return pluginId.substring(0, atIndex);
  }
  return pluginId;
}
var PluginManager = class {
  constructor(vaultPath, ccSettingsStorage) {
    this.plugins = [];
    this.vaultPath = vaultPath;
    this.ccSettingsStorage = ccSettingsStorage;
  }
  async loadPlugins() {
    var _a3, _b2, _c, _d2;
    const installedPlugins = readJsonFile(INSTALLED_PLUGINS_PATH);
    const globalSettings = readJsonFile(GLOBAL_SETTINGS_PATH);
    const projectSettings = await this.loadProjectSettings();
    const globalEnabled = (_a3 = globalSettings == null ? void 0 : globalSettings.enabledPlugins) != null ? _a3 : {};
    const projectEnabled = (_b2 = projectSettings == null ? void 0 : projectSettings.enabledPlugins) != null ? _b2 : {};
    const plugins = [];
    const normalizedVaultPath = normalizePathForComparison2(this.vaultPath);
    if (installedPlugins == null ? void 0 : installedPlugins.plugins) {
      for (const [pluginId, entries] of Object.entries(installedPlugins.plugins)) {
        if (!entries || entries.length === 0) continue;
        const entriesArray = Array.isArray(entries) ? entries : [entries];
        if (!Array.isArray(entries)) {
          new import_obsidian2.Notice(`Claudian: plugin "${pluginId}" has malformed entry in installed_plugins.json (expected array, got ${typeof entries})`);
        }
        const entry = selectInstalledPluginEntry(entriesArray, normalizedVaultPath);
        if (!entry) continue;
        const scope = entry.scope === "project" ? "project" : "user";
        const enabled = (_d2 = (_c = projectEnabled[pluginId]) != null ? _c : globalEnabled[pluginId]) != null ? _d2 : true;
        plugins.push({
          id: pluginId,
          name: extractPluginName(pluginId),
          enabled,
          scope,
          installPath: entry.installPath
        });
      }
    }
    this.plugins = plugins.sort((a2, b10) => {
      if (a2.scope !== b10.scope) {
        return a2.scope === "project" ? -1 : 1;
      }
      return a2.id.localeCompare(b10.id);
    });
  }
  async loadProjectSettings() {
    const projectSettingsPath = path5.join(this.vaultPath, ".claude", "settings.json");
    return readJsonFile(projectSettingsPath);
  }
  getPlugins() {
    return [...this.plugins];
  }
  hasPlugins() {
    return this.plugins.length > 0;
  }
  hasEnabledPlugins() {
    return this.plugins.some((p) => p.enabled);
  }
  getEnabledCount() {
    return this.plugins.filter((p) => p.enabled).length;
  }
  /** Used to detect changes that require restarting the persistent query. */
  getPluginsKey() {
    const enabledPlugins = this.plugins.filter((p) => p.enabled).sort((a2, b10) => a2.id.localeCompare(b10.id));
    if (enabledPlugins.length === 0) {
      return "";
    }
    return enabledPlugins.map((p) => `${p.id}:${p.installPath}`).join("|");
  }
  /** Writes to project .claude/settings.json so CLI respects the state. */
  async togglePlugin(pluginId) {
    const plugin = this.plugins.find((p) => p.id === pluginId);
    if (!plugin) {
      return;
    }
    const newEnabled = !plugin.enabled;
    plugin.enabled = newEnabled;
    await this.ccSettingsStorage.setPluginEnabled(pluginId, newEnabled);
  }
  async enablePlugin(pluginId) {
    const plugin = this.plugins.find((p) => p.id === pluginId);
    if (!plugin || plugin.enabled) {
      return;
    }
    plugin.enabled = true;
    await this.ccSettingsStorage.setPluginEnabled(pluginId, true);
  }
  async disablePlugin(pluginId) {
    const plugin = this.plugins.find((p) => p.id === pluginId);
    if (!plugin || !plugin.enabled) {
      return;
    }
    plugin.enabled = false;
    await this.ccSettingsStorage.setPluginEnabled(pluginId, false);
  }
};

// src/providers/claude/runtime/ClaudeCliResolver.ts
var fs7 = __toESM(require("fs"));
init_env();
init_path();

// src/providers/claude/cli/findClaudeCLIPath.ts
var fs6 = __toESM(require("fs"));
var os6 = __toESM(require("os"));
var path6 = __toESM(require("path"));
init_path();
function getEnvValue2(name) {
  return process.env[name];
}
function dedupePaths(entries) {
  const seen = /* @__PURE__ */ new Set();
  return entries.filter((entry) => {
    const key = process.platform === "win32" ? entry.toLowerCase() : entry;
    if (seen.has(key)) return false;
    seen.add(key);
    return true;
  });
}
function findFirstExistingPath(entries, candidates) {
  for (const dir of entries) {
    if (!dir) continue;
    for (const candidate of candidates) {
      const fullPath = path6.join(dir, candidate);
      if (isExistingFile(fullPath)) {
        return fullPath;
      }
    }
  }
  return null;
}
function isExistingFile(filePath) {
  try {
    if (fs6.existsSync(filePath)) {
      const stat = fs6.statSync(filePath);
      return stat.isFile();
    }
  } catch (e2) {
  }
  return false;
}
function resolveCliJsNearPathEntry(entry, isWindows2) {
  const directCandidate = path6.join(entry, "node_modules", "@anthropic-ai", "claude-code", "cli.js");
  if (isExistingFile(directCandidate)) {
    return directCandidate;
  }
  const baseName = path6.basename(entry).toLowerCase();
  if (baseName === "bin") {
    const prefix = path6.dirname(entry);
    const candidate = isWindows2 ? path6.join(prefix, "node_modules", "@anthropic-ai", "claude-code", "cli.js") : path6.join(prefix, "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js");
    if (isExistingFile(candidate)) {
      return candidate;
    }
  }
  return null;
}
function resolveCliJsFromPathEntries(entries, isWindows2) {
  for (const entry of entries) {
    const candidate = resolveCliJsNearPathEntry(entry, isWindows2);
    if (candidate) {
      return candidate;
    }
  }
  return null;
}
function resolveClaudeFromPathEntries(entries, isWindows2) {
  if (entries.length === 0) {
    return null;
  }
  if (!isWindows2) {
    const unixCandidate = findFirstExistingPath(entries, ["claude"]);
    return unixCandidate;
  }
  const exeCandidate = findFirstExistingPath(entries, ["claude.exe", "claude"]);
  if (exeCandidate) {
    return exeCandidate;
  }
  const cliJsCandidate = resolveCliJsFromPathEntries(entries, isWindows2);
  if (cliJsCandidate) {
    return cliJsCandidate;
  }
  return null;
}
function getNpmGlobalPrefix() {
  if (process.env.npm_config_prefix) {
    return process.env.npm_config_prefix;
  }
  if (process.platform === "win32") {
    const appDataNpm = process.env.APPDATA ? path6.join(process.env.APPDATA, "npm") : null;
    if (appDataNpm && fs6.existsSync(appDataNpm)) {
      return appDataNpm;
    }
  }
  return null;
}
function getNpmCliJsPaths() {
  const homeDir = os6.homedir();
  const isWindows2 = process.platform === "win32";
  const cliJsPaths = [];
  if (isWindows2) {
    cliJsPaths.push(
      path6.join(homeDir, "AppData", "Roaming", "npm", "node_modules", "@anthropic-ai", "claude-code", "cli.js")
    );
    const npmPrefix = getNpmGlobalPrefix();
    if (npmPrefix) {
      cliJsPaths.push(
        path6.join(npmPrefix, "node_modules", "@anthropic-ai", "claude-code", "cli.js")
      );
    }
    const programFiles = process.env.ProgramFiles || "C:\\Program Files";
    const programFilesX86 = process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)";
    cliJsPaths.push(
      path6.join(programFiles, "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js"),
      path6.join(programFilesX86, "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js")
    );
    cliJsPaths.push(
      path6.join("D:", "Program Files", "nodejs", "node_global", "node_modules", "@anthropic-ai", "claude-code", "cli.js")
    );
  } else {
    cliJsPaths.push(
      path6.join(homeDir, ".npm-global", "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js"),
      "/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js",
      "/usr/lib/node_modules/@anthropic-ai/claude-code/cli.js"
    );
    if (process.env.npm_config_prefix) {
      cliJsPaths.push(
        path6.join(process.env.npm_config_prefix, "lib", "node_modules", "@anthropic-ai", "claude-code", "cli.js")
      );
    }
  }
  return cliJsPaths;
}
function findClaudeCLIPath(pathValue) {
  const homeDir = os6.homedir();
  const isWindows2 = process.platform === "win32";
  const customEntries = dedupePaths(parsePathEntries(pathValue));
  if (customEntries.length > 0) {
    const customResolution = resolveClaudeFromPathEntries(customEntries, isWindows2);
    if (customResolution) {
      return customResolution;
    }
  }
  if (isWindows2) {
    const exePaths = [
      path6.join(homeDir, ".claude", "local", "claude.exe"),
      path6.join(homeDir, "AppData", "Local", "Claude", "claude.exe"),
      path6.join(process.env.ProgramFiles || "C:\\Program Files", "Claude", "claude.exe"),
      path6.join(process.env["ProgramFiles(x86)"] || "C:\\Program Files (x86)", "Claude", "claude.exe"),
      path6.join(homeDir, ".local", "bin", "claude.exe")
    ];
    for (const p of exePaths) {
      if (isExistingFile(p)) {
        return p;
      }
    }
    const cliJsPaths = getNpmCliJsPaths();
    for (const p of cliJsPaths) {
      if (isExistingFile(p)) {
        return p;
      }
    }
  }
  const commonPaths = [
    path6.join(homeDir, ".claude", "local", "claude"),
    path6.join(homeDir, ".local", "bin", "claude"),
    path6.join(homeDir, ".volta", "bin", "claude"),
    path6.join(homeDir, ".asdf", "shims", "claude"),
    path6.join(homeDir, ".asdf", "bin", "claude"),
    "/usr/local/bin/claude",
    "/opt/homebrew/bin/claude",
    path6.join(homeDir, "bin", "claude"),
    path6.join(homeDir, ".npm-global", "bin", "claude")
  ];
  const npmPrefix = getNpmGlobalPrefix();
  if (npmPrefix) {
    commonPaths.push(path6.join(npmPrefix, "bin", "claude"));
  }
  const nvmBin = resolveNvmDefaultBin(homeDir);
  if (nvmBin) {
    commonPaths.push(path6.join(nvmBin, "claude"));
  }
  for (const p of commonPaths) {
    if (isExistingFile(p)) {
      return p;
    }
  }
  if (!isWindows2) {
    const cliJsPaths = getNpmCliJsPaths();
    for (const p of cliJsPaths) {
      if (isExistingFile(p)) {
        return p;
      }
    }
  }
  const envEntries = dedupePaths(parsePathEntries(getEnvValue2("PATH")));
  if (envEntries.length > 0) {
    const envResolution = resolveClaudeFromPathEntries(envEntries, isWindows2);
    if (envResolution) {
      return envResolution;
    }
  }
  return null;
}

// src/providers/claude/runtime/ClaudeCliResolver.ts
var ClaudeCliResolver = class {
  constructor() {
    this.resolvedPath = null;
    this.lastHostnamePath = "";
    this.lastLegacyPath = "";
    this.lastEnvText = "";
    this.cachedHostname = getHostnameKey();
  }
  /**
   * Resolves CLI path with priority: hostname-specific -> legacy -> auto-detect.
   * @param settings Full app settings bag
   */
  resolveFromSettings(settings11) {
    var _a3;
    const hostnameKey = this.cachedHostname;
    const claudeSettings = getClaudeProviderSettings(settings11);
    const hostnamePath = ((_a3 = claudeSettings.cliPathsByHost[hostnameKey]) != null ? _a3 : "").trim();
    const normalizedLegacy = claudeSettings.cliPath.trim();
    const normalizedEnv = getRuntimeEnvironmentText(settings11, "claude");
    if (this.resolvedPath && hostnamePath === this.lastHostnamePath && normalizedLegacy === this.lastLegacyPath && normalizedEnv === this.lastEnvText) {
      return this.resolvedPath;
    }
    this.lastHostnamePath = hostnamePath;
    this.lastLegacyPath = normalizedLegacy;
    this.lastEnvText = normalizedEnv;
    this.resolvedPath = resolveClaudeCliPath(hostnamePath, normalizedLegacy, normalizedEnv);
    return this.resolvedPath;
  }
  resolve(hostnamePaths, legacyPath, envText) {
    return this.resolveFromSettings({
      sharedEnvironmentVariables: envText,
      providerConfigs: {
        claude: {
          cliPath: legacyPath != null ? legacyPath : "",
          cliPathsByHost: hostnamePaths != null ? hostnamePaths : {}
        }
      }
    });
  }
  reset() {
    this.resolvedPath = null;
    this.lastHostnamePath = "";
    this.lastLegacyPath = "";
    this.lastEnvText = "";
  }
};
function resolveConfiguredPath(rawPath) {
  const trimmed = (rawPath != null ? rawPath : "").trim();
  if (!trimmed) return null;
  try {
    const expanded = expandHomePath(trimmed);
    if (fs7.existsSync(expanded) && fs7.statSync(expanded).isFile()) {
      return expanded;
    }
  } catch (e2) {
  }
  return null;
}
function resolveClaudeCliPath(hostnamePath, legacyPath, envText) {
  var _a3, _b2;
  return (_b2 = (_a3 = resolveConfiguredPath(hostnamePath)) != null ? _a3 : resolveConfiguredPath(legacyPath)) != null ? _b2 : findClaudeCLIPath(parseEnvironmentVariables(envText || "").PATH);
}

// src/providers/claude/storage/StorageService.ts
var import_obsidian3 = require("obsidian");

// src/core/bootstrap/StoragePaths.ts
var CLAUDIAN_STORAGE_PATH = ".claudian";
var LEGACY_CLAUDIAN_SETTINGS_PATH = ".claude/claudian-settings.json";
var CLAUDIAN_SETTINGS_PATH = `${CLAUDIAN_STORAGE_PATH}/claudian-settings.json`;
var LEGACY_SESSIONS_PATH = ".claude/sessions";
var SESSIONS_PATH = `${CLAUDIAN_STORAGE_PATH}/sessions`;

// src/core/providers/commands/hiddenCommands.ts
function normalizeHiddenCommandName(value) {
  return value.trim().replace(/^[/$]+/, "");
}
function normalizeHiddenCommandList(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  const seen = /* @__PURE__ */ new Set();
  const normalized = [];
  for (const item of value) {
    if (typeof item !== "string") {
      continue;
    }
    const commandName = normalizeHiddenCommandName(item);
    if (!commandName) {
      continue;
    }
    const key = commandName.toLowerCase();
    if (seen.has(key)) {
      continue;
    }
    seen.add(key);
    normalized.push(commandName);
  }
  return normalized;
}
function getDefaultHiddenProviderCommands() {
  return {};
}
function normalizeHiddenProviderCommands(value) {
  if (!value || typeof value !== "object") {
    return getDefaultHiddenProviderCommands();
  }
  const candidate = value;
  const normalized = {};
  for (const [providerId, commands] of Object.entries(candidate)) {
    const next = normalizeHiddenCommandList(commands);
    if (next.length > 0) {
      normalized[providerId] = next;
    }
  }
  return normalized;
}
function getHiddenProviderCommands(settings11, providerId) {
  var _a3, _b2;
  return (_b2 = (_a3 = settings11.hiddenProviderCommands) == null ? void 0 : _a3[providerId]) != null ? _b2 : [];
}
function getHiddenProviderCommandSet(settings11, providerId) {
  return new Set(getHiddenProviderCommands(settings11, providerId).map((command) => command.toLowerCase()));
}

// src/providers/codex/settings.ts
init_env();

// src/providers/codex/types/models.ts
var CODEX_SPARK_MODEL = "gpt-5.3-codex-spark";
var DEFAULT_CODEX_MINI_MODEL = "gpt-5.4-mini";
var DEFAULT_CODEX_PRIMARY_MODEL = "gpt-5.5";
var FAST_TIER_CODEX_MODEL = DEFAULT_CODEX_PRIMARY_MODEL;
function formatCodexModelSuffix(suffix) {
  return suffix.split("-").filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1).toLowerCase()).join(" ");
}
function formatCodexModelLabel(model) {
  const match = model.match(/^gpt-([^-]+)(?:-(.+))?$/i);
  if (!match) {
    return model;
  }
  const [, version2, suffix] = match;
  return `GPT-${version2}${suffix ? ` ${formatCodexModelSuffix(suffix)}` : ""}`;
}
function createCodexModelOption(model, description) {
  return {
    value: model,
    label: formatCodexModelLabel(model),
    description
  };
}
var DEFAULT_CODEX_MINI_MODEL_LABEL = formatCodexModelLabel(DEFAULT_CODEX_MINI_MODEL);
var DEFAULT_CODEX_PRIMARY_MODEL_LABEL = formatCodexModelLabel(DEFAULT_CODEX_PRIMARY_MODEL);
var FAST_TIER_CODEX_MODEL_LABEL = formatCodexModelLabel(FAST_TIER_CODEX_MODEL);
var FAST_TIER_CODEX_DESCRIPTION = `Enable ${FAST_TIER_CODEX_MODEL_LABEL} fast mode for this conversation. Faster responses use more credits.`;
var DEFAULT_CODEX_MODELS = [
  createCodexModelOption(DEFAULT_CODEX_MINI_MODEL, "Fast"),
  createCodexModelOption(DEFAULT_CODEX_PRIMARY_MODEL, "Latest")
];
var DEFAULT_CODEX_MODEL_SET = new Set(DEFAULT_CODEX_MODELS.map((model) => model.value));

// src/providers/codex/settings.ts
function normalizeCodexInstallationMethod(value) {
  return value === "wsl" ? "wsl" : "native-windows";
}
function normalizeOptionalString(value) {
  return typeof value === "string" ? value.trim() : "";
}
var DEFAULT_CODEX_PROVIDER_SETTINGS = Object.freeze({
  enabled: false,
  safeMode: "workspace-write",
  cliPath: "",
  cliPathsByHost: {},
  customModels: "",
  reasoningSummary: "detailed",
  environmentVariables: "",
  environmentHash: "",
  installationMethod: "native-windows",
  installationMethodsByHost: {},
  wslDistroOverride: "",
  wslDistroOverridesByHost: {}
});
function shouldDisableCodexReasoningSummary(model) {
  return model === CODEX_SPARK_MODEL;
}
function getEffectiveCodexReasoningSummary(settings11, model) {
  if (shouldDisableCodexReasoningSummary(model)) {
    return "none";
  }
  return getCodexProviderSettings(settings11).reasoningSummary;
}
function applyCodexModelDefaults(model, settings11) {
  if (shouldDisableCodexReasoningSummary(model)) {
    updateCodexProviderSettings(settings11, { reasoningSummary: "none" });
  }
}
function normalizeHostnameCliPaths2(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return {};
  }
  const result = {};
  for (const [key, entry] of Object.entries(value)) {
    if (typeof entry === "string" && entry.trim()) {
      result[key] = entry.trim();
    }
  }
  return result;
}
function normalizeInstallationMethodsByHost(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return {};
  }
  const result = {};
  for (const [key, entry] of Object.entries(value)) {
    if (typeof key === "string" && key.trim()) {
      result[key] = normalizeCodexInstallationMethod(entry);
    }
  }
  return result;
}
function getCodexProviderSettings(settings11) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l, _m, _n, _o, _p2;
  const config2 = getProviderConfig(settings11, "codex");
  const hostnameKey = getHostnameKey();
  const installationMethodsByHost = normalizeInstallationMethodsByHost(config2.installationMethodsByHost);
  const wslDistroOverridesByHost = normalizeHostnameCliPaths2(config2.wslDistroOverridesByHost);
  const hasHostScopedInstallationMethods = Object.keys(installationMethodsByHost).length > 0;
  const hasHostScopedWslDistroOverrides = Object.keys(wslDistroOverridesByHost).length > 0;
  const legacyInstallationMethod = normalizeCodexInstallationMethod(config2.installationMethod);
  const legacyWslDistroOverride = normalizeOptionalString(config2.wslDistroOverride);
  return {
    enabled: (_b2 = (_a3 = config2.enabled) != null ? _a3 : settings11.codexEnabled) != null ? _b2 : DEFAULT_CODEX_PROVIDER_SETTINGS.enabled,
    safeMode: (_d2 = (_c = config2.safeMode) != null ? _c : settings11.codexSafeMode) != null ? _d2 : DEFAULT_CODEX_PROVIDER_SETTINGS.safeMode,
    cliPath: (_f = (_e = config2.cliPath) != null ? _e : settings11.codexCliPath) != null ? _f : DEFAULT_CODEX_PROVIDER_SETTINGS.cliPath,
    cliPathsByHost: normalizeHostnameCliPaths2((_g = config2.cliPathsByHost) != null ? _g : settings11.codexCliPathsByHost),
    customModels: (_h = config2.customModels) != null ? _h : DEFAULT_CODEX_PROVIDER_SETTINGS.customModels,
    reasoningSummary: (_j2 = (_i = config2.reasoningSummary) != null ? _i : settings11.codexReasoningSummary) != null ? _j2 : DEFAULT_CODEX_PROVIDER_SETTINGS.reasoningSummary,
    environmentVariables: (_l = (_k = config2.environmentVariables) != null ? _k : getProviderEnvironmentVariables(settings11, "codex")) != null ? _l : DEFAULT_CODEX_PROVIDER_SETTINGS.environmentVariables,
    environmentHash: (_n = (_m = config2.environmentHash) != null ? _m : settings11.lastCodexEnvHash) != null ? _n : DEFAULT_CODEX_PROVIDER_SETTINGS.environmentHash,
    installationMethod: (_o = installationMethodsByHost[hostnameKey]) != null ? _o : hasHostScopedInstallationMethods ? DEFAULT_CODEX_PROVIDER_SETTINGS.installationMethod : legacyInstallationMethod,
    installationMethodsByHost,
    wslDistroOverride: (_p2 = wslDistroOverridesByHost[hostnameKey]) != null ? _p2 : hasHostScopedWslDistroOverrides ? DEFAULT_CODEX_PROVIDER_SETTINGS.wslDistroOverride : legacyWslDistroOverride,
    wslDistroOverridesByHost
  };
}
function updateCodexProviderSettings(settings11, updates) {
  var _a3, _b2;
  const current = getCodexProviderSettings(settings11);
  const hostnameKey = getHostnameKey();
  const installationMethodsByHost = "installationMethodsByHost" in updates ? normalizeInstallationMethodsByHost(updates.installationMethodsByHost) : { ...current.installationMethodsByHost };
  const wslDistroOverridesByHost = "wslDistroOverridesByHost" in updates ? normalizeHostnameCliPaths2(updates.wslDistroOverridesByHost) : { ...current.wslDistroOverridesByHost };
  if (Object.keys(installationMethodsByHost).length === 0 && current.installationMethod !== DEFAULT_CODEX_PROVIDER_SETTINGS.installationMethod) {
    installationMethodsByHost[hostnameKey] = current.installationMethod;
  }
  if (Object.keys(wslDistroOverridesByHost).length === 0 && current.wslDistroOverride) {
    wslDistroOverridesByHost[hostnameKey] = current.wslDistroOverride;
  }
  if ("installationMethod" in updates) {
    installationMethodsByHost[hostnameKey] = normalizeCodexInstallationMethod(updates.installationMethod);
  }
  if ("wslDistroOverride" in updates) {
    const normalizedDistroOverride = normalizeOptionalString(updates.wslDistroOverride);
    if (normalizedDistroOverride) {
      wslDistroOverridesByHost[hostnameKey] = normalizedDistroOverride;
    } else {
      delete wslDistroOverridesByHost[hostnameKey];
    }
  }
  const next = {
    ...current,
    ...updates,
    installationMethod: (_a3 = installationMethodsByHost[hostnameKey]) != null ? _a3 : DEFAULT_CODEX_PROVIDER_SETTINGS.installationMethod,
    installationMethodsByHost,
    wslDistroOverride: (_b2 = wslDistroOverridesByHost[hostnameKey]) != null ? _b2 : DEFAULT_CODEX_PROVIDER_SETTINGS.wslDistroOverride,
    wslDistroOverridesByHost
  };
  setProviderConfig(settings11, "codex", {
    enabled: next.enabled,
    safeMode: next.safeMode,
    cliPath: next.cliPath,
    cliPathsByHost: next.cliPathsByHost,
    customModels: next.customModels,
    reasoningSummary: next.reasoningSummary,
    environmentVariables: next.environmentVariables,
    environmentHash: next.environmentHash,
    installationMethodsByHost,
    wslDistroOverridesByHost
  });
  return next;
}

// src/providers/opencode/settings.ts
init_env();

// src/providers/opencode/internal/compareCollections.ts
function sameStringList(left, right) {
  if (left.length !== right.length) {
    return false;
  }
  return left.every((entry, index) => entry === right[index]);
}
function sameStringMap(left, right) {
  const leftEntries = Object.entries(left);
  if (leftEntries.length !== Object.keys(right).length) {
    return false;
  }
  return leftEntries.every(([key, value]) => right[key] === value);
}
function sameModes(left, right) {
  if (left.length !== right.length) {
    return false;
  }
  return left.every((mode, index) => {
    var _a3, _b2, _c, _d2, _e;
    return mode.id === ((_a3 = right[index]) == null ? void 0 : _a3.id) && mode.name === ((_b2 = right[index]) == null ? void 0 : _b2.name) && ((_c = mode.description) != null ? _c : "") === ((_e = (_d2 = right[index]) == null ? void 0 : _d2.description) != null ? _e : "");
  });
}
function sameDiscoveredModels(left, right) {
  if (left.length !== right.length) {
    return false;
  }
  return left.every((model, index) => {
    var _a3, _b2, _c, _d2, _e;
    return model.rawId === ((_a3 = right[index]) == null ? void 0 : _a3.rawId) && model.label === ((_b2 = right[index]) == null ? void 0 : _b2.label) && ((_c = model.description) != null ? _c : "") === ((_e = (_d2 = right[index]) == null ? void 0 : _d2.description) != null ? _e : "");
  });
}

// src/providers/opencode/models.ts
var OPENCODE_SYNTHETIC_MODEL_ID = "opencode";
var OPENCODE_DEFAULT_THINKING_LEVEL = "default";
var OPENCODE_MODEL_PREFIX = "opencode:";
var OPENCODE_VARIANT_ASCENDING_ORDER = [
  "none",
  "minimal",
  "low",
  "medium",
  "high",
  "max",
  "xhigh"
];
var OPENCODE_VARIANT_ASCENDING_RANK = new Map(
  OPENCODE_VARIANT_ASCENDING_ORDER.map((value, index) => [value, index])
);
function isOpencodeModelSelectionId(model) {
  return model === OPENCODE_SYNTHETIC_MODEL_ID || model.startsWith(OPENCODE_MODEL_PREFIX);
}
function encodeOpencodeModelId(rawModelId) {
  const normalized = rawModelId.trim();
  return normalized ? `${OPENCODE_MODEL_PREFIX}${normalized}` : OPENCODE_SYNTHETIC_MODEL_ID;
}
function decodeOpencodeModelId(model) {
  if (!model.startsWith(OPENCODE_MODEL_PREFIX)) {
    return null;
  }
  const rawModelId = model.slice(OPENCODE_MODEL_PREFIX.length).trim();
  return rawModelId || null;
}
function normalizeOpencodeDiscoveredModels(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  const normalized = [];
  const seen = /* @__PURE__ */ new Set();
  for (const entry of value) {
    if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
      continue;
    }
    const rawId = typeof entry.rawId === "string" ? entry.rawId.trim() : "";
    const label = typeof entry.label === "string" ? entry.label.trim() : rawId;
    const description = typeof entry.description === "string" ? entry.description.trim() : "";
    if (!rawId || seen.has(rawId)) {
      continue;
    }
    seen.add(rawId);
    normalized.push({
      ...description ? { description } : {},
      label: label || rawId,
      rawId
    });
  }
  return normalized;
}
function resolveOpencodeBaseModelRawId(rawId, discoveredModels) {
  const normalizedRawId = rawId.trim();
  if (!normalizedRawId) {
    return "";
  }
  const discoveredRawIds = discoveredModels instanceof Set ? discoveredModels : new Set(discoveredModels.map((model) => model.rawId));
  const slashIndex = normalizedRawId.lastIndexOf("/");
  if (slashIndex <= 0) {
    return normalizedRawId;
  }
  const candidate = normalizedRawId.slice(0, slashIndex);
  if (discoveredRawIds.has(candidate)) {
    return candidate;
  }
  const variant = normalizedRawId.slice(slashIndex + 1).trim().toLowerCase();
  return OPENCODE_VARIANT_ASCENDING_RANK.has(variant) ? candidate : normalizedRawId;
}
function extractOpencodeModelVariantValue(rawId, discoveredModels) {
  const normalizedRawId = rawId.trim();
  if (!normalizedRawId) {
    return null;
  }
  const baseRawId = resolveOpencodeBaseModelRawId(normalizedRawId, discoveredModels);
  if (baseRawId === normalizedRawId || baseRawId.length >= normalizedRawId.length) {
    return null;
  }
  const variant = normalizedRawId.slice(baseRawId.length + 1).trim();
  return variant || null;
}
function combineOpencodeRawModelSelection(baseRawId, thinkingLevel, discoveredModels) {
  const normalizedBaseRawId = baseRawId == null ? void 0 : baseRawId.trim();
  if (!normalizedBaseRawId) {
    return null;
  }
  const variant = thinkingLevel == null ? void 0 : thinkingLevel.trim();
  if (!variant || variant === OPENCODE_DEFAULT_THINKING_LEVEL) {
    return normalizedBaseRawId;
  }
  const supportedVariants = new Set(
    getOpencodeModelVariants(normalizedBaseRawId, discoveredModels).map((entry) => entry.value)
  );
  return supportedVariants.has(variant) ? `${normalizedBaseRawId}/${variant}` : normalizedBaseRawId;
}
function splitOpencodeModelLabel(label) {
  const trimmed = label.trim();
  const slashIndex = trimmed.indexOf("/");
  if (slashIndex <= 0 || slashIndex >= trimmed.length - 1) {
    return {
      modelLabel: trimmed,
      providerLabel: "Other"
    };
  }
  return {
    modelLabel: trimmed.slice(slashIndex + 1).trim(),
    providerLabel: trimmed.slice(0, slashIndex).trim()
  };
}
function buildOpencodeBaseModels(models) {
  const discoveredRawIds = new Set(models.map((model) => model.rawId));
  const discoveredByRawId = new Map(models.map((model) => [model.rawId, model]));
  const grouped = /* @__PURE__ */ new Map();
  for (const model of models) {
    const baseRawId = resolveOpencodeBaseModelRawId(model.rawId, discoveredRawIds);
    const existing = grouped.get(baseRawId);
    if (existing) {
      existing.push(model);
    } else {
      grouped.set(baseRawId, [model]);
    }
  }
  return Array.from(grouped.entries()).map(([baseRawId, entries]) => {
    var _a3, _b2;
    const baseModel = (_a3 = discoveredByRawId.get(baseRawId)) != null ? _a3 : entries[0];
    const variants = entries.flatMap((entry) => {
      if (entry.rawId === baseRawId) {
        return [];
      }
      const variant = extractOpencodeModelVariantValue(entry.rawId, discoveredRawIds);
      if (!variant) {
        return [];
      }
      return [{
        ...entry.description ? { description: entry.description } : {},
        label: formatOpencodeThinkingLevelLabel(variant),
        value: variant
      }];
    });
    return {
      ...(baseModel == null ? void 0 : baseModel.description) ? { description: baseModel.description } : {},
      label: (_b2 = baseModel == null ? void 0 : baseModel.label) != null ? _b2 : baseRawId,
      rawId: baseRawId,
      variants: dedupeOpencodeVariants(variants)
    };
  }).sort((left, right) => left.label.localeCompare(right.label));
}
function getOpencodeModelVariants(rawId, models) {
  var _a3, _b2;
  const baseRawId = resolveOpencodeBaseModelRawId(rawId, models);
  return (_b2 = (_a3 = buildOpencodeBaseModels(models).find((model) => model.rawId === baseRawId)) == null ? void 0 : _a3.variants) != null ? _b2 : [];
}
function formatOpencodeThinkingLevelLabel(value) {
  const trimmed = value.trim();
  if (!trimmed) {
    return "";
  }
  if (trimmed.toLowerCase() === "xhigh") {
    return "XHigh";
  }
  return trimmed.charAt(0).toUpperCase() + trimmed.slice(1);
}
function dedupeOpencodeVariants(variants) {
  const unique = /* @__PURE__ */ new Map();
  for (const variant of variants) {
    if (!unique.has(variant.value)) {
      unique.set(variant.value, variant);
    }
  }
  return Array.from(unique.values()).sort((left, right) => compareOpencodeVariantValues(left.value, right.value));
}
function compareOpencodeVariantValues(left, right) {
  const leftRank = OPENCODE_VARIANT_ASCENDING_RANK.get(left.toLowerCase());
  const rightRank = OPENCODE_VARIANT_ASCENDING_RANK.get(right.toLowerCase());
  if (leftRank !== void 0 && rightRank !== void 0) {
    return leftRank - rightRank;
  }
  if (leftRank !== void 0) {
    return -1;
  }
  if (rightRank !== void 0) {
    return 1;
  }
  return left.localeCompare(right);
}

// src/providers/opencode/modes.ts
var OPENCODE_BUILD_MODE_ID = "build";
var OPENCODE_YOLO_MODE_ID = "claudian-yolo";
var OPENCODE_SAFE_MODE_ID = "claudian-safe";
var OPENCODE_PLAN_MODE_ID = "plan";
var OPENCODE_FALLBACK_MODES = Object.freeze([
  {
    description: "The default agent. Executes tools based on configured permissions.",
    id: OPENCODE_YOLO_MODE_ID,
    name: "yolo"
  },
  {
    description: "Safe mode. Asks before shell commands and file edits.",
    id: OPENCODE_SAFE_MODE_ID,
    name: "safe"
  },
  {
    description: "Plan mode. Disallows all edit tools.",
    id: OPENCODE_PLAN_MODE_ID,
    name: OPENCODE_PLAN_MODE_ID
  }
]);
var OPENCODE_MANAGED_MODE_IDS = /* @__PURE__ */ new Set([
  OPENCODE_BUILD_MODE_ID,
  ...OPENCODE_FALLBACK_MODES.map((mode) => mode.id)
]);
function normalizeOpencodeAvailableModes(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  const normalized = [];
  const seen = /* @__PURE__ */ new Set();
  for (const entry of value) {
    if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
      continue;
    }
    const id = typeof entry.id === "string" ? entry.id.trim() : "";
    const name = typeof entry.name === "string" ? entry.name.trim() : id;
    const description = typeof entry.description === "string" ? entry.description.trim() : "";
    if (!id || seen.has(id)) {
      continue;
    }
    seen.add(id);
    normalized.push({
      ...description ? { description } : {},
      id,
      name: name || id
    });
  }
  return normalized;
}
function getEffectiveOpencodeModes(modes) {
  return modes.length > 0 ? modes : [...OPENCODE_FALLBACK_MODES];
}
function isManagedOpencodeModeId(value) {
  return OPENCODE_MANAGED_MODE_IDS.has(value);
}
function getManagedOpencodeModes(modes) {
  const effectiveModes = getEffectiveOpencodeModes(modes);
  return OPENCODE_FALLBACK_MODES.map((fallbackMode) => {
    var _a3;
    return (_a3 = effectiveModes.find((mode) => mode.id === fallbackMode.id)) != null ? _a3 : fallbackMode;
  });
}
function normalizeOpencodeSelectedMode(value) {
  if (typeof value !== "string") {
    return "";
  }
  const trimmed = value.trim();
  if (!trimmed) {
    return "";
  }
  return trimmed;
}
function normalizeManagedOpencodeSelectedMode(value, modes = []) {
  var _a3, _b2;
  const normalized = normalizeOpencodeSelectedMode(value);
  if (!normalized) {
    return "";
  }
  const canonicalModeId = normalized === OPENCODE_BUILD_MODE_ID ? OPENCODE_YOLO_MODE_ID : normalized;
  const managedModes = getManagedOpencodeModes(modes);
  return managedModes.some((mode) => mode.id === canonicalModeId) ? canonicalModeId : (_b2 = (_a3 = managedModes[0]) == null ? void 0 : _a3.id) != null ? _b2 : "";
}
function resolveOpencodeModeForPermissionMode(permissionMode, modes = []) {
  var _a3, _b2;
  const managedModes = getManagedOpencodeModes(modes);
  const managedModeIds = new Set(managedModes.map((mode) => mode.id));
  if (permissionMode === "plan" && managedModeIds.has(OPENCODE_PLAN_MODE_ID)) {
    return OPENCODE_PLAN_MODE_ID;
  }
  if (permissionMode === "normal" && managedModeIds.has(OPENCODE_SAFE_MODE_ID)) {
    return OPENCODE_SAFE_MODE_ID;
  }
  if (managedModeIds.has(OPENCODE_YOLO_MODE_ID)) {
    return OPENCODE_YOLO_MODE_ID;
  }
  return (_b2 = (_a3 = managedModes[0]) == null ? void 0 : _a3.id) != null ? _b2 : "";
}
function resolvePermissionModeForManagedOpencodeMode(modeId) {
  if (modeId === OPENCODE_BUILD_MODE_ID || modeId === OPENCODE_YOLO_MODE_ID) {
    return "yolo";
  }
  if (modeId === OPENCODE_SAFE_MODE_ID) {
    return "normal";
  }
  if (modeId === OPENCODE_PLAN_MODE_ID) {
    return "plan";
  }
  return null;
}

// src/providers/opencode/discoveryState.ts
var OPENCODE_DISCOVERY_STATE = /* @__PURE__ */ Symbol("opencodeDiscoveryState");
function ensureDiscoveryState(settings11) {
  const bag = settings11;
  const existing = bag[OPENCODE_DISCOVERY_STATE];
  if (existing && typeof existing === "object" && !Array.isArray(existing)) {
    return existing;
  }
  const next = {
    availableModes: [],
    discoveredModels: []
  };
  bag[OPENCODE_DISCOVERY_STATE] = next;
  return next;
}
function cloneModes(modes) {
  return modes.map((mode) => ({ ...mode }));
}
function cloneDiscoveredModels(models) {
  return models.map((model) => ({ ...model }));
}
function getOpencodeDiscoveryState(settings11) {
  const state = ensureDiscoveryState(settings11);
  return {
    availableModes: cloneModes(state.availableModes),
    discoveredModels: cloneDiscoveredModels(state.discoveredModels)
  };
}
function updateOpencodeDiscoveryState(settings11, updates) {
  const state = ensureDiscoveryState(settings11);
  const nextAvailableModes = "availableModes" in updates ? normalizeOpencodeAvailableModes(updates.availableModes) : state.availableModes;
  const nextDiscoveredModels = "discoveredModels" in updates ? normalizeOpencodeDiscoveredModels(updates.discoveredModels) : state.discoveredModels;
  const changed = !sameModes(state.availableModes, nextAvailableModes) || !sameDiscoveredModels(state.discoveredModels, nextDiscoveredModels);
  if (!changed) {
    return false;
  }
  state.availableModes = cloneModes(nextAvailableModes);
  state.discoveredModels = cloneDiscoveredModels(nextDiscoveredModels);
  return true;
}
function clearOpencodeDiscoveryState(settings11) {
  const state = ensureDiscoveryState(settings11);
  if (state.availableModes.length === 0 && state.discoveredModels.length === 0) {
    return false;
  }
  state.availableModes = [];
  state.discoveredModels = [];
  return true;
}
function seedOpencodeDiscoveryStateFromLegacyConfig(settings11, legacyConfig) {
  const state = ensureDiscoveryState(settings11);
  const nextAvailableModes = state.availableModes.length > 0 ? state.availableModes : normalizeOpencodeAvailableModes(legacyConfig.availableModes);
  const nextDiscoveredModels = state.discoveredModels.length > 0 ? state.discoveredModels : normalizeOpencodeDiscoveredModels(legacyConfig.discoveredModels);
  return updateOpencodeDiscoveryState(settings11, {
    availableModes: nextAvailableModes,
    discoveredModels: nextDiscoveredModels
  });
}

// src/providers/opencode/internal/providerProjection.ts
function ensureProviderProjectionMap(settings11, key) {
  const current = settings11[key];
  if (current && typeof current === "object" && !Array.isArray(current)) {
    return current;
  }
  const next = {};
  settings11[key] = next;
  return next;
}

// src/providers/opencode/settings.ts
var OPENCODE_DEFAULT_ENVIRONMENT_VARIABLES = "OPENCODE_ENABLE_EXA=1";
var DEFAULT_OPENCODE_PROVIDER_SETTINGS = Object.freeze({
  cliPath: "",
  cliPathsByHost: {},
  enabled: false,
  environmentHash: "",
  environmentVariables: OPENCODE_DEFAULT_ENVIRONMENT_VARIABLES,
  modelAliases: {},
  preferredThinkingByModel: {},
  selectedMode: "",
  visibleModels: []
});
function normalizeHostnameCliPaths3(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return {};
  }
  const result = {};
  for (const [key, entry] of Object.entries(value)) {
    if (typeof entry === "string" && entry.trim()) {
      result[key] = entry.trim();
    }
  }
  return result;
}
function normalizeOpencodeVisibleModels(value, discoveredModels = []) {
  if (!Array.isArray(value)) {
    return [];
  }
  const normalized = [];
  const seen = /* @__PURE__ */ new Set();
  for (const entry of value) {
    if (typeof entry !== "string") {
      continue;
    }
    const trimmed = resolveOpencodeBaseModelRawId(entry.trim(), discoveredModels);
    if (!trimmed || seen.has(trimmed)) {
      continue;
    }
    seen.add(trimmed);
    normalized.push(trimmed);
  }
  return normalized;
}
function normalizeOpencodeModelAliases(value, discoveredModels = []) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return {};
  }
  const normalized = {};
  for (const [rawId, alias] of Object.entries(value)) {
    if (typeof alias !== "string") {
      continue;
    }
    const normalizedRawId = resolveOpencodeBaseModelRawId(rawId.trim(), discoveredModels);
    const normalizedAlias = alias.trim();
    if (!normalizedRawId || !normalizedAlias) {
      continue;
    }
    normalized[normalizedRawId] = normalizedAlias;
  }
  return normalized;
}
function normalizeOpencodePreferredThinkingByModel(value, discoveredModels = []) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return {};
  }
  const normalized = {};
  for (const [rawId, thinkingLevel] of Object.entries(value)) {
    if (typeof thinkingLevel !== "string") {
      continue;
    }
    const normalizedRawId = resolveOpencodeBaseModelRawId(rawId.trim(), discoveredModels);
    const normalizedThinkingLevel = thinkingLevel.trim();
    if (!normalizedRawId || !normalizedThinkingLevel) {
      continue;
    }
    normalized[normalizedRawId] = normalizedThinkingLevel;
  }
  return normalized;
}
function getOpencodeProviderSettings(settings11) {
  var _a3, _b2, _c, _d2, _e;
  const config2 = getProviderConfig(settings11, "opencode");
  seedOpencodeDiscoveryStateFromLegacyConfig(settings11, config2);
  const discoveryState = getOpencodeDiscoveryState(settings11);
  const availableModes = discoveryState.availableModes;
  const discoveredModels = discoveryState.discoveredModels;
  return {
    availableModes,
    cliPath: (_a3 = config2.cliPath) != null ? _a3 : DEFAULT_OPENCODE_PROVIDER_SETTINGS.cliPath,
    cliPathsByHost: normalizeHostnameCliPaths3(config2.cliPathsByHost),
    discoveredModels,
    enabled: (_b2 = config2.enabled) != null ? _b2 : DEFAULT_OPENCODE_PROVIDER_SETTINGS.enabled,
    environmentHash: (_c = config2.environmentHash) != null ? _c : DEFAULT_OPENCODE_PROVIDER_SETTINGS.environmentHash,
    environmentVariables: (_e = (_d2 = config2.environmentVariables) != null ? _d2 : getProviderEnvironmentVariables(settings11, "opencode")) != null ? _e : DEFAULT_OPENCODE_PROVIDER_SETTINGS.environmentVariables,
    modelAliases: normalizeOpencodeModelAliases(config2.modelAliases, discoveredModels),
    preferredThinkingByModel: normalizeOpencodePreferredThinkingByModel(
      config2.preferredThinkingByModel,
      discoveredModels
    ),
    selectedMode: normalizeManagedOpencodeSelectedMode(config2.selectedMode, availableModes),
    visibleModels: normalizeOpencodeVisibleModels(config2.visibleModels, discoveredModels)
  };
}
function updateOpencodeProviderSettings(settings11, updates) {
  var _a3, _b2, _c, _d2;
  const current = getOpencodeProviderSettings(settings11);
  const hostnameKey = getHostnameKey();
  if ("availableModes" in updates || "discoveredModels" in updates) {
    updateOpencodeDiscoveryState(settings11, {
      ...updates.availableModes !== void 0 ? { availableModes: updates.availableModes } : {},
      ...updates.discoveredModels !== void 0 ? { discoveredModels: updates.discoveredModels } : {}
    });
  }
  const discoveryState = getOpencodeDiscoveryState(settings11);
  const nextAvailableModes = discoveryState.availableModes;
  const nextDiscoveredModels = discoveryState.discoveredModels;
  const nextSelectedMode = normalizeManagedOpencodeSelectedMode(
    (_a3 = updates.selectedMode) != null ? _a3 : current.selectedMode,
    nextAvailableModes
  );
  const nextVisibleModels = normalizeOpencodeVisibleModels(
    (_b2 = updates.visibleModels) != null ? _b2 : current.visibleModels,
    nextDiscoveredModels
  );
  const nextModelAliases = pruneModelAliasesToVisible(
    normalizeOpencodeModelAliases(
      (_c = updates.modelAliases) != null ? _c : current.modelAliases,
      nextDiscoveredModels
    ),
    nextVisibleModels
  );
  const nextCliPathsByHost = "cliPathsByHost" in updates ? normalizeHostnameCliPaths3(updates.cliPathsByHost) : { ...current.cliPathsByHost };
  let nextCliPath = "cliPathsByHost" in updates ? DEFAULT_OPENCODE_PROVIDER_SETTINGS.cliPath : current.cliPath.trim();
  if ("cliPath" in updates) {
    const trimmedCliPath = typeof updates.cliPath === "string" ? updates.cliPath.trim() : "";
    if (trimmedCliPath) {
      nextCliPathsByHost[hostnameKey] = trimmedCliPath;
    } else {
      delete nextCliPathsByHost[hostnameKey];
    }
    nextCliPath = DEFAULT_OPENCODE_PROVIDER_SETTINGS.cliPath;
  }
  const next = {
    ...current,
    ...updates,
    availableModes: nextAvailableModes,
    cliPath: nextCliPath,
    cliPathsByHost: nextCliPathsByHost,
    discoveredModels: nextDiscoveredModels,
    modelAliases: nextModelAliases,
    preferredThinkingByModel: normalizeOpencodePreferredThinkingByModel(
      (_d2 = updates.preferredThinkingByModel) != null ? _d2 : current.preferredThinkingByModel,
      nextDiscoveredModels
    ),
    selectedMode: nextSelectedMode,
    visibleModels: nextVisibleModels
  };
  if (updates.visibleModels !== void 0) {
    retargetRemovedOpencodeSelections(settings11, next);
  }
  setProviderConfig(settings11, "opencode", {
    cliPath: next.cliPath,
    cliPathsByHost: next.cliPathsByHost,
    enabled: next.enabled,
    environmentHash: next.environmentHash,
    environmentVariables: next.environmentVariables,
    modelAliases: next.modelAliases,
    preferredThinkingByModel: next.preferredThinkingByModel,
    selectedMode: next.selectedMode,
    visibleModels: next.visibleModels
  });
  return next;
}
function hasLegacyOpencodeDiscoveryFields(settings11) {
  const config2 = getProviderConfig(settings11, "opencode");
  return "availableModes" in config2 || "discoveredModels" in config2;
}
function pruneModelAliasesToVisible(aliases, visibleModels) {
  if (visibleModels.length === 0 || Object.keys(aliases).length === 0) {
    return {};
  }
  const visibleSet = new Set(visibleModels);
  const pruned = {};
  for (const [rawId, alias] of Object.entries(aliases)) {
    if (visibleSet.has(rawId)) {
      pruned[rawId] = alias;
    }
  }
  return pruned;
}
function retargetRemovedOpencodeSelections(settings11, next) {
  var _a3;
  if (next.visibleModels.length === 0) {
    if (typeof settings11.titleGenerationModel === "string" && isOpencodeModelSelectionId(settings11.titleGenerationModel)) {
      settings11.titleGenerationModel = "";
    }
    return;
  }
  const visibleSet = new Set(next.visibleModels);
  const fallbackRawId = next.visibleModels[0];
  const fallbackModelId = encodeOpencodeModelId(fallbackRawId);
  const fallbackEffort = (_a3 = next.preferredThinkingByModel[fallbackRawId]) != null ? _a3 : OPENCODE_DEFAULT_THINKING_LEVEL;
  const maybeRetargetModel = (value) => {
    if (typeof value !== "string" || !isOpencodeModelSelectionId(value)) {
      return null;
    }
    const rawModelId = decodeOpencodeModelId(value);
    if (!rawModelId) {
      return fallbackModelId;
    }
    const baseRawId = resolveOpencodeBaseModelRawId(rawModelId, next.discoveredModels);
    return visibleSet.has(baseRawId) ? null : fallbackModelId;
  };
  const savedProviderModel = ensureProviderProjectionMap(settings11, "savedProviderModel");
  const nextSavedModel = maybeRetargetModel(savedProviderModel.opencode);
  if (nextSavedModel) {
    savedProviderModel.opencode = nextSavedModel;
    ensureProviderProjectionMap(settings11, "savedProviderEffort").opencode = fallbackEffort;
  }
  const nextTopLevelModel = maybeRetargetModel(settings11.model);
  if (nextTopLevelModel) {
    settings11.model = nextTopLevelModel;
    settings11.effortLevel = fallbackEffort;
  }
  const nextTitleGenerationModel = maybeRetargetModel(settings11.titleGenerationModel);
  if (nextTitleGenerationModel) {
    settings11.titleGenerationModel = nextTitleGenerationModel;
  }
}

// src/providers/defaultProviderConfigs.ts
function getBuiltInProviderDefaultConfigs() {
  return {
    claude: { ...DEFAULT_CLAUDE_PROVIDER_SETTINGS },
    codex: { ...DEFAULT_CODEX_PROVIDER_SETTINGS },
    opencode: { ...DEFAULT_OPENCODE_PROVIDER_SETTINGS }
  };
}

// src/app/settings/defaultSettings.ts
var DEFAULT_CLAUDIAN_SETTINGS = {
  userName: "",
  permissionMode: "yolo",
  model: "haiku",
  thinkingBudget: "off",
  effortLevel: "high",
  serviceTier: "default",
  enableAutoTitleGeneration: true,
  titleGenerationModel: "",
  excludedTags: [],
  mediaFolder: "",
  systemPrompt: "",
  persistentExternalContextPaths: [],
  sharedEnvironmentVariables: "",
  envSnippets: [],
  customContextLimits: {},
  keyboardNavigation: {
    scrollUpKey: "w",
    scrollDownKey: "s",
    focusInputKey: "i"
  },
  locale: "en",
  providerConfigs: getBuiltInProviderDefaultConfigs(),
  settingsProvider: "claude",
  savedProviderModel: {},
  savedProviderEffort: {},
  savedProviderServiceTier: {},
  savedProviderThinkingBudget: {},
  savedProviderPermissionMode: {},
  lastCustomModel: "",
  maxTabs: 3,
  tabBarPosition: "input",
  enableAutoScroll: true,
  openInMainTab: false,
  hiddenProviderCommands: getDefaultHiddenProviderCommands()
};

// src/app/settings/ClaudianSettingsStorage.ts
var LEGACY_TOP_LEVEL_PROVIDER_FIELDS = [
  "claudeSafeMode",
  "codexSafeMode",
  "claudeCliPath",
  "claudeCliPathsByHost",
  "codexCliPath",
  "codexCliPathsByHost",
  "codexReasoningSummary",
  "loadUserClaudeSettings",
  "codexEnabled",
  "lastClaudeModel",
  "enableChrome",
  "enableBangBash",
  "enableOpus1M",
  "enableSonnet1M",
  "environmentVariables",
  "lastEnvHash",
  "lastCodexEnvHash"
];
function stripLegacyFields(settings11) {
  const {
    activeConversationId: _activeConversationId,
    show1MModel: _show1MModel,
    hiddenSlashCommands: _hiddenSlashCommands,
    slashCommands: _slashCommands,
    allowExternalAccess: _allowExternalAccess,
    allowedExportPaths: _allowedExportPaths,
    enableBlocklist: _enableBlocklist,
    blockedCommands: _blockedCommands,
    claudeSafeMode: _claudeSafeMode,
    codexSafeMode: _codexSafeMode,
    claudeCliPath: _claudeCliPath,
    claudeCliPathsByHost: _claudeCliPathsByHost,
    codexCliPath: _codexCliPath,
    codexCliPathsByHost: _codexCliPathsByHost,
    codexReasoningSummary: _codexReasoningSummary,
    loadUserClaudeSettings: _loadUserClaudeSettings,
    codexEnabled: _codexEnabled,
    lastClaudeModel: _lastClaudeModel,
    enableChrome: _enableChrome,
    enableBangBash: _enableBangBash,
    enableOpus1M: _enableOpus1M,
    enableSonnet1M: _enableSonnet1M,
    environmentVariables: _environmentVariables,
    lastEnvHash: _lastEnvHash,
    lastCodexEnvHash: _lastCodexEnvHash,
    ...cleaned
  } = settings11;
  return cleaned;
}
function normalizeProviderConfigs(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return {};
  }
  const result = {};
  for (const [providerId, config2] of Object.entries(value)) {
    if (config2 && typeof config2 === "object" && !Array.isArray(config2)) {
      result[providerId] = { ...config2 };
    }
  }
  return result;
}
function isEnvironmentScope(value) {
  return value === "shared" || typeof value === "string" && value.startsWith("provider:");
}
function normalizeContextLimits(value) {
  if (!value || typeof value !== "object" || Array.isArray(value)) {
    return void 0;
  }
  const result = {};
  for (const [key, entry] of Object.entries(value)) {
    if (typeof entry === "number" && Number.isFinite(entry) && entry > 0) {
      result[key] = entry;
    }
  }
  return Object.keys(result).length > 0 ? result : void 0;
}
function normalizeEnvSnippets(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  const snippets = [];
  for (const item of value) {
    if (!item || typeof item !== "object" || Array.isArray(item)) {
      continue;
    }
    const candidate = item;
    if (typeof candidate.id !== "string" || typeof candidate.name !== "string" || typeof candidate.description !== "string" || typeof candidate.envVars !== "string") {
      continue;
    }
    snippets.push({
      id: candidate.id,
      name: candidate.name,
      description: candidate.description,
      envVars: candidate.envVars,
      scope: resolveEnvironmentSnippetScope(
        candidate.envVars,
        isEnvironmentScope(candidate.scope) ? candidate.scope : inferEnvironmentSnippetScope(candidate.envVars)
      ),
      contextLimits: normalizeContextLimits(candidate.contextLimits)
    });
  }
  return snippets;
}
function hasLegacyTopLevelProviderFields(stored) {
  return LEGACY_TOP_LEVEL_PROVIDER_FIELDS.some((key) => key in stored);
}
function mergeLegacyClaudeHiddenCommands(hiddenProviderCommands, legacyHiddenSlashCommands) {
  const legacyCommands = normalizeHiddenCommandList(legacyHiddenSlashCommands);
  if (legacyCommands.length === 0 || hiddenProviderCommands.claude) {
    return hiddenProviderCommands;
  }
  return {
    ...hiddenProviderCommands,
    claude: legacyCommands
  };
}
var ClaudianSettingsStorage = class {
  constructor(adapter) {
    this.adapter = adapter;
  }
  async load() {
    var _a3;
    const settingsPath = await this.getLoadPath();
    if (!settingsPath) {
      return this.getDefaults();
    }
    const content = await this.adapter.read(settingsPath);
    const stored = JSON.parse(content);
    const hiddenProviderCommands = mergeLegacyClaudeHiddenCommands(
      normalizeHiddenProviderCommands(stored.hiddenProviderCommands),
      stored.hiddenSlashCommands
    );
    const envSnippets = normalizeEnvSnippets(stored.envSnippets);
    const providerConfigs = normalizeProviderConfigs(stored.providerConfigs);
    const legacyProviderSettings = {
      ...stored,
      hiddenProviderCommands,
      providerConfigs
    };
    const storedWithoutLegacy = stripLegacyFields({
      ...legacyProviderSettings
    });
    const legacyNormalized = {
      ...storedWithoutLegacy,
      sharedEnvironmentVariables: getSharedEnvironmentVariables(legacyProviderSettings),
      envSnippets,
      hiddenProviderCommands,
      providerConfigs
    };
    const merged = {
      ...this.getDefaults(),
      ...legacyNormalized
    };
    updateClaudeProviderSettings(
      merged,
      getClaudeProviderSettings(legacyProviderSettings)
    );
    updateCodexProviderSettings(
      merged,
      getCodexProviderSettings(legacyProviderSettings)
    );
    if (settingsPath !== CLAUDIAN_SETTINGS_PATH || (hasLegacyTopLevelProviderFields(stored) || "show1MModel" in stored || "slashCommands" in stored || "hiddenSlashCommands" in stored || "activeConversationId" in stored || "allowExternalAccess" in stored || "allowedExportPaths" in stored || "enableBlocklist" in stored || "blockedCommands" in stored || JSON.stringify(envSnippets) !== JSON.stringify((_a3 = stored.envSnippets) != null ? _a3 : []))) {
      await this.save(merged);
    }
    return merged;
  }
  async save(settings11) {
    const content = JSON.stringify(
      stripLegacyFields(settings11),
      null,
      2
    );
    await this.adapter.write(CLAUDIAN_SETTINGS_PATH, content);
    await this.deleteLegacyFileIfPresent();
  }
  async exists() {
    if (await this.adapter.exists(CLAUDIAN_SETTINGS_PATH)) {
      return true;
    }
    return this.adapter.exists(LEGACY_CLAUDIAN_SETTINGS_PATH);
  }
  async update(updates) {
    const current = await this.load();
    await this.save({ ...current, ...updates });
  }
  async setLastModel(model, isCustom) {
    if (isCustom) {
      await this.update({ lastCustomModel: model });
      return;
    }
    const current = await this.load();
    updateClaudeProviderSettings(
      current,
      { lastModel: model }
    );
    await this.save(current);
  }
  async setLastEnvHash(hash2) {
    const current = await this.load();
    updateClaudeProviderSettings(
      current,
      { environmentHash: hash2 }
    );
    await this.save(current);
  }
  getDefaults() {
    return DEFAULT_CLAUDIAN_SETTINGS;
  }
  async getLoadPath() {
    if (await this.adapter.exists(CLAUDIAN_SETTINGS_PATH)) {
      return CLAUDIAN_SETTINGS_PATH;
    }
    if (await this.adapter.exists(LEGACY_CLAUDIAN_SETTINGS_PATH)) {
      return LEGACY_CLAUDIAN_SETTINGS_PATH;
    }
    return null;
  }
  async deleteLegacyFileIfPresent() {
    if (await this.adapter.exists(LEGACY_CLAUDIAN_SETTINGS_PATH)) {
      await this.adapter.delete(LEGACY_CLAUDIAN_SETTINGS_PATH);
    }
  }
};

// src/core/bootstrap/SessionStorage.ts
var SessionStorage = class {
  constructor(adapter) {
    this.adapter = adapter;
  }
  getMetadataPath(id) {
    return `${SESSIONS_PATH}/${id}.meta.json`;
  }
  getLegacyMetadataPath(id) {
    return `${LEGACY_SESSIONS_PATH}/${id}.meta.json`;
  }
  async saveMetadata(metadata) {
    const filePath = this.getMetadataPath(metadata.id);
    const content = JSON.stringify(metadata, null, 2);
    await this.adapter.write(filePath, content);
    await this.deleteLegacyMetadataIfPresent(metadata.id);
  }
  async loadMetadata(id) {
    const filePath = await this.getLoadPath(id);
    try {
      if (!filePath) {
        return null;
      }
      const content = await this.adapter.read(filePath);
      const metadata = JSON.parse(content);
      if (filePath !== this.getMetadataPath(id)) {
        await this.saveMetadata(metadata);
      }
      return metadata;
    } catch (e2) {
      return null;
    }
  }
  async deleteMetadata(id) {
    await this.adapter.delete(this.getMetadataPath(id));
    await this.deleteLegacyMetadataIfPresent(id);
  }
  async listMetadata() {
    const metas = [];
    const files = await this.listUniqueMetadataFiles();
    for (const filePath of files) {
      try {
        const content = await this.adapter.read(filePath);
        const raw = JSON.parse(content);
        metas.push(raw);
        if (filePath.startsWith(`${LEGACY_SESSIONS_PATH}/`)) {
          await this.saveMetadata(raw);
        }
      } catch (e2) {
      }
    }
    return metas;
  }
  async listAllConversations() {
    const nativeMetas = await this.listMetadata();
    const metas = nativeMetas.map((meta3) => {
      var _a3;
      return {
        id: meta3.id,
        providerId: (_a3 = meta3.providerId) != null ? _a3 : DEFAULT_CHAT_PROVIDER_ID,
        title: meta3.title,
        createdAt: meta3.createdAt,
        updatedAt: meta3.updatedAt,
        lastResponseAt: meta3.lastResponseAt,
        messageCount: 0,
        preview: "SDK session",
        titleGenerationStatus: meta3.titleGenerationStatus
      };
    });
    return metas.sort(
      (a2, b10) => {
        var _a3, _b2;
        return ((_a3 = b10.lastResponseAt) != null ? _a3 : b10.createdAt) - ((_b2 = a2.lastResponseAt) != null ? _b2 : a2.createdAt);
      }
    );
  }
  toSessionMetadata(conversation) {
    var _a3, _b2, _c;
    const providerState = (_c = (_b2 = (_a3 = ProviderRegistry.getConversationHistoryService(conversation.providerId)).buildPersistedProviderState) == null ? void 0 : _b2.call(_a3, conversation)) != null ? _c : conversation.providerState;
    return {
      id: conversation.id,
      providerId: conversation.providerId,
      title: conversation.title,
      titleGenerationStatus: conversation.titleGenerationStatus,
      createdAt: conversation.createdAt,
      updatedAt: conversation.updatedAt,
      lastResponseAt: conversation.lastResponseAt,
      sessionId: conversation.sessionId,
      providerState: providerState && Object.keys(providerState).length > 0 ? providerState : void 0,
      currentNote: conversation.currentNote,
      externalContextPaths: conversation.externalContextPaths,
      enabledMcpServers: conversation.enabledMcpServers,
      usage: conversation.usage,
      resumeAtMessageId: conversation.resumeAtMessageId
    };
  }
  async getLoadPath(id) {
    const filePath = this.getMetadataPath(id);
    if (await this.adapter.exists(filePath)) {
      return filePath;
    }
    const legacyFilePath = this.getLegacyMetadataPath(id);
    if (await this.adapter.exists(legacyFilePath)) {
      return legacyFilePath;
    }
    return null;
  }
  async deleteLegacyMetadataIfPresent(id) {
    const legacyFilePath = this.getLegacyMetadataPath(id);
    if (await this.adapter.exists(legacyFilePath)) {
      await this.adapter.delete(legacyFilePath);
    }
  }
  async listUniqueMetadataFiles() {
    const preferredFiles = await this.listMetadataFiles(SESSIONS_PATH);
    const fallbackFiles = await this.listMetadataFiles(LEGACY_SESSIONS_PATH);
    const filesByName = /* @__PURE__ */ new Map();
    for (const filePath of preferredFiles) {
      filesByName.set(this.getFileName(filePath), filePath);
    }
    for (const filePath of fallbackFiles) {
      const fileName = this.getFileName(filePath);
      if (!filesByName.has(fileName)) {
        filesByName.set(fileName, filePath);
      }
    }
    return Array.from(filesByName.values());
  }
  async listMetadataFiles(folderPath) {
    try {
      const files = await this.adapter.listFiles(folderPath);
      return files.filter((filePath) => filePath.endsWith(".meta.json"));
    } catch (e2) {
      return [];
    }
  }
  getFileName(filePath) {
    var _a3;
    const parts = filePath.split("/");
    return (_a3 = parts[parts.length - 1]) != null ? _a3 : filePath;
  }
};

// src/core/storage/VaultFileAdapter.ts
var VaultFileAdapter = class {
  constructor(app) {
    this.app = app;
    this.writeQueue = Promise.resolve();
  }
  async exists(path24) {
    return this.app.vault.adapter.exists(path24);
  }
  async read(path24) {
    return this.app.vault.adapter.read(path24);
  }
  async write(path24, content) {
    await this.ensureParentFolder(path24);
    await this.app.vault.adapter.write(path24, content);
  }
  async append(path24, content) {
    await this.ensureParentFolder(path24);
    this.writeQueue = this.writeQueue.then(async () => {
      if (await this.exists(path24)) {
        const existing = await this.read(path24);
        await this.app.vault.adapter.write(path24, existing + content);
      } else {
        await this.app.vault.adapter.write(path24, content);
      }
    }).catch(() => {
    });
    await this.writeQueue;
  }
  async delete(path24) {
    if (await this.exists(path24)) {
      await this.app.vault.adapter.remove(path24);
    }
  }
  /** Fails silently if non-empty or missing. */
  async deleteFolder(path24) {
    try {
      if (await this.exists(path24)) {
        await this.app.vault.adapter.rmdir(path24, false);
      }
    } catch (e2) {
    }
  }
  async listFiles(folder) {
    if (!await this.exists(folder)) {
      return [];
    }
    const listing = await this.app.vault.adapter.list(folder);
    return listing.files;
  }
  /** List subfolders in a folder. Returns relative paths from the folder. */
  async listFolders(folder) {
    if (!await this.exists(folder)) {
      return [];
    }
    const listing = await this.app.vault.adapter.list(folder);
    return listing.folders;
  }
  /** Recursively list all files in a folder and subfolders. */
  async listFilesRecursive(folder) {
    const allFiles = [];
    const processFolder = async (currentFolder) => {
      if (!await this.exists(currentFolder)) return;
      const listing = await this.app.vault.adapter.list(currentFolder);
      allFiles.push(...listing.files);
      for (const subfolder of listing.folders) {
        await processFolder(subfolder);
      }
    };
    await processFolder(folder);
    return allFiles;
  }
  async ensureParentFolder(filePath) {
    const folder = filePath.substring(0, filePath.lastIndexOf("/"));
    if (folder && !await this.exists(folder)) {
      await this.ensureFolder(folder);
    }
  }
  /** Ensure a folder exists, creating it and parent folders if needed. */
  async ensureFolder(path24) {
    if (await this.exists(path24)) return;
    const parts = path24.split("/").filter(Boolean);
    let current = "";
    for (const part of parts) {
      current = current ? `${current}/${part}` : part;
      if (!await this.exists(current)) {
        await this.app.vault.adapter.mkdir(current);
      }
    }
  }
  /** Rename/move a file. */
  async rename(oldPath, newPath) {
    await this.app.vault.adapter.rename(oldPath, newPath);
  }
  async stat(path24) {
    try {
      const stat = await this.app.vault.adapter.stat(path24);
      if (!stat) return null;
      return { mtime: stat.mtime, size: stat.size };
    } catch (e2) {
      return null;
    }
  }
};

// src/providers/claude/types/settings.ts
function createPermissionRule(rule) {
  return rule;
}
var DEFAULT_CC_SETTINGS = {
  $schema: "https://json.schemastore.org/claude-code-settings.json",
  permissions: {
    allow: [],
    deny: [],
    ask: []
  }
};
var DEFAULT_CC_PERMISSIONS = {
  allow: [],
  deny: [],
  ask: []
};

// src/utils/agent.ts
function validateAgentName(name) {
  return validateSlugName(name, "Agent");
}
function pushYamlList(lines, key, items) {
  if (!items || items.length === 0) return;
  lines.push(`${key}:`);
  for (const item of items) {
    lines.push(`  - ${yamlString(item)}`);
  }
}
function serializeAgent(agent) {
  const lines = ["---"];
  lines.push(`name: ${agent.name}`);
  lines.push(`description: ${yamlString(agent.description)}`);
  pushYamlList(lines, "tools", agent.tools);
  pushYamlList(lines, "disallowedTools", agent.disallowedTools);
  if (agent.model && agent.model !== "inherit") {
    lines.push(`model: ${agent.model}`);
  }
  if (agent.permissionMode) {
    lines.push(`permissionMode: ${agent.permissionMode}`);
  }
  pushYamlList(lines, "skills", agent.skills);
  if (agent.hooks !== void 0) {
    lines.push(`hooks: ${JSON.stringify(agent.hooks)}`);
  }
  if (agent.extraFrontmatter) {
    for (const [key, value] of Object.entries(agent.extraFrontmatter)) {
      lines.push(`${key}: ${JSON.stringify(value)}`);
    }
  }
  lines.push("---");
  lines.push(agent.prompt);
  return lines.join("\n");
}

// src/providers/claude/storage/AgentVaultStorage.ts
var AGENTS_PATH = ".claude/agents";
var AgentVaultStorage = class {
  constructor(adapter) {
    this.adapter = adapter;
  }
  async loadAll() {
    const agents = [];
    try {
      const files = await this.adapter.listFiles(AGENTS_PATH);
      for (const filePath of files) {
        if (!filePath.endsWith(".md")) continue;
        try {
          const content = await this.adapter.read(filePath);
          const parsed = parseAgentFile(content);
          if (!parsed) continue;
          const { frontmatter, body } = parsed;
          agents.push(buildAgentFromFrontmatter(frontmatter, body, {
            id: frontmatter.name,
            source: "vault",
            filePath
          }));
        } catch (e2) {
        }
      }
    } catch (e2) {
    }
    return agents;
  }
  async load(agent) {
    const filePath = this.resolvePath(agent);
    try {
      const content = await this.adapter.read(filePath);
      const parsed = parseAgentFile(content);
      if (!parsed) return null;
      const { frontmatter, body } = parsed;
      return buildAgentFromFrontmatter(frontmatter, body, {
        id: frontmatter.name,
        source: agent.source,
        filePath
      });
    } catch (error48) {
      if (this.isFileNotFoundError(error48)) {
        return null;
      }
      throw error48;
    }
  }
  async save(agent) {
    await this.adapter.write(this.resolvePath(agent), serializeAgent(agent));
  }
  async delete(agent) {
    await this.adapter.delete(this.resolvePath(agent));
  }
  resolvePath(agent) {
    if (!agent.filePath) {
      return `${AGENTS_PATH}/${agent.name}.md`;
    }
    const normalized = agent.filePath.replace(/\\/g, "/");
    const idx = normalized.lastIndexOf(`${AGENTS_PATH}/`);
    if (idx !== -1) {
      return normalized.slice(idx);
    }
    return `${AGENTS_PATH}/${agent.name}.md`;
  }
  isFileNotFoundError(error48) {
    if (!error48) return false;
    if (typeof error48 === "string") {
      return /enoent|not found|no such file/i.test(error48);
    }
    if (typeof error48 === "object") {
      const maybeCode = error48.code;
      if (typeof maybeCode === "string" && /enoent|not.?found/i.test(maybeCode)) {
        return true;
      }
      const maybeMessage = error48.message;
      if (typeof maybeMessage === "string" && /enoent|not found|no such file/i.test(maybeMessage)) {
        return true;
      }
    }
    return false;
  }
};

// src/providers/claude/storage/CCSettingsStorage.ts
var CC_SETTINGS_PATH = ".claude/settings.json";
var CC_SETTINGS_SCHEMA = "https://json.schemastore.org/claude-code-settings.json";
function normalizeRuleList(value) {
  if (!Array.isArray(value)) return [];
  return value.filter((r2) => typeof r2 === "string");
}
function normalizePermissions(permissions) {
  if (!permissions || typeof permissions !== "object") {
    return { ...DEFAULT_CC_PERMISSIONS };
  }
  const p = permissions;
  return {
    allow: normalizeRuleList(p.allow),
    deny: normalizeRuleList(p.deny),
    ask: normalizeRuleList(p.ask),
    defaultMode: typeof p.defaultMode === "string" ? p.defaultMode : void 0,
    additionalDirectories: Array.isArray(p.additionalDirectories) ? p.additionalDirectories.filter((d6) => typeof d6 === "string") : void 0
  };
}
var CCSettingsStorage = class {
  constructor(adapter) {
    this.adapter = adapter;
  }
  async load() {
    if (!await this.adapter.exists(CC_SETTINGS_PATH)) {
      return { ...DEFAULT_CC_SETTINGS };
    }
    const content = await this.adapter.read(CC_SETTINGS_PATH);
    const stored = JSON.parse(content);
    return {
      $schema: CC_SETTINGS_SCHEMA,
      ...stored,
      permissions: normalizePermissions(stored.permissions)
    };
  }
  async save(settings11) {
    var _a3;
    let existing = {};
    if (await this.adapter.exists(CC_SETTINGS_PATH)) {
      try {
        const content2 = await this.adapter.read(CC_SETTINGS_PATH);
        existing = JSON.parse(content2);
      } catch (e2) {
      }
    }
    const merged = {
      ...existing,
      $schema: CC_SETTINGS_SCHEMA,
      permissions: (_a3 = settings11.permissions) != null ? _a3 : { ...DEFAULT_CC_PERMISSIONS }
    };
    if (settings11.enabledPlugins !== void 0) {
      merged.enabledPlugins = settings11.enabledPlugins;
    }
    const content = JSON.stringify(merged, null, 2);
    await this.adapter.write(CC_SETTINGS_PATH, content);
  }
  async exists() {
    return this.adapter.exists(CC_SETTINGS_PATH);
  }
  async getPermissions() {
    var _a3;
    const settings11 = await this.load();
    return (_a3 = settings11.permissions) != null ? _a3 : { ...DEFAULT_CC_PERMISSIONS };
  }
  async updatePermissions(permissions) {
    const settings11 = await this.load();
    settings11.permissions = permissions;
    await this.save(settings11);
  }
  async addAllowRule(rule) {
    var _a3, _b2;
    const permissions = await this.getPermissions();
    if (!((_a3 = permissions.allow) == null ? void 0 : _a3.includes(rule))) {
      permissions.allow = [...(_b2 = permissions.allow) != null ? _b2 : [], rule];
      await this.updatePermissions(permissions);
    }
  }
  async addDenyRule(rule) {
    var _a3, _b2;
    const permissions = await this.getPermissions();
    if (!((_a3 = permissions.deny) == null ? void 0 : _a3.includes(rule))) {
      permissions.deny = [...(_b2 = permissions.deny) != null ? _b2 : [], rule];
      await this.updatePermissions(permissions);
    }
  }
  async addAskRule(rule) {
    var _a3, _b2;
    const permissions = await this.getPermissions();
    if (!((_a3 = permissions.ask) == null ? void 0 : _a3.includes(rule))) {
      permissions.ask = [...(_b2 = permissions.ask) != null ? _b2 : [], rule];
      await this.updatePermissions(permissions);
    }
  }
  async removeRule(rule) {
    var _a3, _b2, _c;
    const permissions = await this.getPermissions();
    permissions.allow = (_a3 = permissions.allow) == null ? void 0 : _a3.filter((r2) => r2 !== rule);
    permissions.deny = (_b2 = permissions.deny) == null ? void 0 : _b2.filter((r2) => r2 !== rule);
    permissions.ask = (_c = permissions.ask) == null ? void 0 : _c.filter((r2) => r2 !== rule);
    await this.updatePermissions(permissions);
  }
  async getEnabledPlugins() {
    var _a3;
    const settings11 = await this.load();
    return (_a3 = settings11.enabledPlugins) != null ? _a3 : {};
  }
  async setPluginEnabled(pluginId, enabled) {
    var _a3;
    const settings11 = await this.load();
    const enabledPlugins = (_a3 = settings11.enabledPlugins) != null ? _a3 : {};
    enabledPlugins[pluginId] = enabled;
    settings11.enabledPlugins = enabledPlugins;
    await this.save(settings11);
  }
  async getExplicitlyEnabledPluginIds() {
    const enabledPlugins = await this.getEnabledPlugins();
    return Object.entries(enabledPlugins).filter(([, enabled]) => enabled).map(([id]) => id);
  }
  async isPluginDisabled(pluginId) {
    const enabledPlugins = await this.getEnabledPlugins();
    return enabledPlugins[pluginId] === false;
  }
};

// src/core/types/chat.ts
var VIEW_TYPE_CLAUDIAN = "claudian-view";

// src/core/types/mcp.ts
function getMcpServerType(config2) {
  if (config2.type === "sse") return "sse";
  if (config2.type === "http") return "http";
  if ("url" in config2) return "http";
  return "stdio";
}
function isValidMcpServerConfig(obj) {
  if (!obj || typeof obj !== "object") return false;
  const config2 = obj;
  if (config2.command && typeof config2.command === "string") return true;
  if (config2.url && typeof config2.url === "string") return true;
  return false;
}
var DEFAULT_MCP_SERVER = {
  enabled: true,
  contextSaving: true
};

// src/providers/claude/storage/McpStorage.ts
var MCP_CONFIG_PATH = ".claude/mcp.json";
var McpStorage = class {
  constructor(adapter) {
    this.adapter = adapter;
  }
  async load() {
    var _a3, _b2, _c, _d2, _e;
    try {
      if (!await this.adapter.exists(MCP_CONFIG_PATH)) {
        return [];
      }
      const content = await this.adapter.read(MCP_CONFIG_PATH);
      const file2 = JSON.parse(content);
      if (!file2.mcpServers || typeof file2.mcpServers !== "object") {
        return [];
      }
      const claudianMeta = (_b2 = (_a3 = file2._claudian) == null ? void 0 : _a3.servers) != null ? _b2 : {};
      const servers = [];
      for (const [name, config2] of Object.entries(file2.mcpServers)) {
        if (!isValidMcpServerConfig(config2)) {
          continue;
        }
        const meta3 = (_c = claudianMeta[name]) != null ? _c : {};
        const disabledTools = Array.isArray(meta3.disabledTools) ? meta3.disabledTools.filter((tool) => typeof tool === "string") : void 0;
        const normalizedDisabledTools = disabledTools && disabledTools.length > 0 ? disabledTools : void 0;
        servers.push({
          name,
          config: config2,
          enabled: (_d2 = meta3.enabled) != null ? _d2 : DEFAULT_MCP_SERVER.enabled,
          contextSaving: (_e = meta3.contextSaving) != null ? _e : DEFAULT_MCP_SERVER.contextSaving,
          disabledTools: normalizedDisabledTools,
          description: meta3.description
        });
      }
      return servers;
    } catch (e2) {
      return [];
    }
  }
  async save(servers) {
    var _a3;
    const mcpServers = {};
    const claudianServers = {};
    for (const server of servers) {
      mcpServers[server.name] = server.config;
      const meta3 = {};
      if (server.enabled !== DEFAULT_MCP_SERVER.enabled) {
        meta3.enabled = server.enabled;
      }
      if (server.contextSaving !== DEFAULT_MCP_SERVER.contextSaving) {
        meta3.contextSaving = server.contextSaving;
      }
      const normalizedDisabledTools = (_a3 = server.disabledTools) == null ? void 0 : _a3.map((tool) => tool.trim()).filter((tool) => tool.length > 0);
      if (normalizedDisabledTools && normalizedDisabledTools.length > 0) {
        meta3.disabledTools = normalizedDisabledTools;
      }
      if (server.description) {
        meta3.description = server.description;
      }
      if (Object.keys(meta3).length > 0) {
        claudianServers[server.name] = meta3;
      }
    }
    let existing = null;
    if (await this.adapter.exists(MCP_CONFIG_PATH)) {
      try {
        const raw = await this.adapter.read(MCP_CONFIG_PATH);
        const parsed = JSON.parse(raw);
        if (parsed && typeof parsed === "object") {
          existing = parsed;
        }
      } catch (e2) {
        existing = null;
      }
    }
    const file2 = existing ? { ...existing } : {};
    file2.mcpServers = mcpServers;
    const existingClaudian = existing && typeof existing._claudian === "object" ? existing._claudian : null;
    if (Object.keys(claudianServers).length > 0) {
      file2._claudian = { ...existingClaudian != null ? existingClaudian : {}, servers: claudianServers };
    } else if (existingClaudian) {
      const { servers: _servers, ...rest } = existingClaudian;
      if (Object.keys(rest).length > 0) {
        file2._claudian = rest;
      } else {
        delete file2._claudian;
      }
    } else {
      delete file2._claudian;
    }
    const content = JSON.stringify(file2, null, 2);
    await this.adapter.write(MCP_CONFIG_PATH, content);
  }
  async exists() {
    return this.adapter.exists(MCP_CONFIG_PATH);
  }
};

// src/providers/claude/storage/SkillStorage.ts
var SKILLS_PATH = ".claude/skills";
var SkillStorage = class {
  constructor(adapter) {
    this.adapter = adapter;
  }
  async loadAll() {
    const skills = [];
    try {
      const folders = await this.adapter.listFolders(SKILLS_PATH);
      for (const folder of folders) {
        const skillName = folder.split("/").pop();
        const skillPath = `${SKILLS_PATH}/${skillName}/SKILL.md`;
        try {
          if (!await this.adapter.exists(skillPath)) continue;
          const content = await this.adapter.read(skillPath);
          const parsed = parseSlashCommandContent(content);
          skills.push({
            ...parsedToSlashCommand(parsed, {
              id: `skill-${skillName}`,
              name: skillName,
              source: "user"
            }),
            kind: "skill"
          });
        } catch (e2) {
        }
      }
    } catch (e2) {
      return [];
    }
    return skills;
  }
  async save(skill) {
    const name = skill.name;
    const dirPath = `${SKILLS_PATH}/${name}`;
    const filePath = `${dirPath}/SKILL.md`;
    await this.adapter.ensureFolder(dirPath);
    await this.adapter.write(filePath, serializeCommand(skill));
  }
  async delete(skillId) {
    const name = skillId.replace(/^skill-/, "");
    const dirPath = `${SKILLS_PATH}/${name}`;
    const filePath = `${dirPath}/SKILL.md`;
    await this.adapter.delete(filePath);
    await this.adapter.deleteFolder(dirPath);
  }
};

// src/providers/claude/storage/SlashCommandStorage.ts
var COMMANDS_PATH = ".claude/commands";
var SlashCommandStorage = class {
  constructor(adapter) {
    this.adapter = adapter;
  }
  async loadAll() {
    const commands = [];
    try {
      const files = await this.adapter.listFilesRecursive(COMMANDS_PATH);
      for (const filePath of files) {
        if (!filePath.endsWith(".md")) continue;
        try {
          const command = await this.loadFromFile(filePath);
          if (command) {
            commands.push(command);
          }
        } catch (e2) {
        }
      }
    } catch (e2) {
    }
    return commands;
  }
  async loadFromFile(filePath) {
    const content = await this.adapter.read(filePath);
    return this.parseFile(content, filePath);
  }
  async save(command) {
    const filePath = this.getFilePath(command);
    await this.adapter.write(filePath, serializeCommand(command));
  }
  async delete(commandId) {
    const files = await this.adapter.listFilesRecursive(COMMANDS_PATH);
    for (const filePath of files) {
      if (!filePath.endsWith(".md")) continue;
      const id = this.filePathToId(filePath);
      if (id === commandId) {
        await this.adapter.delete(filePath);
        return;
      }
    }
  }
  getFilePath(command) {
    const safeName = command.name.replace(/[^a-zA-Z0-9_/-]/g, "-");
    return `${COMMANDS_PATH}/${safeName}.md`;
  }
  parseFile(content, filePath) {
    const parsed = parseSlashCommandContent(content);
    return {
      ...parsedToSlashCommand(parsed, {
        id: this.filePathToId(filePath),
        name: this.filePathToName(filePath)
      }),
      kind: "command"
    };
  }
  filePathToId(filePath) {
    const relativePath = filePath.replace(`${COMMANDS_PATH}/`, "").replace(/\.md$/, "");
    const escaped = relativePath.replace(/-/g, "-_").replace(/\//g, "--");
    return `cmd-${escaped}`;
  }
  filePathToName(filePath) {
    return filePath.replace(`${COMMANDS_PATH}/`, "").replace(/\.md$/, "");
  }
};

// src/providers/claude/storage/StorageService.ts
var CLAUDE_PATH = ".claude";
var StorageService = class {
  constructor(plugin, adapter) {
    this.plugin = plugin;
    this.app = plugin.app;
    this.adapter = adapter != null ? adapter : new VaultFileAdapter(this.app);
    this.ccSettings = new CCSettingsStorage(this.adapter);
    this.claudianSettings = new ClaudianSettingsStorage(this.adapter);
    this.commands = new SlashCommandStorage(this.adapter);
    this.skills = new SkillStorage(this.adapter);
    this.sessions = new SessionStorage(this.adapter);
    this.mcp = new McpStorage(this.adapter);
    this.agents = new AgentVaultStorage(this.adapter);
  }
  async initialize() {
    await this.ensureDirectories();
    const cc = await this.ccSettings.load();
    const claudian = await this.claudianSettings.load();
    return { cc, claudian };
  }
  async ensureDirectories() {
    await this.adapter.ensureFolder(CLAUDE_PATH);
    await this.adapter.ensureFolder(CLAUDIAN_STORAGE_PATH);
    await this.adapter.ensureFolder(COMMANDS_PATH);
    await this.adapter.ensureFolder(SKILLS_PATH);
    await this.adapter.ensureFolder(SESSIONS_PATH);
    await this.adapter.ensureFolder(AGENTS_PATH);
  }
  async loadAllSlashCommands() {
    const commands = await this.commands.loadAll();
    const skills = await this.skills.loadAll();
    return [...commands, ...skills];
  }
  getAdapter() {
    return this.adapter;
  }
  async getPermissions() {
    return this.ccSettings.getPermissions();
  }
  async updatePermissions(permissions) {
    return this.ccSettings.updatePermissions(permissions);
  }
  async addAllowRule(rule) {
    return this.ccSettings.addAllowRule(createPermissionRule(rule));
  }
  async addDenyRule(rule) {
    return this.ccSettings.addDenyRule(createPermissionRule(rule));
  }
  async removePermissionRule(rule) {
    return this.ccSettings.removeRule(createPermissionRule(rule));
  }
  async updateClaudianSettings(updates) {
    return this.claudianSettings.update(updates);
  }
  async saveClaudianSettings(settings11) {
    return this.claudianSettings.save(settings11);
  }
  async loadClaudianSettings() {
    return this.claudianSettings.load();
  }
  async getTabManagerState() {
    try {
      const data = await this.plugin.loadData();
      if (data == null ? void 0 : data.tabManagerState) {
        return this.validateTabManagerState(data.tabManagerState);
      }
      return null;
    } catch (e2) {
      return null;
    }
  }
  validateTabManagerState(data) {
    if (!data || typeof data !== "object") {
      return null;
    }
    const state = data;
    if (!Array.isArray(state.openTabs)) {
      return null;
    }
    const validatedTabs = [];
    for (const tab of state.openTabs) {
      if (!tab || typeof tab !== "object") {
        continue;
      }
      const tabObj = tab;
      if (typeof tabObj.tabId !== "string") {
        continue;
      }
      validatedTabs.push({
        tabId: tabObj.tabId,
        conversationId: typeof tabObj.conversationId === "string" ? tabObj.conversationId : null,
        ...typeof tabObj.draftModel === "string" ? { draftModel: tabObj.draftModel } : {}
      });
    }
    const activeTabId = typeof state.activeTabId === "string" ? state.activeTabId : null;
    return {
      openTabs: validatedTabs,
      activeTabId
    };
  }
  async setTabManagerState(state) {
    try {
      const data = await this.plugin.loadData() || {};
      data.tabManagerState = state;
      await this.plugin.saveData(data);
    } catch (e2) {
      new import_obsidian3.Notice("Failed to save tab layout");
    }
  }
};

// src/providers/claude/ui/ClaudeSettingsTab.ts
var fs8 = __toESM(require("fs"));
var import_obsidian13 = require("obsidian");

// src/core/providers/ProviderSettingsCoordinator.ts
var PROJECTION_KEYS = /* @__PURE__ */ new Set([
  "model",
  "effortLevel",
  "serviceTier",
  "thinkingBudget",
  "permissionMode"
]);
function getSettingsProviderId(settings11) {
  return ProviderRegistry.resolveSettingsProviderId(settings11);
}
function ensureProjectionMap(settings11, key) {
  const current = settings11[key];
  if (current && typeof current === "object") {
    return current;
  }
  const next = {};
  settings11[key] = next;
  return next;
}
function cloneProviderSettings(settings11) {
  return {
    ...settings11,
    savedProviderModel: { ...settings11.savedProviderModel },
    savedProviderEffort: { ...settings11.savedProviderEffort },
    savedProviderServiceTier: { ...settings11.savedProviderServiceTier },
    savedProviderThinkingBudget: { ...settings11.savedProviderThinkingBudget },
    savedProviderPermissionMode: { ...settings11.savedProviderPermissionMode }
  };
}
function normalizeToggleValue(value, allowedValues) {
  if (typeof value !== "string") {
    return void 0;
  }
  return allowedValues.has(value) ? value : void 0;
}
function mergeProviderSettings(target, source) {
  for (const [key, value] of Object.entries(source)) {
    if (PROJECTION_KEYS.has(key)) {
      continue;
    }
    target[key] = value;
  }
}
function normalizeReasoningValue(uiConfig, settings11, model, value) {
  const allowedValues = new Set(uiConfig.getReasoningOptions(model, settings11).map((option) => option.value));
  if (typeof value === "string" && allowedValues.has(value)) {
    return value;
  }
  return uiConfig.getDefaultReasoningValue(model, settings11);
}
function normalizeProviderModel(uiConfig, settings11, model) {
  if (!model) {
    return void 0;
  }
  return uiConfig.normalizeModelVariant(model, settings11);
}
var ProviderSettingsCoordinator = class {
  static handleEnvironmentChange(settings11, providerIds) {
    var _a3;
    let anyChanged = false;
    for (const providerId of providerIds) {
      const reconciler = ProviderRegistry.getSettingsReconciler(providerId);
      if ((_a3 = reconciler.handleEnvironmentChange) == null ? void 0 : _a3.call(reconciler, settings11)) {
        anyChanged = true;
      }
    }
    return anyChanged;
  }
  static reconcileTitleGenerationModelSelection(settings11) {
    const currentModel = typeof settings11.titleGenerationModel === "string" ? settings11.titleGenerationModel : "";
    if (!currentModel) {
      return false;
    }
    const isValid2 = ProviderRegistry.getRegisteredProviderIds().some(
      (providerId) => ProviderRegistry.getChatUIConfig(providerId).getModelOptions(settings11).some((option) => option.value === currentModel)
    );
    if (isValid2) {
      return false;
    }
    settings11.titleGenerationModel = "";
    return true;
  }
  static normalizeProviderSelection(settings11) {
    const next = getSettingsProviderId(settings11);
    if (settings11.settingsProvider === next) {
      return false;
    }
    settings11.settingsProvider = next;
    return true;
  }
  static getProviderSettingsSnapshot(settings11, providerId) {
    const snapshot = cloneProviderSettings(settings11);
    this.projectProviderState(snapshot, providerId);
    return snapshot;
  }
  static commitProviderSettingsSnapshot(settings11, providerId, snapshot) {
    this.persistProjectedProviderState(snapshot, providerId);
    if (providerId === getSettingsProviderId(settings11)) {
      Object.assign(settings11, snapshot);
      return;
    }
    mergeProviderSettings(settings11, snapshot);
  }
  static persistProjectedProviderState(settings11, providerId = getSettingsProviderId(settings11)) {
    var _a3, _b2, _c;
    const savedModel = ensureProjectionMap(settings11, "savedProviderModel");
    const savedEffort = ensureProjectionMap(settings11, "savedProviderEffort");
    const savedServiceTier = ensureProjectionMap(settings11, "savedProviderServiceTier");
    const savedBudget = ensureProjectionMap(settings11, "savedProviderThinkingBudget");
    const savedPermissionMode = ensureProjectionMap(settings11, "savedProviderPermissionMode");
    const uiConfig = ProviderRegistry.getChatUIConfig(providerId);
    const normalizedModel = normalizeProviderModel(
      uiConfig,
      settings11,
      typeof settings11.model === "string" ? settings11.model : void 0
    );
    const projectedSettings = normalizedModel && normalizedModel !== settings11.model ? { ...settings11, model: normalizedModel } : settings11;
    if (normalizedModel) {
      savedModel[providerId] = normalizedModel;
    }
    if (typeof settings11.effortLevel === "string") {
      savedEffort[providerId] = settings11.effortLevel;
    }
    const serviceTierToggle = (_b2 = (_a3 = uiConfig.getServiceTierToggle) == null ? void 0 : _a3.call(uiConfig, projectedSettings)) != null ? _b2 : null;
    if (serviceTierToggle && typeof settings11.serviceTier === "string") {
      savedServiceTier[providerId] = settings11.serviceTier;
    }
    if (typeof settings11.thinkingBudget === "string") {
      savedBudget[providerId] = settings11.thinkingBudget;
    }
    if (typeof settings11.permissionMode === "string" && ((_c = uiConfig.getPermissionModeToggle) == null ? void 0 : _c.call(uiConfig))) {
      savedPermissionMode[providerId] = settings11.permissionMode;
    }
  }
  static projectProviderState(settings11, providerId) {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l;
    const uiConfig = ProviderRegistry.getChatUIConfig(providerId);
    const savedModel = settings11.savedProviderModel;
    const savedEffort = settings11.savedProviderEffort;
    const savedServiceTier = settings11.savedProviderServiceTier;
    const savedBudget = settings11.savedProviderThinkingBudget;
    const savedPermissionMode = settings11.savedProviderPermissionMode;
    const shouldPreferCurrentProjection = providerId === getSettingsProviderId(settings11);
    const currentModelRaw = typeof settings11.model === "string" ? settings11.model : "";
    const currentModel = shouldPreferCurrentProjection ? (_a3 = normalizeProviderModel(uiConfig, settings11, currentModelRaw)) != null ? _a3 : "" : currentModelRaw;
    const currentEffort = typeof settings11.effortLevel === "string" ? settings11.effortLevel : void 0;
    const currentServiceTier = typeof settings11.serviceTier === "string" ? settings11.serviceTier : void 0;
    const currentBudget = typeof settings11.thinkingBudget === "string" ? settings11.thinkingBudget : void 0;
    const modelOptions = uiConfig.getModelOptions(settings11);
    const isDefaultModelOfAnotherProvider = currentModel.length > 0 && ProviderRegistry.getRegisteredProviderIds().filter((id) => id !== providerId).some((id) => ProviderRegistry.getChatUIConfig(id).isDefaultModel(currentModel));
    const canReuseCurrentModel = currentModel.length > 0 && !isDefaultModelOfAnotherProvider && (shouldPreferCurrentProjection || modelOptions.some((option) => option.value === currentModel));
    const fallbackModel = canReuseCurrentModel ? currentModel : (_c = (_b2 = modelOptions[0]) == null ? void 0 : _b2.value) != null ? _c : currentModel;
    const savedModelValue = normalizeProviderModel(uiConfig, settings11, savedModel == null ? void 0 : savedModel[providerId]);
    const isSavedModelValid = savedModelValue !== void 0 && modelOptions.some((option) => option.value === savedModelValue);
    const model = (_d2 = isSavedModelValid ? savedModelValue : void 0) != null ? _d2 : fallbackModel;
    const canReuseCurrentProjection = canReuseCurrentModel && model === currentModel;
    if (model) {
      settings11.model = model;
      uiConfig.applyModelDefaults(model, settings11);
    }
    const serviceTierToggle = (_f = (_e = uiConfig.getServiceTierToggle) == null ? void 0 : _e.call(uiConfig, {
      ...settings11,
      ...model ? { model } : {}
    })) != null ? _f : null;
    const isAdaptive = Boolean(model) && uiConfig.isAdaptiveReasoningModel(model, settings11);
    if ((savedEffort == null ? void 0 : savedEffort[providerId]) !== void 0) {
      settings11.effortLevel = savedEffort[providerId];
    } else if (canReuseCurrentProjection && currentEffort !== void 0) {
      settings11.effortLevel = currentEffort;
    } else if (isAdaptive) {
      settings11.effortLevel = uiConfig.getDefaultReasoningValue(model, settings11);
    }
    if (isAdaptive) {
      settings11.effortLevel = normalizeReasoningValue(uiConfig, settings11, model, settings11.effortLevel);
    }
    if ((savedServiceTier == null ? void 0 : savedServiceTier[providerId]) !== void 0) {
      settings11.serviceTier = savedServiceTier[providerId];
    } else if (canReuseCurrentProjection && currentServiceTier !== void 0) {
      settings11.serviceTier = currentServiceTier;
    } else {
      settings11.serviceTier = (_g = serviceTierToggle == null ? void 0 : serviceTierToggle.inactiveValue) != null ? _g : "default";
    }
    const usesBudget = Boolean(model) && !isAdaptive;
    if ((savedBudget == null ? void 0 : savedBudget[providerId]) !== void 0) {
      settings11.thinkingBudget = savedBudget[providerId];
    } else if (canReuseCurrentProjection && currentBudget !== void 0) {
      settings11.thinkingBudget = currentBudget;
    } else if (usesBudget) {
      settings11.thinkingBudget = uiConfig.getDefaultReasoningValue(model, settings11);
    }
    if (usesBudget) {
      settings11.thinkingBudget = normalizeReasoningValue(uiConfig, settings11, model, settings11.thinkingBudget);
    }
    const permissionToggle = (_i = (_h = uiConfig.getPermissionModeToggle) == null ? void 0 : _h.call(uiConfig)) != null ? _i : null;
    if (!permissionToggle) {
      return;
    }
    const allowedPermissionModes = /* @__PURE__ */ new Set([
      permissionToggle.inactiveValue,
      permissionToggle.activeValue,
      ...permissionToggle.planValue ? [permissionToggle.planValue] : []
    ]);
    const currentPermissionMode = normalizeToggleValue(settings11.permissionMode, allowedPermissionModes);
    const derivedPermissionMode = normalizeToggleValue(
      (_j2 = uiConfig.resolvePermissionMode) == null ? void 0 : _j2.call(uiConfig, settings11),
      allowedPermissionModes
    );
    const savedPermissionModeValue = normalizeToggleValue(
      savedPermissionMode == null ? void 0 : savedPermissionMode[providerId],
      allowedPermissionModes
    );
    const projectedPermissionMode = (_l = (_k = savedPermissionModeValue != null ? savedPermissionModeValue : derivedPermissionMode) != null ? _k : shouldPreferCurrentProjection ? currentPermissionMode : void 0) != null ? _l : currentPermissionMode;
    if (projectedPermissionMode !== void 0) {
      settings11.permissionMode = projectedPermissionMode;
    }
  }
  /** Each provider's reconciler only processes its own conversations. */
  static reconcileAllProviders(settings11, conversations) {
    return this.reconcileProviders(
      settings11,
      conversations,
      ProviderRegistry.getRegisteredProviderIds()
    );
  }
  static reconcileProviders(settings11, conversations, providerIds) {
    let anyChanged = false;
    const allInvalidated = [];
    const settingsProvider = getSettingsProviderId(settings11);
    for (const providerId of providerIds) {
      const reconciler = ProviderRegistry.getSettingsReconciler(providerId);
      const providerConversations = conversations.filter((c) => c.providerId === providerId);
      const targetSettings = providerId === settingsProvider ? settings11 : cloneProviderSettings(settings11);
      if (providerId !== settingsProvider) {
        this.projectProviderState(targetSettings, providerId);
      }
      const { changed, invalidatedConversations } = reconciler.reconcileModelWithEnvironment(
        targetSettings,
        providerConversations
      );
      if (changed) {
        anyChanged = true;
        this.persistProjectedProviderState(targetSettings, providerId);
        if (providerId !== settingsProvider) {
          mergeProviderSettings(settings11, targetSettings);
        }
      }
      allInvalidated.push(...invalidatedConversations);
    }
    if (this.reconcileTitleGenerationModelSelection(settings11)) {
      anyChanged = true;
    }
    return { changed: anyChanged, invalidatedConversations: allInvalidated };
  }
  static normalizeAllModelVariants(settings11) {
    let anyChanged = false;
    const settingsProvider = getSettingsProviderId(settings11);
    for (const providerId of ProviderRegistry.getRegisteredProviderIds()) {
      const reconciler = ProviderRegistry.getSettingsReconciler(providerId);
      const targetSettings = providerId === settingsProvider ? settings11 : cloneProviderSettings(settings11);
      if (providerId !== settingsProvider) {
        this.projectProviderState(targetSettings, providerId);
      }
      const changed = reconciler.normalizeModelVariantSettings(targetSettings);
      if (changed) {
        anyChanged = true;
        this.persistProjectedProviderState(targetSettings, providerId);
        if (providerId !== settingsProvider) {
          mergeProviderSettings(settings11, targetSettings);
        }
      }
    }
    if (this.reconcileTitleGenerationModelSelection(settings11)) {
      anyChanged = true;
    }
    return anyChanged;
  }
  /**
   * Project the settings provider's saved values into the top-level
   * model/effortLevel/thinkingBudget fields.
   */
  static projectActiveProviderState(settings11) {
    this.projectProviderState(settings11, getSettingsProviderId(settings11));
  }
};

// src/features/settings/ui/EnvironmentSettingsSection.ts
var import_obsidian5 = require("obsidian");

// src/features/settings/ui/EnvSnippetManager.ts
var import_obsidian4 = require("obsidian");

// src/i18n/locales/de.json
var de_exports = {};
__export(de_exports, {
  chat: () => chat,
  common: () => common,
  default: () => de_default,
  settings: () => settings
});
var common = {
  save: "Speichern",
  cancel: "Abbrechen",
  delete: "L\xF6schen",
  edit: "Bearbeiten",
  add: "Hinzuf\xFCgen",
  remove: "Entfernen",
  clear: "L\xF6schen",
  clearAll: "Alle l\xF6schen",
  loading: "L\xE4dt",
  error: "Fehler",
  success: "Erfolg",
  warning: "Warnung",
  confirm: "Best\xE4tigen",
  settings: "Einstellungen",
  advanced: "Erweitert",
  enabled: "Aktiviert",
  disabled: "Deaktiviert",
  platform: "Plattform",
  refresh: "Aktualisieren",
  rewind: "Zur\xFCckspulen"
};
var chat = {
  rewind: {
    confirmMessage: "Zu diesem Punkt zur\xFCckspulen? Datei\xE4nderungen nach dieser Nachricht werden r\xFCckg\xE4ngig gemacht. Das Zur\xFCckspulen betrifft keine manuell oder \xFCber Bash bearbeiteten Dateien.",
    confirmButton: "Zur\xFCckspulen",
    ariaLabel: "Hierher zur\xFCckspulen",
    notice: "Zur\xFCckgespult: {count} Datei(en) wiederhergestellt",
    noticeSaveFailed: "Zur\xFCckgespult: {count} Datei(en) wiederhergestellt, aber Status konnte nicht gespeichert werden: {error}",
    failed: "Zur\xFCckspulen fehlgeschlagen: {error}",
    cannot: "Zur\xFCckspulen nicht m\xF6glich: {error}",
    unavailableStreaming: "Zur\xFCckspulen w\xE4hrend des Streamings nicht m\xF6glich",
    unavailableNoUuid: "Zur\xFCckspulen nicht m\xF6glich: Nachrichtenkennungen fehlen"
  },
  fork: {
    ariaLabel: "Konversation verzweigen",
    chooseTarget: "Konversation verzweigen",
    targetNewTab: "Neuer Tab",
    targetCurrentTab: "Aktueller Tab",
    maxTabsReached: "Verzweigung nicht m\xF6glich: maximal {count} Tabs erreicht",
    notice: "In neuem Tab verzweigt",
    noticeCurrentTab: "Im aktuellen Tab verzweigt",
    failed: "Verzweigung fehlgeschlagen: {error}",
    unavailableStreaming: "Verzweigung w\xE4hrend des Streamings nicht m\xF6glich",
    unavailableNoUuid: "Verzweigung nicht m\xF6glich: Nachrichtenkennungen fehlen",
    unavailableNoResponse: "Verzweigung nicht m\xF6glich: keine Antwort zum Verzweigen vorhanden",
    errorMessageNotFound: "Nachricht nicht gefunden",
    errorNoSession: "Keine Sitzungs-ID verf\xFCgbar",
    errorNoActiveTab: "Kein aktiver Tab",
    commandNoMessages: "Verzweigung nicht m\xF6glich: keine Nachrichten in der Konversation",
    commandNoAssistantUuid: "Verzweigung nicht m\xF6glich: keine Assistentenantwort mit Kennungen"
  },
  bangBash: {
    placeholder: "> Einen Bash-Befehl ausf\xFChren...",
    commandPanel: "Befehlspanel",
    copyAriaLabel: "Neueste Befehlsausgabe kopieren",
    clearAriaLabel: "Bash-Ausgabe l\xF6schen",
    commandLabel: "{command}",
    statusLabel: "Status des Befehls: {status}",
    collapseOutput: "Befehlsausgabe einklappen",
    expandOutput: "Befehlsausgabe ausklappen",
    running: "Wird ausgef\xFChrt...",
    copyFailed: "Kopieren in die Zwischenablage fehlgeschlagen"
  }
};
var settings = {
  title: "Claudian Einstellungen",
  tabs: {
    general: "Allgemein",
    claude: "Claude",
    codex: "Codex"
  },
  display: "Anzeige",
  conversations: "Unterhaltungen",
  content: "Inhalte",
  input: "Eingabe",
  setup: "Einrichtung",
  models: "Modelle",
  experimental: "Experimentell",
  userName: {
    name: "Wie soll Claudian dich nennen?",
    desc: "Dein Name f\xFCr personalisierte Begr\xFC\xDFungen (leer lassen f\xFCr allgemeine Begr\xFC\xDFungen)"
  },
  excludedTags: {
    name: "Ausgeschlossene Tags",
    desc: "Notizen mit diesen Tags werden nicht automatisch als Kontext geladen (einer pro Zeile, ohne #)"
  },
  mediaFolder: {
    name: "Medienordner",
    desc: "Ordner mit Anh\xE4ngen/Bildern. Wenn Notizen ![[image.jpg]] verwenden, sucht Claude hier. Leer lassen f\xFCr Vault-Stammverzeichnis."
  },
  systemPrompt: {
    name: "Benutzerdefinierter System-Prompt",
    desc: "Zus\xE4tzliche Anweisungen, die an den Standard-System-Prompt angeh\xE4ngt werden"
  },
  autoTitle: {
    name: "Konversationstitel automatisch generieren",
    desc: "Generiert automatisch Konversationstitel nach der ersten Nutzernachricht."
  },
  titleModel: {
    name: "Titel-Generierungsmodell",
    desc: "Modell zur automatischen Generierung von Konversationstiteln.",
    auto: "Automatisch (Haiku)"
  },
  navMappings: {
    name: "Vim-Style Navigationszuordnungen",
    desc: 'Eine Zuordnung pro Zeile. Format: "map <Taste> <Aktion>" (Aktionen: scrollUp, scrollDown, focusInput).'
  },
  hotkeys: "Tastenk\xFCrzel",
  inlineEditHotkey: {
    name: "Inline-Bearbeitung",
    descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}",
    descNoKey: "Kein Tastenk\xFCrzel festgelegt",
    btnChange: "\xC4ndern",
    btnSet: "Festlegen"
  },
  openChatHotkey: {
    name: "Chat \xF6ffnen",
    descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}",
    descNoKey: "Kein Tastenk\xFCrzel festgelegt",
    btnChange: "\xC4ndern",
    btnSet: "Festlegen"
  },
  newSessionHotkey: {
    name: "Neue Sitzung",
    descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}",
    descNoKey: "Kein Tastenk\xFCrzel festgelegt",
    btnChange: "\xC4ndern",
    btnSet: "Festlegen"
  },
  newTabHotkey: {
    name: "Neuer Tab",
    descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}",
    descNoKey: "Kein Tastenk\xFCrzel festgelegt",
    btnChange: "\xC4ndern",
    btnSet: "Festlegen"
  },
  closeTabHotkey: {
    name: "Tab schlie\xDFen",
    descWithKey: "Aktuelles Tastenk\xFCrzel: {hotkey}",
    descNoKey: "Kein Tastenk\xFCrzel festgelegt",
    btnChange: "\xC4ndern",
    btnSet: "Festlegen"
  },
  slashCommands: {
    name: "Befehle und F\xE4higkeiten",
    desc: "Verwalte Vault-Befehle und -F\xE4higkeiten in .claude/commands/ und .claude/skills/. Ausgel\xF6st durch /Name."
  },
  hiddenSlashCommands: {
    name: "Ausgeblendete Befehle und F\xE4higkeiten",
    desc: "Bestimmte Befehle und F\xE4higkeiten aus dem Dropdown ausblenden. N\xFCtzlich, um Claude Code-Eintr\xE4ge auszublenden, die f\xFCr Claudian nicht relevant sind. Gib Namen ohne f\xFChrenden Schr\xE4gstrich ein, einen pro Zeile.",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "MCP-Server",
    desc: "Verwalte Vault-MCP-Serverkonfigurationen in .claude/mcp.json. Server mit Kontext-Speichermodus ben\xF6tigen @mention zur Aktivierung."
  },
  plugins: {
    name: "Claude Code-Plugins",
    desc: "Verwalte Claude Code Plugins aus ~/.claude/plugins. Aktivierte Plugins werden pro Vault in .claude/settings.json gespeichert."
  },
  subagents: {
    name: "Sub-Agenten",
    desc: "Verwalte Vault-Sub-Agenten in .claude/agents/. Jede Markdown-Datei definiert einen benutzerdefinierten Agenten.",
    noAgents: "Keine Sub-Agenten konfiguriert. Klicke auf +, um einen zu erstellen.",
    deleteConfirm: 'Sub-Agent "{name}" l\xF6schen?',
    saveFailed: "Sub-Agent konnte nicht gespeichert werden: {message}",
    refreshFailed: "Sub-Agenten konnten nicht aktualisiert werden: {message}",
    deleteFailed: "Sub-Agent konnte nicht gel\xF6scht werden: {message}",
    renameCleanupFailed: 'Warnung: Alte Datei f\xFCr "{name}" konnte nicht entfernt werden',
    created: 'Sub-Agent "{name}" erstellt',
    updated: 'Sub-Agent "{name}" aktualisiert',
    deleted: 'Sub-Agent "{name}" gel\xF6scht',
    duplicateName: 'Ein Agent mit dem Namen "{name}" existiert bereits',
    descriptionRequired: "Beschreibung ist erforderlich",
    promptRequired: "System-Prompt ist erforderlich",
    modal: {
      titleEdit: "Sub-Agent bearbeiten",
      titleAdd: "Sub-Agent hinzuf\xFCgen",
      name: "Name",
      nameDesc: "Nur Kleinbuchstaben, Zahlen und Bindestriche",
      namePlaceholder: "code-reviewer",
      description: "Beschreibung",
      descriptionDesc: "Kurzbeschreibung dieses Agenten",
      descriptionPlaceholder: "Pr\xFCft Code auf Fehler und Stil",
      advancedOptions: "Erweiterte Optionen",
      model: "Modell",
      modelDesc: "Modell\xFCberschreibung f\xFCr diesen Agenten",
      tools: "Tools",
      toolsDesc: "Kommagetrennte Liste zul\xE4ssiger Tools (leer = alle)",
      disallowedTools: "Nicht erlaubte Tools",
      disallowedToolsDesc: "Kommagetrennte Liste der zu verbietenden Tools",
      skills: "F\xE4higkeiten",
      skillsDesc: "Kommagetrennte Liste von F\xE4higkeiten",
      prompt: "System-Prompt",
      promptDesc: "Anweisungen f\xFCr den Agenten",
      promptPlaceholder: "Du bist ein Code-Reviewer. Analysiere den angegebenen Code auf..."
    }
  },
  safety: "Sicherheit",
  loadUserSettings: {
    name: "Benutzer-Claude-Einstellungen laden",
    desc: "L\xE4dt ~/.claude/settings.json. Wenn aktiviert, k\xF6nnen Benutzer-Claude-Code-Berechtigungsregeln den Sicherheitsmodus umgehen."
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "Umgebung",
  customVariables: {
    name: "Benutzerdefinierte Variablen",
    desc: "Umgebungsvariablen f\xFCr Claude SDK (KEY=VALUE-Format, eine pro Zeile). Export-Pr\xE4fix unterst\xFCtzt."
  },
  envSnippets: {
    name: "Snippets",
    addBtn: "Snippet hinzuf\xFCgen",
    noSnippets: "Keine gespeicherten Umgebungsvariablen-Snippets. Klicken Sie auf +, um Ihre aktuelle Konfiguration zu speichern.",
    nameRequired: "Bitte geben Sie einen Namen f\xFCr das Snippet ein",
    modal: {
      titleEdit: "Snippet bearbeiten",
      titleSave: "Snippet speichern",
      name: "Name",
      namePlaceholder: "Ein beschreibender Name f\xFCr diese Umgebungskonfiguration",
      description: "Beschreibung",
      descPlaceholder: "Optionale Beschreibung",
      envVars: "Umgebungsvariablen",
      envVarsPlaceholder: "KEY=VALUE-Format, eine pro Zeile (export-Pr\xE4fix unterst\xFCtzt)",
      save: "Speichern",
      update: "Aktualisieren",
      cancel: "Abbrechen"
    }
  },
  customContextLimits: {
    name: "Benutzerdefinierte Kontextlimits",
    desc: "Legen Sie die Kontextfenstergr\xF6\xDFen f\xFCr Ihre benutzerdefinierten Modelle fest. Leer lassen f\xFCr den Standardwert (200k Token).",
    invalid: "Ung\xFCltiges Format. Verwenden Sie: 256k, 1m oder exakte Anzahl (1000-10000000)."
  },
  enableOpus1M: {
    name: "Opus 1M Kontextfenster",
    desc: "Opus 1M in der Modellauswahl anzeigen. In Max-, Team- und Enterprise-Pl\xE4nen enthalten. API- und Pro-Nutzer ben\xF6tigen zus\xE4tzliche Nutzung."
  },
  enableSonnet1M: {
    name: "Sonnet 1M Kontextfenster",
    desc: "Sonnet 1M in der Modellauswahl anzeigen. Erfordert zus\xE4tzliche Nutzung bei Max-, Team- und Enterprise-Pl\xE4nen. API- und Pro-Nutzer ben\xF6tigen zus\xE4tzliche Nutzung."
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "Chrome-Erweiterung aktivieren",
    desc: "Erlaubt Claude die Interaktion mit Chrome \xFCber die claude-in-chrome-Erweiterung. Die Erweiterung muss installiert sein. Erfordert Neustart der Sitzung."
  },
  enableBangBash: {
    name: "Bash-Modus (!) aktivieren",
    desc: "Gib ! in ein leeres Eingabefeld ein, um den Bash-Modus zu starten. F\xFChrt Befehle direkt \xFCber Node.js child_process aus. Die Ansicht muss neu ge\xF6ffnet werden.",
    validation: {
      noNode: "Node.js wurde auf PATH nicht gefunden. Installiere Node.js oder pr\xFCfe deine PATH-Konfiguration."
    }
  },
  maxTabs: {
    name: "Maximale Chat-Tabs",
    desc: "Maximale Anzahl gleichzeitiger Chat-Tabs (3-10). Jeder Tab verwendet eine separate Claude-Sitzung.",
    warning: "Mehr als 5 Tabs k\xF6nnen Leistung und Speichernutzung beeintr\xE4chtigen."
  },
  tabBarPosition: {
    name: "Tab-Leiste Position",
    desc: "W\xE4hlen Sie, wo Tab-Badges und Aktionsschaltfl\xE4chen angezeigt werden",
    input: "\xDCber Eingabefeld (Standard)",
    header: "In Kopfzeile"
  },
  enableAutoScroll: {
    name: "Automatisches Scrollen w\xE4hrend Streaming",
    desc: "Automatisch nach unten scrollen, w\xE4hrend Claude Antworten streamt. Deaktivieren, um oben zu bleiben und von Anfang an zu lesen."
  },
  openInMainTab: {
    name: "Im Haupteditorbereich \xF6ffnen",
    desc: "Chat-Panel als Haupttab im zentralen Editorbereich statt in der rechten Seitenleiste \xF6ffnen"
  },
  cliPath: {
    name: "Claude CLI-Pfad",
    desc: "Benutzerdefinierter Pfad zum Claude Code CLI. Leer lassen f\xFCr automatische Erkennung.",
    descWindows: "F\xFCr den nativen Installer verwenden Sie claude.exe. F\xFCr npm/pnpm/yarn oder andere Paketmanager-Installationen verwenden Sie den cli.js-Pfad (nicht claude.cmd).",
    descUnix: 'F\xFCgen Sie die Ausgabe von "which claude" ein \u2014 funktioniert sowohl f\xFCr native als auch npm/pnpm/yarn-Installationen.',
    validation: {
      notExist: "Pfad existiert nicht",
      isDirectory: "Pfad ist ein Verzeichnis, keine Datei"
    }
  },
  language: {
    name: "Sprache",
    desc: "Anzeigesprache der Plugin-Oberfl\xE4che \xE4ndern"
  }
};
var de_default = {
  common,
  chat,
  settings
};

// src/i18n/locales/en.json
var en_exports = {};
__export(en_exports, {
  chat: () => chat2,
  common: () => common2,
  default: () => en_default,
  settings: () => settings2
});
var common2 = {
  save: "Save",
  cancel: "Cancel",
  delete: "Delete",
  edit: "Edit",
  add: "Add",
  remove: "Remove",
  clear: "Clear",
  clearAll: "Clear all",
  loading: "Loading",
  error: "Error",
  success: "Success",
  warning: "Warning",
  confirm: "Confirm",
  settings: "Settings",
  advanced: "Advanced",
  enabled: "Enabled",
  disabled: "Disabled",
  platform: "Platform",
  refresh: "Refresh",
  rewind: "Rewind"
};
var chat2 = {
  rewind: {
    confirmMessage: "Rewind to this point? File changes after this message will be reverted. Rewinding does not affect files edited manually or via bash.",
    confirmButton: "Rewind",
    ariaLabel: "Rewind to here",
    notice: "Rewound: {count} file(s) reverted",
    noticeSaveFailed: "Rewound: {count} file(s) reverted, but failed to save state: {error}",
    failed: "Rewind failed: {error}",
    cannot: "Cannot rewind: {error}",
    unavailableStreaming: "Cannot rewind while streaming",
    unavailableNoUuid: "Cannot rewind: missing message identifiers"
  },
  fork: {
    ariaLabel: "Fork conversation",
    chooseTarget: "Fork conversation",
    targetNewTab: "New tab",
    targetCurrentTab: "Current tab",
    maxTabsReached: "Cannot fork: maximum {count} tabs reached",
    notice: "Forked to new tab",
    noticeCurrentTab: "Forked in current tab",
    failed: "Fork failed: {error}",
    unavailableStreaming: "Cannot fork while streaming",
    unavailableNoUuid: "Cannot fork: missing message identifiers",
    unavailableNoResponse: "Cannot fork: no response to fork from",
    errorMessageNotFound: "Message not found",
    errorNoSession: "No session ID available",
    errorNoActiveTab: "No active tab",
    commandNoMessages: "Cannot fork: no messages in conversation",
    commandNoAssistantUuid: "Cannot fork: no assistant response with identifiers"
  },
  bangBash: {
    placeholder: "> Run a bash command...",
    commandPanel: "Command panel",
    copyAriaLabel: "Copy latest command output",
    clearAriaLabel: "Clear bash output",
    commandLabel: "{command}",
    statusLabel: "Status: {status}",
    collapseOutput: "Collapse command output",
    expandOutput: "Expand command output",
    running: "Running...",
    copyFailed: "Failed to copy to clipboard"
  }
};
var settings2 = {
  title: "Claudian Settings",
  tabs: {
    general: "General",
    claude: "Claude",
    codex: "Codex"
  },
  display: "Display",
  conversations: "Conversations",
  content: "Content",
  input: "Input",
  setup: "Setup",
  models: "Models",
  experimental: "Experimental",
  userName: {
    name: "What should Claudian call you?",
    desc: "Your name for personalized greetings (leave empty for generic greetings)"
  },
  excludedTags: {
    name: "Excluded tags",
    desc: "Notes with these tags will not auto-load as context (one per line, without #)"
  },
  mediaFolder: {
    name: "Media folder",
    desc: "Folder containing attachments/images. When notes use ![[image.jpg]], Claude will look here. Leave empty for vault root."
  },
  systemPrompt: {
    name: "Custom system prompt",
    desc: "Additional instructions appended to the default system prompt"
  },
  autoTitle: {
    name: "Auto-generate conversation titles",
    desc: "Automatically generate conversation titles after the first user message is sent."
  },
  titleModel: {
    name: "Title generation model",
    desc: "Model used for auto-generating conversation titles.",
    auto: "Auto (Haiku)"
  },
  navMappings: {
    name: "Vim-style navigation mappings",
    desc: 'One mapping per line. Format: "map <key> <action>" (actions: scrollUp, scrollDown, focusInput).'
  },
  hotkeys: "Hotkeys",
  inlineEditHotkey: {
    name: "Inline Edit",
    descWithKey: "Current hotkey: {hotkey}",
    descNoKey: "No hotkey set",
    btnChange: "Change",
    btnSet: "Set hotkey"
  },
  openChatHotkey: {
    name: "Open Chat",
    descWithKey: "Current hotkey: {hotkey}",
    descNoKey: "No hotkey set",
    btnChange: "Change",
    btnSet: "Set hotkey"
  },
  newSessionHotkey: {
    name: "New Session",
    descWithKey: "Current hotkey: {hotkey}",
    descNoKey: "No hotkey set",
    btnChange: "Change",
    btnSet: "Set hotkey"
  },
  newTabHotkey: {
    name: "New Tab",
    descWithKey: "Current hotkey: {hotkey}",
    descNoKey: "No hotkey set",
    btnChange: "Change",
    btnSet: "Set hotkey"
  },
  closeTabHotkey: {
    name: "Close Tab",
    descWithKey: "Current hotkey: {hotkey}",
    descNoKey: "No hotkey set",
    btnChange: "Change",
    btnSet: "Set hotkey"
  },
  slashCommands: {
    name: "Commands and Skills",
    desc: "Manage vault-level commands and skills stored in .claude/commands/ and .claude/skills/. Triggered by /name."
  },
  hiddenSlashCommands: {
    name: "Hidden Commands and Skills",
    desc: "Hide specific commands and skills from the dropdown. Useful for hiding Claude Code entries that are not relevant to Claudian. Enter names without the leading slash, one per line.",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "MCP Servers",
    desc: "Manage vault-level MCP server configurations stored in .claude/mcp.json. Servers with context-saving mode require @mention to activate."
  },
  plugins: {
    name: "Claude Code Plugins",
    desc: "Manage Claude Code plugins discovered from ~/.claude/plugins. Enabled plugins are stored per vault in .claude/settings.json."
  },
  subagents: {
    name: "Subagents",
    desc: "Manage vault-level subagents stored in .claude/agents/. Each Markdown file defines one custom agent.",
    noAgents: "No subagents configured. Click + to create one.",
    deleteConfirm: 'Delete subagent "{name}"?',
    saveFailed: "Failed to save subagent: {message}",
    refreshFailed: "Failed to refresh subagents: {message}",
    deleteFailed: "Failed to delete subagent: {message}",
    renameCleanupFailed: 'Warning: could not remove old file for "{name}"',
    created: 'Subagent "{name}" created',
    updated: 'Subagent "{name}" updated',
    deleted: 'Subagent "{name}" deleted',
    duplicateName: 'An agent named "{name}" already exists',
    descriptionRequired: "Description is required",
    promptRequired: "System prompt is required",
    modal: {
      titleEdit: "Edit Subagent",
      titleAdd: "Add Subagent",
      name: "Name",
      nameDesc: "Lowercase letters, numbers, and hyphens only",
      namePlaceholder: "code-reviewer",
      description: "Description",
      descriptionDesc: "Brief description of this agent",
      descriptionPlaceholder: "Reviews code for bugs and style",
      advancedOptions: "Advanced options",
      model: "Model",
      modelDesc: "Model override for this agent",
      tools: "Tools",
      toolsDesc: "Comma-separated list of allowed tools (empty = all)",
      disallowedTools: "Disallowed tools",
      disallowedToolsDesc: "Comma-separated list of tools to disallow",
      skills: "Skills",
      skillsDesc: "Comma-separated list of skills",
      prompt: "System prompt",
      promptDesc: "Instructions for the agent",
      promptPlaceholder: "You are a code reviewer. Analyze the given code for..."
    }
  },
  safety: "Safety",
  loadUserSettings: {
    name: "Load user Claude settings",
    desc: "Load ~/.claude/settings.json. When enabled, user's Claude Code permission rules may bypass Safe mode."
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "Environment",
  customVariables: {
    name: "Custom variables",
    desc: "Environment variables for Claude SDK (KEY=VALUE format, one per line). Shell export prefix supported."
  },
  envSnippets: {
    name: "Snippets",
    addBtn: "Add snippet",
    noSnippets: "No saved environment snippets yet. Click + to save your current environment configuration.",
    nameRequired: "Please enter a name for the snippet",
    modal: {
      titleEdit: "Edit snippet",
      titleSave: "Save snippet",
      name: "Name",
      namePlaceholder: "A descriptive name for this environment configuration",
      description: "Description",
      descPlaceholder: "Optional description",
      envVars: "Environment variables",
      envVarsPlaceholder: "KEY=VALUE format, one per line (export prefix supported)",
      save: "Save",
      update: "Update",
      cancel: "Cancel"
    }
  },
  customContextLimits: {
    name: "Custom Context Limits",
    desc: "Set context window sizes for your custom models. Leave empty to use the default (200k tokens).",
    invalid: "Invalid format. Use: 256k, 1m, or exact count (1000-10000000)."
  },
  enableOpus1M: {
    name: "Opus 1M context window",
    desc: "Show Opus 1M in the model selector. Included with Max, Team, and Enterprise plans. API and Pro users need extra usage."
  },
  enableSonnet1M: {
    name: "Sonnet 1M context window",
    desc: "Show Sonnet 1M in the model selector. Requires extra usage on Max, Team, and Enterprise plans. API and Pro users need extra usage."
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "Enable Chrome extension",
    desc: "Allow Claude to interact with Chrome via the claude-in-chrome extension. Requires the extension to be installed. Requires session restart."
  },
  enableBangBash: {
    name: "Enable bash mode (!)",
    desc: "Type ! on empty input to enter bash mode. Runs commands directly via Node.js child_process. Requires view reopen.",
    validation: {
      noNode: "Node.js not found on PATH. Install Node.js or check your PATH configuration."
    }
  },
  maxTabs: {
    name: "Maximum chat tabs",
    desc: "Maximum number of concurrent chat tabs (3-10). Each tab uses a separate Claude session.",
    warning: "More than 5 tabs may impact performance and memory usage."
  },
  tabBarPosition: {
    name: "Tab bar position",
    desc: "Choose where to display tab badges and action buttons",
    input: "Above input (default)",
    header: "In header"
  },
  enableAutoScroll: {
    name: "Auto-scroll during streaming",
    desc: "Automatically scroll to the bottom as Claude streams responses. Disable to stay at the top and read from the beginning."
  },
  openInMainTab: {
    name: "Open in main editor area",
    desc: "Open chat panel as a main tab in the center editor area instead of the right sidebar"
  },
  cliPath: {
    name: "Claude CLI path",
    desc: "Custom path to Claude Code CLI. Leave empty for auto-detection.",
    descWindows: "For the native installer, use claude.exe. For npm/pnpm/yarn or other package manager installs, use the cli.js path (not claude.cmd).",
    descUnix: 'Paste the output of "which claude" \u2014 works for both native and npm/pnpm/yarn installs.',
    validation: {
      notExist: "Path does not exist",
      isDirectory: "Path is a directory, not a file"
    }
  },
  language: {
    name: "Language",
    desc: "Change the display language of the plugin interface"
  }
};
var en_default = {
  common: common2,
  chat: chat2,
  settings: settings2
};

// src/i18n/locales/es.json
var es_exports = {};
__export(es_exports, {
  chat: () => chat3,
  common: () => common3,
  default: () => es_default,
  settings: () => settings3
});
var common3 = {
  save: "Guardar",
  cancel: "Cancelar",
  delete: "Eliminar",
  edit: "Editar",
  add: "Agregar",
  remove: "Eliminar",
  clear: "Limpiar",
  clearAll: "Limpiar todo",
  loading: "Cargando",
  error: "Error",
  success: "\xC9xito",
  warning: "Advertencia",
  confirm: "Confirmar",
  settings: "Configuraci\xF3n",
  advanced: "Avanzado",
  enabled: "Habilitado",
  disabled: "Deshabilitado",
  platform: "Plataforma",
  refresh: "Actualizar",
  rewind: "Rebobinar"
};
var chat3 = {
  rewind: {
    confirmMessage: "\xBFRebobinar a este punto? Los cambios de archivos despu\xE9s de este mensaje ser\xE1n revertidos. El rebobinado no afecta archivos editados manualmente o mediante bash.",
    confirmButton: "Rebobinar",
    ariaLabel: "Rebobinar hasta aqu\xED",
    notice: "Rebobinado: {count} archivo(s) revertido(s)",
    noticeSaveFailed: "Rebobinado: {count} archivo(s) revertido(s), pero no se pudo guardar el estado: {error}",
    failed: "Error al rebobinar: {error}",
    cannot: "No se puede rebobinar: {error}",
    unavailableStreaming: "No se puede rebobinar durante la transmisi\xF3n",
    unavailableNoUuid: "No se puede rebobinar: faltan identificadores de mensaje"
  },
  fork: {
    ariaLabel: "Bifurcar conversaci\xF3n",
    chooseTarget: "Bifurcar conversaci\xF3n",
    targetNewTab: "Nueva pesta\xF1a",
    targetCurrentTab: "Pesta\xF1a actual",
    maxTabsReached: "No se puede bifurcar: m\xE1ximo de {count} pesta\xF1as alcanzado",
    notice: "Bifurcado a nueva pesta\xF1a",
    noticeCurrentTab: "Bifurcado en pesta\xF1a actual",
    failed: "Error al bifurcar: {error}",
    unavailableStreaming: "No se puede bifurcar durante la transmisi\xF3n",
    unavailableNoUuid: "No se puede bifurcar: faltan identificadores de mensaje",
    unavailableNoResponse: "No se puede bifurcar: no hay respuesta para bifurcar",
    errorMessageNotFound: "Mensaje no encontrado",
    errorNoSession: "No hay ning\xFAn ID de sesi\xF3n disponible",
    errorNoActiveTab: "No hay ninguna pesta\xF1a activa",
    commandNoMessages: "No se puede bifurcar: no hay mensajes en la conversaci\xF3n",
    commandNoAssistantUuid: "No se puede bifurcar: no hay respuesta del asistente con identificadores"
  },
  bangBash: {
    placeholder: "> Ejecuta un comando bash...",
    commandPanel: "Panel de comandos",
    copyAriaLabel: "Copiar la salida del comando m\xE1s reciente",
    clearAriaLabel: "Limpiar la salida de bash",
    commandLabel: "{command}",
    statusLabel: "Estado: {status}",
    collapseOutput: "Contraer la salida del comando",
    expandOutput: "Expandir la salida del comando",
    running: "Ejecutando...",
    copyFailed: "No se pudo copiar al portapapeles"
  }
};
var settings3 = {
  title: "Configuraci\xF3n de Claudian",
  tabs: {
    general: "General",
    claude: "Claude",
    codex: "Codex"
  },
  display: "Pantalla",
  conversations: "Conversaciones",
  content: "Contenido",
  input: "Entrada",
  setup: "Configuraci\xF3n",
  models: "Modelos",
  experimental: "Experimental",
  userName: {
    name: "\xBFC\xF3mo deber\xEDa Claudian llamarte?",
    desc: "Tu nombre para saludos personalizados (dejar vac\xEDo para saludos gen\xE9ricos)"
  },
  excludedTags: {
    name: "Etiquetas excluidas",
    desc: "Las notas con estas etiquetas no se cargar\xE1n autom\xE1ticamente como contexto (una por l\xEDnea, sin #)"
  },
  mediaFolder: {
    name: "Carpeta de medios",
    desc: "Carpeta que contiene archivos adjuntos/imagenes. Cuando las notas usan ![[image.jpg]], Claude buscar\xE1 aqu\xED. Dejar vac\xEDo para la ra\xEDz del dep\xF3sito."
  },
  systemPrompt: {
    name: "Prompt de sistema personalizado",
    desc: "Instrucciones adicionales a\xF1adidas al prompt de sistema por defecto"
  },
  autoTitle: {
    name: "Generar autom\xE1ticamente t\xEDtulos de conversaci\xF3n",
    desc: "Genera autom\xE1ticamente t\xEDtulos de conversaci\xF3n despu\xE9s del primer mensaje del usuario."
  },
  titleModel: {
    name: "Modelo de generaci\xF3n de t\xEDtulos",
    desc: "Modelo utilizado para generar autom\xE1ticamente t\xEDtulos de conversaci\xF3n.",
    auto: "Autom\xE1tico (Haiku)"
  },
  navMappings: {
    name: "Mapeos de navegaci\xF3n estilo Vim",
    desc: 'Un mapeo por l\xEDnea. Formato: "map <tecla> <acci\xF3n>" (acciones: scrollUp, scrollDown, focusInput).'
  },
  hotkeys: "Atajos de teclado",
  inlineEditHotkey: {
    name: "Edici\xF3n en l\xEDnea",
    descWithKey: "Atajo actual: {hotkey}",
    descNoKey: "Sin atajo configurado",
    btnChange: "Cambiar",
    btnSet: "Configurar"
  },
  openChatHotkey: {
    name: "Abrir chat",
    descWithKey: "Atajo actual: {hotkey}",
    descNoKey: "Sin atajo configurado",
    btnChange: "Cambiar",
    btnSet: "Configurar"
  },
  newSessionHotkey: {
    name: "Nueva sesi\xF3n",
    descWithKey: "Atajo actual: {hotkey}",
    descNoKey: "Sin atajo configurado",
    btnChange: "Cambiar",
    btnSet: "Configurar"
  },
  newTabHotkey: {
    name: "Nueva pesta\xF1a",
    descWithKey: "Atajo actual: {hotkey}",
    descNoKey: "Sin atajo configurado",
    btnChange: "Cambiar",
    btnSet: "Configurar"
  },
  closeTabHotkey: {
    name: "Cerrar pesta\xF1a",
    descWithKey: "Atajo actual: {hotkey}",
    descNoKey: "Sin atajo configurado",
    btnChange: "Cambiar",
    btnSet: "Configurar"
  },
  slashCommands: {
    name: "Comandos y habilidades",
    desc: "Administra comandos y habilidades a nivel de vault almacenados en .claude/commands/ y .claude/skills/. Activados por /nombre."
  },
  hiddenSlashCommands: {
    name: "Comandos y habilidades ocultos",
    desc: "Oculta comandos y habilidades espec\xEDficos del men\xFA desplegable. \xDAtil para ocultar entradas de Claude Code que no son relevantes para Claudian. Ingresa los nombres sin la barra inicial, uno por l\xEDnea.",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "Servidores MCP",
    desc: "Administra configuraciones de servidores MCP a nivel de vault almacenadas en .claude/mcp.json. Los servidores con modo de guardado de contexto requieren @mention para activarse."
  },
  plugins: {
    name: "Plugins de Claude Code",
    desc: "Administra plugins de Claude Code descubiertos desde ~/.claude/plugins. Los plugins habilitados se almacenan por vault en .claude/settings.json."
  },
  subagents: {
    name: "Subagentes",
    desc: "Administra subagentes a nivel de vault almacenados en .claude/agents/. Cada archivo Markdown define un agente personalizado.",
    noAgents: "No hay subagentes configurados. Haz clic en + para crear uno.",
    deleteConfirm: '\xBFEliminar el subagente "{name}"?',
    saveFailed: "No se pudo guardar el subagente: {message}",
    refreshFailed: "No se pudieron actualizar los subagentes: {message}",
    deleteFailed: "No se pudo eliminar el subagente: {message}",
    renameCleanupFailed: 'Advertencia: no se pudo eliminar el archivo anterior de "{name}"',
    created: 'Se cre\xF3 el subagente "{name}"',
    updated: 'Se actualiz\xF3 el subagente "{name}"',
    deleted: 'Se elimin\xF3 el subagente "{name}"',
    duplicateName: 'Ya existe un agente con el nombre "{name}"',
    descriptionRequired: "La descripci\xF3n es obligatoria",
    promptRequired: "El prompt del sistema es obligatorio",
    modal: {
      titleEdit: "Editar subagente",
      titleAdd: "Agregar subagente",
      name: "Nombre",
      nameDesc: "Solo letras min\xFAsculas, n\xFAmeros y guiones",
      namePlaceholder: "code-reviewer",
      description: "Descripci\xF3n",
      descriptionDesc: "Descripci\xF3n breve de este agente",
      descriptionPlaceholder: "Revisa c\xF3digo en busca de errores y estilo",
      advancedOptions: "Opciones avanzadas",
      model: "Modelo",
      modelDesc: "Modelo alternativo para este agente",
      tools: "Herramientas",
      toolsDesc: "Lista separada por comas de las herramientas permitidas (vac\xEDo = todas)",
      disallowedTools: "Herramientas no permitidas",
      disallowedToolsDesc: "Lista separada por comas de herramientas no permitidas",
      skills: "Habilidades",
      skillsDesc: "Lista separada por comas de habilidades",
      prompt: "Prompt del sistema",
      promptDesc: "Instrucciones para el agente",
      promptPlaceholder: "Eres un revisor de c\xF3digo. Analiza el c\xF3digo proporcionado para..."
    }
  },
  safety: "Seguridad",
  loadUserSettings: {
    name: "Cargar configuraci\xF3n de usuario Claude",
    desc: "Carga ~/.claude/settings.json. Cuando est\xE1 habilitado, las reglas de permisos del usuario pueden eludir el modo seguro."
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "Entorno",
  customVariables: {
    name: "Variables personalizadas",
    desc: "Variables de entorno para Claude SDK (formato KEY=VALUE, una por l\xEDnea). Prefijo export soportado."
  },
  envSnippets: {
    name: "Fragmentos",
    addBtn: "A\xF1adir fragmento",
    noSnippets: "No hay fragmentos de entorno guardados. Haga clic en + para guardar su configuraci\xF3n actual.",
    nameRequired: "Por favor ingrese un nombre para el fragmento",
    modal: {
      titleEdit: "Editar fragmento",
      titleSave: "Guardar fragmento",
      name: "Nombre",
      namePlaceholder: "Un nombre descriptivo para esta configuraci\xF3n",
      description: "Descripci\xF3n",
      descPlaceholder: "Descripci\xF3n opcional",
      envVars: "Variables de entorno",
      envVarsPlaceholder: "Formato KEY=VALUE, una por l\xEDnea (prefijo export soportado)",
      save: "Guardar",
      update: "Actualizar",
      cancel: "Cancelar"
    }
  },
  customContextLimits: {
    name: "L\xEDmites de contexto personalizados",
    desc: "Establezca tama\xF1os de ventana de contexto para sus modelos personalizados. Deje vac\xEDo para usar el valor predeterminado (200k tokens).",
    invalid: "Formato inv\xE1lido. Use: 256k, 1m o n\xFAmero exacto (1000-10000000)."
  },
  enableOpus1M: {
    name: "Ventana de contexto Opus 1M",
    desc: "Mostrar Opus 1M en el selector de modelos. Incluido en planes Max, Team y Enterprise. Usuarios de API y Pro necesitan uso adicional."
  },
  enableSonnet1M: {
    name: "Ventana de contexto Sonnet 1M",
    desc: "Mostrar Sonnet 1M en el selector de modelos. Requiere uso adicional en planes Max, Team y Enterprise. Usuarios de API y Pro necesitan uso adicional."
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "Habilitar extensi\xF3n de Chrome",
    desc: "Permitir que Claude interact\xFAe con Chrome a trav\xE9s de la extensi\xF3n claude-in-chrome. Requiere que la extensi\xF3n est\xE9 instalada. Requiere reinicio de sesi\xF3n."
  },
  enableBangBash: {
    name: "Habilitar modo bash (!)",
    desc: "Escribe ! en una entrada vac\xEDa para entrar en modo bash. Ejecuta comandos directamente mediante Node.js child_process. Requiere volver a abrir la vista.",
    validation: {
      noNode: "Node.js no se encontr\xF3 en PATH. Instala Node.js o revisa tu configuraci\xF3n de PATH."
    }
  },
  maxTabs: {
    name: "M\xE1ximo de pesta\xF1as de chat",
    desc: "N\xFAmero m\xE1ximo de pesta\xF1as de chat simult\xE1neas (3-10). Cada pesta\xF1a usa una sesi\xF3n de Claude separada.",
    warning: "M\xE1s de 5 pesta\xF1as puede afectar el rendimiento y el uso de memoria."
  },
  tabBarPosition: {
    name: "Posici\xF3n de la barra de pesta\xF1as",
    desc: "Elige d\xF3nde mostrar las insignias de pesta\xF1as y los botones de acci\xF3n",
    input: "Sobre el \xE1rea de entrada (predeterminado)",
    header: "En el encabezado"
  },
  enableAutoScroll: {
    name: "Desplazamiento autom\xE1tico durante streaming",
    desc: "Desplazarse autom\xE1ticamente hacia abajo mientras Claude transmite respuestas. Desactivar para quedarse arriba y leer desde el principio."
  },
  openInMainTab: {
    name: "Abrir en \xE1rea de editor principal",
    desc: "Abrir el panel de chat como una pesta\xF1a principal en el \xE1rea de editor central en lugar de la barra lateral derecha"
  },
  cliPath: {
    name: "Ruta CLI Claude",
    desc: "Ruta personalizada a Claude Code CLI. Dejar vac\xEDo para detecci\xF3n autom\xE1tica.",
    descWindows: "Para el instalador nativo, use claude.exe. Para instalaciones con npm/pnpm/yarn u otros gestores de paquetes, use la ruta cli.js (no claude.cmd).",
    descUnix: 'Pegue la salida de "which claude" \u2014 funciona tanto para instalaciones nativas como npm/pnpm/yarn.',
    validation: {
      notExist: "La ruta no existe",
      isDirectory: "La ruta es un directorio, no un archivo"
    }
  },
  language: {
    name: "Idioma",
    desc: "Cambiar el idioma de visualizaci\xF3n de la interfaz del plugin"
  }
};
var es_default = {
  common: common3,
  chat: chat3,
  settings: settings3
};

// src/i18n/locales/fr.json
var fr_exports = {};
__export(fr_exports, {
  chat: () => chat4,
  common: () => common4,
  default: () => fr_default,
  settings: () => settings4
});
var common4 = {
  save: "Enregistrer",
  cancel: "Annuler",
  delete: "Supprimer",
  edit: "Modifier",
  add: "Ajouter",
  remove: "Supprimer",
  clear: "Effacer",
  clearAll: "Tout effacer",
  loading: "Chargement",
  error: "Erreur",
  success: "Succ\xE8s",
  warning: "Avertissement",
  confirm: "Confirmer",
  settings: "Param\xE8tres",
  advanced: "Avanc\xE9",
  enabled: "Activ\xE9",
  disabled: "D\xE9sactiv\xE9",
  platform: "Plateforme",
  refresh: "Actualiser",
  rewind: "Rembobiner"
};
var chat4 = {
  rewind: {
    confirmMessage: "Rembobiner jusqu'\xE0 ce point ? Les modifications de fichiers apr\xE8s ce message seront annul\xE9es. Le rembobinage n'affecte pas les fichiers modifi\xE9s manuellement ou via bash.",
    confirmButton: "Rembobiner",
    ariaLabel: "Rembobiner jusqu'ici",
    notice: "Rembobin\xE9 : {count} fichier(s) restaur\xE9(s)",
    noticeSaveFailed: "Rembobin\xE9 : {count} fichier(s) restaur\xE9(s), mais impossible d'enregistrer l'\xE9tat : {error}",
    failed: "\xC9chec du rembobinage : {error}",
    cannot: "Impossible de rembobiner : {error}",
    unavailableStreaming: "Impossible de rembobiner pendant le streaming",
    unavailableNoUuid: "Impossible de rembobiner : identifiants de message manquants"
  },
  fork: {
    ariaLabel: "Bifurquer la conversation",
    chooseTarget: "Bifurquer la conversation",
    targetNewTab: "Nouvel onglet",
    targetCurrentTab: "Onglet actuel",
    maxTabsReached: "Impossible de bifurquer : maximum de {count} onglets atteint",
    notice: "Bifurqu\xE9 dans un nouvel onglet",
    noticeCurrentTab: "Bifurqu\xE9 dans l'onglet actuel",
    failed: "\xC9chec de la bifurcation : {error}",
    unavailableStreaming: "Impossible de bifurquer pendant le streaming",
    unavailableNoUuid: "Impossible de bifurquer : identifiants de message manquants",
    unavailableNoResponse: "Impossible de bifurquer : aucune r\xE9ponse pour bifurquer",
    errorMessageNotFound: "Message introuvable",
    errorNoSession: "Aucun ID de session disponible",
    errorNoActiveTab: "Aucun onglet actif",
    commandNoMessages: "Impossible de bifurquer : aucun message dans la conversation",
    commandNoAssistantUuid: "Impossible de bifurquer : aucune r\xE9ponse de l\u2019assistant avec des identifiants"
  },
  bangBash: {
    placeholder: "> Ex\xE9cuter une commande bash...",
    commandPanel: "Panneau de commandes",
    copyAriaLabel: "Copier la sortie de la derni\xE8re commande",
    clearAriaLabel: "Effacer la sortie bash",
    commandLabel: "{command}",
    statusLabel: "Statut : {status}",
    collapseOutput: "R\xE9duire la sortie de la commande",
    expandOutput: "D\xE9velopper la sortie de la commande",
    running: "Ex\xE9cution...",
    copyFailed: "\xC9chec de la copie dans le presse-papiers"
  }
};
var settings4 = {
  title: "Param\xE8tres Claudian",
  tabs: {
    general: "G\xE9n\xE9ral",
    claude: "Claude",
    codex: "Codex"
  },
  display: "Affichage",
  conversations: "Conversations",
  content: "Contenu",
  input: "Saisie",
  setup: "Configuration",
  models: "Mod\xE8les",
  experimental: "Exp\xE9rimental",
  userName: {
    name: "Comment Claudian doit-il vous appeler ?",
    desc: "Votre nom pour les salutations personnalis\xE9es (laisser vide pour les salutations g\xE9n\xE9riques)"
  },
  excludedTags: {
    name: "Tags exclus",
    desc: "Les notes avec ces tags ne seront pas charg\xE9es automatiquement comme contexte (un par ligne, sans #)"
  },
  mediaFolder: {
    name: "Dossier des m\xE9dias",
    desc: "Dossier contenant les pi\xE8ces jointes/images. Lorsque les notes utilisent ![[image.jpg]], Claude cherchera ici. Laisser vide pour la racine du coffre."
  },
  systemPrompt: {
    name: "Prompt syst\xE8me personnalis\xE9",
    desc: "Instructions suppl\xE9mentaires ajout\xE9es au prompt syst\xE8me par d\xE9faut"
  },
  autoTitle: {
    name: "G\xE9n\xE9rer automatiquement les titres de conversation",
    desc: "G\xE9n\xE8re automatiquement les titres de conversation apr\xE8s le premier message de l'utilisateur."
  },
  titleModel: {
    name: "Mod\xE8le de g\xE9n\xE9ration de titre",
    desc: "Mod\xE8le utilis\xE9 pour g\xE9n\xE9rer automatiquement les titres de conversation.",
    auto: "Automatique (Haiku)"
  },
  navMappings: {
    name: "Mappages de navigation style Vim",
    desc: 'Un mappage par ligne. Format : "map <touche> <action>" (actions : scrollUp, scrollDown, focusInput).'
  },
  hotkeys: "Raccourcis clavier",
  inlineEditHotkey: {
    name: "\xC9dition en ligne",
    descWithKey: "Raccourci actuel : {hotkey}",
    descNoKey: "Aucun raccourci d\xE9fini",
    btnChange: "Modifier",
    btnSet: "D\xE9finir"
  },
  openChatHotkey: {
    name: "Ouvrir le chat",
    descWithKey: "Raccourci actuel : {hotkey}",
    descNoKey: "Aucun raccourci d\xE9fini",
    btnChange: "Modifier",
    btnSet: "D\xE9finir"
  },
  newSessionHotkey: {
    name: "Nouvelle session",
    descWithKey: "Raccourci actuel : {hotkey}",
    descNoKey: "Aucun raccourci d\xE9fini",
    btnChange: "Modifier",
    btnSet: "D\xE9finir"
  },
  newTabHotkey: {
    name: "Nouvel onglet",
    descWithKey: "Raccourci actuel : {hotkey}",
    descNoKey: "Aucun raccourci d\xE9fini",
    btnChange: "Modifier",
    btnSet: "D\xE9finir"
  },
  closeTabHotkey: {
    name: "Fermer l'onglet",
    descWithKey: "Raccourci actuel : {hotkey}",
    descNoKey: "Aucun raccourci d\xE9fini",
    btnChange: "Modifier",
    btnSet: "D\xE9finir"
  },
  slashCommands: {
    name: "Commandes et comp\xE9tences",
    desc: "G\xE9rez les commandes et comp\xE9tences au niveau du vault stock\xE9es dans .claude/commands/ et .claude/skills/. D\xE9clench\xE9es par /nom."
  },
  hiddenSlashCommands: {
    name: "Commandes et comp\xE9tences masqu\xE9es",
    desc: "Masquez des commandes et comp\xE9tences sp\xE9cifiques du menu d\xE9roulant. Utile pour masquer les entr\xE9es Claude Code qui ne sont pas pertinentes pour Claudian. Saisissez les noms sans le slash initial, un par ligne.",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "Serveurs MCP",
    desc: "G\xE9rez les configurations de serveurs MCP au niveau du vault stock\xE9es dans .claude/mcp.json. Les serveurs avec mode de sauvegarde de contexte n\xE9cessitent une @mention pour s'activer."
  },
  plugins: {
    name: "Plugins Claude Code",
    desc: "G\xE9rez les plugins Claude Code d\xE9couverts dans ~/.claude/plugins. Les plugins activ\xE9s sont stock\xE9s par vault dans .claude/settings.json."
  },
  subagents: {
    name: "Sous-agents",
    desc: "G\xE9rez les sous-agents au niveau du vault stock\xE9s dans .claude/agents/. Chaque fichier Markdown d\xE9finit un agent personnalis\xE9.",
    noAgents: "Aucun sous-agent configur\xE9. Cliquez sur + pour en cr\xE9er un.",
    deleteConfirm: 'Supprimer le sous-agent "{name}" ?',
    saveFailed: "\xC9chec de l\u2019enregistrement du sous-agent : {message}",
    refreshFailed: "\xC9chec de l\u2019actualisation des subagents : {message}",
    deleteFailed: "\xC9chec de la suppression du sous-agent : {message}",
    renameCleanupFailed: 'Avertissement : impossible de supprimer l\u2019ancien fichier pour "{name}"',
    created: 'Sous-agent "{name}" cr\xE9\xE9',
    updated: 'Sous-agent "{name}" mis \xE0 jour',
    deleted: 'Sous-agent "{name}" supprim\xE9',
    duplicateName: 'Un agent nomm\xE9 "{name}" existe d\xE9j\xE0',
    descriptionRequired: "La description est obligatoire",
    promptRequired: "Le prompt syst\xE8me est obligatoire",
    modal: {
      titleEdit: "Modifier le sous-agent",
      titleAdd: "Ajouter un sous-agent",
      name: "Nom",
      nameDesc: "Lettres minuscules, chiffres et tirets uniquement",
      namePlaceholder: "code-reviewer",
      description: "Description",
      descriptionDesc: "Br\xE8ve description de cet agent",
      descriptionPlaceholder: "Examine le code pour d\xE9tecter les bugs et les probl\xE8mes de style",
      advancedOptions: "Options avanc\xE9es",
      model: "Mod\xE8le",
      modelDesc: "Mod\xE8le \xE0 utiliser pour cet agent",
      tools: "Outils",
      toolsDesc: "Liste des outils autoris\xE9s, s\xE9par\xE9s par des virgules (vide = tous)",
      disallowedTools: "Outils non autoris\xE9s",
      disallowedToolsDesc: "Liste des outils \xE0 interdire, s\xE9par\xE9s par des virgules",
      skills: "Comp\xE9tences",
      skillsDesc: "Liste des comp\xE9tences, s\xE9par\xE9es par des virgules",
      prompt: "Prompt syst\xE8me",
      promptDesc: "Instructions pour l\u2019agent",
      promptPlaceholder: "Vous \xEAtes un relecteur de code. Analysez le code fourni pour..."
    }
  },
  safety: "S\xE9curit\xE9",
  loadUserSettings: {
    name: "Charger les param\xE8tres utilisateur Claude",
    desc: "Charge ~/.claude/settings.json. Lorsqu'activ\xE9, les r\xE8gles de permission de l'utilisateur peuvent contourner le mode s\xE9curis\xE9."
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "Environnement",
  customVariables: {
    name: "Variables personnalis\xE9es",
    desc: "Variables d'environnement pour Claude SDK (format KEY=VALUE, une par ligne). Pr\xE9fixe export support\xE9."
  },
  envSnippets: {
    name: "Extraits",
    addBtn: "Ajouter un extrait",
    noSnippets: "Aucun extrait d'environnement enregistr\xE9. Cliquez sur + pour sauvegarder votre configuration actuelle.",
    nameRequired: "Veuillez entrer un nom pour l'extrait",
    modal: {
      titleEdit: "Modifier l'extrait",
      titleSave: "Sauvegarder l'extrait",
      name: "Nom",
      namePlaceholder: "Un nom descriptif pour cette configuration",
      description: "Description",
      descPlaceholder: "Description optionnelle",
      envVars: "Variables d'environnement",
      envVarsPlaceholder: "Format KEY=VALUE, une par ligne (pr\xE9fixe export support\xE9)",
      save: "Enregistrer",
      update: "Mettre \xE0 jour",
      cancel: "Annuler"
    }
  },
  customContextLimits: {
    name: "Limites de contexte personnalis\xE9es",
    desc: "D\xE9finissez les tailles de fen\xEAtre de contexte pour vos mod\xE8les personnalis\xE9s. Laissez vide pour utiliser la valeur par d\xE9faut (200k tokens).",
    invalid: "Format invalide. Utilisez : 256k, 1m ou nombre exact (1000-10000000)."
  },
  enableOpus1M: {
    name: "Fen\xEAtre de contexte Opus 1M",
    desc: "Afficher Opus 1M dans le s\xE9lecteur de mod\xE8le. Inclus avec les plans Max, Team et Enterprise. Les utilisateurs API et Pro n\xE9cessitent une utilisation suppl\xE9mentaire."
  },
  enableSonnet1M: {
    name: "Fen\xEAtre de contexte Sonnet 1M",
    desc: "Afficher Sonnet 1M dans le s\xE9lecteur de mod\xE8le. N\xE9cessite une utilisation suppl\xE9mentaire sur les plans Max, Team et Enterprise. Les utilisateurs API et Pro n\xE9cessitent une utilisation suppl\xE9mentaire."
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "Activer l'extension Chrome",
    desc: "Permettre \xE0 Claude d'interagir avec Chrome via l'extension claude-in-chrome. L'extension doit \xEAtre install\xE9e. N\xE9cessite un red\xE9marrage de session."
  },
  enableBangBash: {
    name: "Activer le mode bash (!)",
    desc: "Saisissez ! dans un champ vide pour passer en mode bash. Ex\xE9cute les commandes directement via le child_process de Node.js. N\xE9cessite de rouvrir la vue.",
    validation: {
      noNode: "Node.js introuvable dans PATH. Installez Node.js ou v\xE9rifiez votre configuration PATH."
    }
  },
  maxTabs: {
    name: "Maximum d'onglets de chat",
    desc: "Nombre maximum d'onglets de chat simultan\xE9s (3-10). Chaque onglet utilise une session Claude s\xE9par\xE9e.",
    warning: "Plus de 5 onglets peut affecter les performances et l'utilisation de la m\xE9moire."
  },
  tabBarPosition: {
    name: "Position de la barre d'onglets",
    desc: "Choisissez o\xF9 afficher les badges d'onglets et les boutons d'action",
    input: "Au-dessus de la saisie (par d\xE9faut)",
    header: "Dans l'en-t\xEAte"
  },
  enableAutoScroll: {
    name: "D\xE9filement automatique pendant le streaming",
    desc: "D\xE9filer automatiquement vers le bas pendant que Claude diffuse les r\xE9ponses. D\xE9sactiver pour rester en haut et lire depuis le d\xE9but."
  },
  openInMainTab: {
    name: "Ouvrir dans la zone d'\xE9diteur principale",
    desc: "Ouvrir le panneau de chat comme un onglet principal dans la zone d'\xE9diteur centrale au lieu de la barre lat\xE9rale droite"
  },
  cliPath: {
    name: "Chemin CLI Claude",
    desc: "Chemin personnalis\xE9 vers Claude Code CLI. Laisser vide pour la d\xE9tection automatique.",
    descWindows: "Pour l'installateur natif, utilisez claude.exe. Pour les installations npm/pnpm/yarn ou autres gestionnaires de paquets, utilisez le chemin cli.js (pas claude.cmd).",
    descUnix: 'Collez la sortie de "which claude" \u2014 fonctionne pour les installations natives et npm/pnpm/yarn.',
    validation: {
      notExist: "Le chemin n'existe pas",
      isDirectory: "Le chemin est un r\xE9pertoire, pas un fichier"
    }
  },
  language: {
    name: "Langue",
    desc: "Changer la langue d'affichage de l'interface du plugin"
  }
};
var fr_default = {
  common: common4,
  chat: chat4,
  settings: settings4
};

// src/i18n/locales/ja.json
var ja_exports = {};
__export(ja_exports, {
  chat: () => chat5,
  common: () => common5,
  default: () => ja_default,
  settings: () => settings5
});
var common5 = {
  save: "\u4FDD\u5B58",
  cancel: "\u30AD\u30E3\u30F3\u30BB\u30EB",
  delete: "\u524A\u9664",
  edit: "\u7DE8\u96C6",
  add: "\u8FFD\u52A0",
  remove: "\u524A\u9664",
  clear: "\u30AF\u30EA\u30A2",
  clearAll: "\u3059\u3079\u3066\u30AF\u30EA\u30A2",
  loading: "\u8AAD\u307F\u8FBC\u307F\u4E2D",
  error: "\u30A8\u30E9\u30FC",
  success: "\u6210\u529F",
  warning: "\u8B66\u544A",
  confirm: "\u78BA\u8A8D",
  settings: "\u8A2D\u5B9A",
  advanced: "\u8A73\u7D30",
  enabled: "\u6709\u52B9",
  disabled: "\u7121\u52B9",
  platform: "\u30D7\u30E9\u30C3\u30C8\u30D5\u30A9\u30FC\u30E0",
  refresh: "\u66F4\u65B0",
  rewind: "\u5DFB\u304D\u623B\u3057"
};
var chat5 = {
  rewind: {
    confirmMessage: "\u3053\u306E\u6642\u70B9\u306B\u5DFB\u304D\u623B\u3057\u307E\u3059\u304B\uFF1F\u3053\u306E\u30E1\u30C3\u30BB\u30FC\u30B8\u4EE5\u964D\u306E\u30D5\u30A1\u30A4\u30EB\u5909\u66F4\u304C\u5143\u306B\u623B\u3055\u308C\u307E\u3059\u3002\u624B\u52D5\u307E\u305F\u306Fbash\u3067\u7DE8\u96C6\u3055\u308C\u305F\u30D5\u30A1\u30A4\u30EB\u306B\u306F\u5F71\u97FF\u3057\u307E\u305B\u3093\u3002",
    confirmButton: "\u5DFB\u304D\u623B\u3059",
    ariaLabel: "\u3053\u3053\u306B\u5DFB\u304D\u623B\u3059",
    notice: "\u5DFB\u304D\u623B\u3057\u5B8C\u4E86\uFF1A{count} \u500B\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u5FA9\u5143",
    noticeSaveFailed: "\u5DFB\u304D\u623B\u3057\u5B8C\u4E86\uFF1A{count} \u500B\u306E\u30D5\u30A1\u30A4\u30EB\u3092\u5FA9\u5143\u3057\u307E\u3057\u305F\u304C\u3001\u72B6\u614B\u3092\u4FDD\u5B58\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F\uFF1A{error}",
    failed: "\u5DFB\u304D\u623B\u3057\u306B\u5931\u6557\uFF1A{error}",
    cannot: "\u5DFB\u304D\u623B\u3057\u3067\u304D\u307E\u305B\u3093\uFF1A{error}",
    unavailableStreaming: "\u30B9\u30C8\u30EA\u30FC\u30DF\u30F3\u30B0\u4E2D\u306F\u5DFB\u304D\u623B\u3057\u3067\u304D\u307E\u305B\u3093",
    unavailableNoUuid: "\u5DFB\u304D\u623B\u3057\u3067\u304D\u307E\u305B\u3093\uFF1A\u30E1\u30C3\u30BB\u30FC\u30B8\u8B58\u5225\u5B50\u304C\u3042\u308A\u307E\u305B\u3093"
  },
  fork: {
    ariaLabel: "\u4F1A\u8A71\u3092\u5206\u5C90",
    chooseTarget: "\u4F1A\u8A71\u3092\u5206\u5C90",
    targetNewTab: "\u65B0\u3057\u3044\u30BF\u30D6",
    targetCurrentTab: "\u73FE\u5728\u306E\u30BF\u30D6",
    maxTabsReached: "\u5206\u5C90\u3067\u304D\u307E\u305B\u3093\uFF1A\u6700\u5927 {count} \u30BF\u30D6\u306B\u9054\u3057\u307E\u3057\u305F",
    notice: "\u65B0\u3057\u3044\u30BF\u30D6\u306B\u5206\u5C90\u3057\u307E\u3057\u305F",
    noticeCurrentTab: "\u73FE\u5728\u306E\u30BF\u30D6\u3067\u5206\u5C90\u3057\u307E\u3057\u305F",
    failed: "\u5206\u5C90\u306B\u5931\u6557\uFF1A{error}",
    unavailableStreaming: "\u30B9\u30C8\u30EA\u30FC\u30DF\u30F3\u30B0\u4E2D\u306F\u5206\u5C90\u3067\u304D\u307E\u305B\u3093",
    unavailableNoUuid: "\u5206\u5C90\u3067\u304D\u307E\u305B\u3093\uFF1A\u30E1\u30C3\u30BB\u30FC\u30B8\u8B58\u5225\u5B50\u304C\u3042\u308A\u307E\u305B\u3093",
    unavailableNoResponse: "\u5206\u5C90\u3067\u304D\u307E\u305B\u3093\uFF1A\u5206\u5C90\u5143\u306E\u5FDC\u7B54\u304C\u3042\u308A\u307E\u305B\u3093",
    errorMessageNotFound: "\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093",
    errorNoSession: "\u30BB\u30C3\u30B7\u30E7\u30F3 ID \u304C\u3042\u308A\u307E\u305B\u3093",
    errorNoActiveTab: "\u30A2\u30AF\u30C6\u30A3\u30D6\u306A\u30BF\u30D6\u304C\u3042\u308A\u307E\u305B\u3093",
    commandNoMessages: "\u30D5\u30A9\u30FC\u30AF\u3067\u304D\u307E\u305B\u3093: \u4F1A\u8A71\u306B\u30E1\u30C3\u30BB\u30FC\u30B8\u304C\u3042\u308A\u307E\u305B\u3093",
    commandNoAssistantUuid: "\u30D5\u30A9\u30FC\u30AF\u3067\u304D\u307E\u305B\u3093: \u8B58\u5225\u5B50\u4ED8\u304D\u306E\u30A2\u30B7\u30B9\u30BF\u30F3\u30C8\u5FDC\u7B54\u304C\u3042\u308A\u307E\u305B\u3093"
  },
  bangBash: {
    placeholder: "> bash \u30B3\u30DE\u30F3\u30C9\u3092\u5B9F\u884C...",
    commandPanel: "\u30B3\u30DE\u30F3\u30C9\u30D1\u30CD\u30EB",
    copyAriaLabel: "\u6700\u65B0\u306E\u30B3\u30DE\u30F3\u30C9\u51FA\u529B\u3092\u30B3\u30D4\u30FC",
    clearAriaLabel: "bash \u51FA\u529B\u3092\u30AF\u30EA\u30A2",
    commandLabel: "{command}",
    statusLabel: "\u72B6\u614B: {status}",
    collapseOutput: "\u30B3\u30DE\u30F3\u30C9\u51FA\u529B\u3092\u6298\u308A\u305F\u305F\u3080",
    expandOutput: "\u30B3\u30DE\u30F3\u30C9\u51FA\u529B\u3092\u5C55\u958B",
    running: "\u5B9F\u884C\u4E2D...",
    copyFailed: "\u30AF\u30EA\u30C3\u30D7\u30DC\u30FC\u30C9\u3078\u306E\u30B3\u30D4\u30FC\u306B\u5931\u6557\u3057\u307E\u3057\u305F"
  }
};
var settings5 = {
  title: "Claudian \u8A2D\u5B9A",
  tabs: {
    general: "\u4E00\u822C",
    claude: "Claude",
    codex: "Codex"
  },
  display: "\u8868\u793A",
  conversations: "\u4F1A\u8A71",
  content: "\u30B3\u30F3\u30C6\u30F3\u30C4",
  input: "\u5165\u529B",
  setup: "\u30BB\u30C3\u30C8\u30A2\u30C3\u30D7",
  models: "\u30E2\u30C7\u30EB",
  experimental: "\u5B9F\u9A13\u7684\u6A5F\u80FD",
  userName: {
    name: "Claudian \u306F\u3069\u306E\u3088\u3046\u306B\u547C\u3073\u307E\u3059\u304B\uFF1F",
    desc: "\u30D1\u30FC\u30BD\u30CA\u30E9\u30A4\u30BA\u3055\u308C\u305F\u6328\u62F6\u306B\u4F7F\u7528\u3059\u308B\u540D\u524D\uFF08\u7A7A\u6B04\u3067\u4E00\u822C\u306E\u6328\u62F6\uFF09"
  },
  excludedTags: {
    name: "\u9664\u5916\u30BF\u30B0",
    desc: "\u3053\u308C\u3089\u306E\u30BF\u30B0\u3092\u542B\u3080\u30CE\u30FC\u30C8\u306F\u81EA\u52D5\u7684\u306B\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u3068\u3057\u3066\u8AAD\u307F\u8FBC\u307E\u308C\u307E\u305B\u3093\uFF081\u884C\u306B1\u3064\u3001#\u306A\u3057\uFF09"
  },
  mediaFolder: {
    name: "\u30E1\u30C7\u30A3\u30A2\u30D5\u30A9\u30EB\u30C0",
    desc: "\u6DFB\u4ED8\u30D5\u30A1\u30A4\u30EB/\u753B\u50CF\u3092\u683C\u7D0D\u3059\u308B\u30D5\u30A9\u30EB\u30C0\u3002\u30CE\u30FC\u30C8\u304C ![[image.jpg]] \u3092\u4F7F\u7528\u3059\u308B\u5834\u5408\u3001Claude \u306F\u3053\u3053\u3067\u63A2\u3057\u307E\u3059\u3002\u7A7A\u6B04\u3067\u30EA\u30DD\u30B8\u30C8\u30EA\u306E\u30EB\u30FC\u30C8\u3092\u4F7F\u7528\u3002"
  },
  systemPrompt: {
    name: "\u30AB\u30B9\u30BF\u30E0\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8",
    desc: "\u30C7\u30D5\u30A9\u30EB\u30C8\u306E\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8\u306B\u8FFD\u52A0\u3055\u308C\u308B\u8FFD\u52A0\u6307\u793A"
  },
  autoTitle: {
    name: "\u4F1A\u8A71\u30BF\u30A4\u30C8\u30EB\u3092\u81EA\u52D5\u751F\u6210",
    desc: "\u6700\u521D\u306E\u30E6\u30FC\u30B6\u30FC\u30E1\u30C3\u30BB\u30FC\u30B8\u9001\u4FE1\u5F8C\u306B\u4F1A\u8A71\u30BF\u30A4\u30C8\u30EB\u3092\u81EA\u52D5\u7684\u306B\u751F\u6210\u3057\u307E\u3059\u3002"
  },
  titleModel: {
    name: "\u30BF\u30A4\u30C8\u30EB\u751F\u6210\u30E2\u30C7\u30EB",
    desc: "\u4F1A\u8A71\u30BF\u30A4\u30C8\u30EB\u3092\u81EA\u52D5\u751F\u6210\u3059\u308B\u305F\u3081\u306B\u4F7F\u7528\u3055\u308C\u308B\u30E2\u30C7\u30EB\u3002",
    auto: "\u81EA\u52D5 (Haiku)"
  },
  navMappings: {
    name: "Vim\u30B9\u30BF\u30A4\u30EB\u30CA\u30D3\u30B2\u30FC\u30B7\u30E7\u30F3\u30DE\u30C3\u30D4\u30F3\u30B0",
    desc: '1\u884C\u306B1\u3064\u306E\u30DE\u30C3\u30D4\u30F3\u30B0\u3002\u5F62\u5F0F\uFF1A"map <\u30AD\u30FC> <\u30A2\u30AF\u30B7\u30E7\u30F3>"\uFF08\u30A2\u30AF\u30B7\u30E7\u30F3\uFF1AscrollUp, scrollDown, focusInput\uFF09\u3002'
  },
  hotkeys: "\u30DB\u30C3\u30C8\u30AD\u30FC",
  inlineEditHotkey: {
    name: "\u30A4\u30F3\u30E9\u30A4\u30F3\u7DE8\u96C6",
    descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}",
    descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A",
    btnChange: "\u5909\u66F4",
    btnSet: "\u8A2D\u5B9A"
  },
  openChatHotkey: {
    name: "\u30C1\u30E3\u30C3\u30C8\u3092\u958B\u304F",
    descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}",
    descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A",
    btnChange: "\u5909\u66F4",
    btnSet: "\u8A2D\u5B9A"
  },
  newSessionHotkey: {
    name: "\u65B0\u898F\u30BB\u30C3\u30B7\u30E7\u30F3",
    descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}",
    descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A",
    btnChange: "\u5909\u66F4",
    btnSet: "\u8A2D\u5B9A"
  },
  newTabHotkey: {
    name: "\u65B0\u898F\u30BF\u30D6",
    descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}",
    descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A",
    btnChange: "\u5909\u66F4",
    btnSet: "\u8A2D\u5B9A"
  },
  closeTabHotkey: {
    name: "\u30BF\u30D6\u3092\u9589\u3058\u308B",
    descWithKey: "\u73FE\u5728\u306E\u30DB\u30C3\u30C8\u30AD\u30FC: {hotkey}",
    descNoKey: "\u30DB\u30C3\u30C8\u30AD\u30FC\u672A\u8A2D\u5B9A",
    btnChange: "\u5909\u66F4",
    btnSet: "\u8A2D\u5B9A"
  },
  slashCommands: {
    name: "\u30B3\u30DE\u30F3\u30C9\u3068\u30B9\u30AD\u30EB",
    desc: ".claude/commands/ \u3068 .claude/skills/ \u306B\u4FDD\u5B58\u3055\u308C\u305F Vault \u30EC\u30D9\u30EB\u306E\u30B3\u30DE\u30F3\u30C9\u3068\u30B9\u30AD\u30EB\u3092\u7BA1\u7406\u3057\u307E\u3059\u3002/\u540D\u524D \u3067\u30C8\u30EA\u30AC\u30FC\u3055\u308C\u307E\u3059\u3002"
  },
  hiddenSlashCommands: {
    name: "\u975E\u8868\u793A\u306E\u30B3\u30DE\u30F3\u30C9\u3068\u30B9\u30AD\u30EB",
    desc: "\u30C9\u30ED\u30C3\u30D7\u30C0\u30A6\u30F3\u304B\u3089\u7279\u5B9A\u306E\u30B3\u30DE\u30F3\u30C9\u3068\u30B9\u30AD\u30EB\u3092\u975E\u8868\u793A\u306B\u3057\u307E\u3059\u3002Claudian \u306B\u95A2\u4FC2\u306E\u306A\u3044 Claude Code \u306E\u9805\u76EE\u3092\u96A0\u3059\u306E\u306B\u4FBF\u5229\u3067\u3059\u3002\u5148\u982D\u306E\u30B9\u30E9\u30C3\u30B7\u30E5\u306A\u3057\u3067\u540D\u524D\u30921\u884C\u306B1\u3064\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "MCP \u30B5\u30FC\u30D0\u30FC",
    desc: ".claude/mcp.json \u306B\u4FDD\u5B58\u3055\u308C\u305F Vault \u30EC\u30D9\u30EB\u306E MCP \u30B5\u30FC\u30D0\u30FC\u8A2D\u5B9A\u3092\u7BA1\u7406\u3057\u307E\u3059\u3002\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u4FDD\u5B58\u30E2\u30FC\u30C9\u306E\u30B5\u30FC\u30D0\u30FC\u306F @mention \u3067\u30A2\u30AF\u30C6\u30A3\u30D6\u306B\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002"
  },
  plugins: {
    name: "Claude Code \u30D7\u30E9\u30B0\u30A4\u30F3",
    desc: "~/.claude/plugins \u304B\u3089\u691C\u51FA\u3055\u308C\u305F Claude Code \u30D7\u30E9\u30B0\u30A4\u30F3\u3092\u7BA1\u7406\u3057\u307E\u3059\u3002\u6709\u52B9\u5316\u3055\u308C\u305F\u30D7\u30E9\u30B0\u30A4\u30F3\u306F Vault \u3054\u3068\u306B .claude/settings.json \u306B\u4FDD\u5B58\u3055\u308C\u307E\u3059\u3002"
  },
  subagents: {
    name: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8",
    desc: ".claude/agents/ \u306B\u4FDD\u5B58\u3055\u308C\u305F Vault \u30EC\u30D9\u30EB\u306E\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u7BA1\u7406\u3057\u307E\u3059\u3002\u5404 Markdown \u30D5\u30A1\u30A4\u30EB\u304C\u30AB\u30B9\u30BF\u30E0\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u30921\u3064\u5B9A\u7FA9\u3057\u307E\u3059\u3002",
    noAgents: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u304C\u8A2D\u5B9A\u3055\u308C\u3066\u3044\u307E\u305B\u3093\u3002+ \u3092\u30AF\u30EA\u30C3\u30AF\u3057\u3066\u4F5C\u6210\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
    deleteConfirm: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u300C{name}\u300D\u3092\u524A\u9664\u3057\u307E\u3059\u304B\uFF1F",
    saveFailed: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u4FDD\u5B58\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {message}",
    refreshFailed: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u66F4\u65B0\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F: {message}",
    deleteFailed: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u524A\u9664\u306B\u5931\u6557\u3057\u307E\u3057\u305F: {message}",
    renameCleanupFailed: "\u8B66\u544A: \u300C{name}\u300D\u306E\u53E4\u3044\u30D5\u30A1\u30A4\u30EB\u3092\u524A\u9664\u3067\u304D\u307E\u305B\u3093\u3067\u3057\u305F",
    created: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u300C{name}\u300D\u3092\u4F5C\u6210\u3057\u307E\u3057\u305F",
    updated: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u300C{name}\u300D\u3092\u66F4\u65B0\u3057\u307E\u3057\u305F",
    deleted: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u300C{name}\u300D\u3092\u524A\u9664\u3057\u307E\u3057\u305F",
    duplicateName: "\u300C{name}\u300D\u3068\u3044\u3046\u540D\u524D\u306E\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306F\u65E2\u306B\u5B58\u5728\u3057\u307E\u3059",
    descriptionRequired: "\u8AAC\u660E\u306F\u5FC5\u9808\u3067\u3059",
    promptRequired: "\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8\u306F\u5FC5\u9808\u3067\u3059",
    modal: {
      titleEdit: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u7DE8\u96C6",
      titleAdd: "\u30B5\u30D6\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3092\u8FFD\u52A0",
      name: "\u540D\u524D",
      nameDesc: "\u5C0F\u6587\u5B57\u3001\u6570\u5B57\u3001\u30CF\u30A4\u30D5\u30F3\u306E\u307F\u4F7F\u7528\u3067\u304D\u307E\u3059",
      namePlaceholder: "code-reviewer",
      description: "\u8AAC\u660E",
      descriptionDesc: "\u3053\u306E\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u7C21\u5358\u306A\u8AAC\u660E",
      descriptionPlaceholder: "\u30B3\u30FC\u30C9\u306E\u30D0\u30B0\u3084\u30B9\u30BF\u30A4\u30EB\u3092\u30EC\u30D3\u30E5\u30FC\u3057\u307E\u3059",
      advancedOptions: "\u8A73\u7D30\u30AA\u30D7\u30B7\u30E7\u30F3",
      model: "\u30E2\u30C7\u30EB",
      modelDesc: "\u3053\u306E\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u30E2\u30C7\u30EB\u4E0A\u66F8\u304D",
      tools: "\u30C4\u30FC\u30EB",
      toolsDesc: "\u8A31\u53EF\u3059\u308B\u30C4\u30FC\u30EB\u306E\u30AB\u30F3\u30DE\u533A\u5207\u308A\u30EA\u30B9\u30C8\uFF08\u7A7A\u6B04 = \u3059\u3079\u3066\uFF09",
      disallowedTools: "\u7981\u6B62\u30C4\u30FC\u30EB",
      disallowedToolsDesc: "\u7981\u6B62\u3059\u308B\u30C4\u30FC\u30EB\u306E\u30AB\u30F3\u30DE\u533A\u5207\u308A\u30EA\u30B9\u30C8",
      skills: "\u30B9\u30AD\u30EB",
      skillsDesc: "\u30B9\u30AD\u30EB\u306E\u30AB\u30F3\u30DE\u533A\u5207\u308A\u30EA\u30B9\u30C8",
      prompt: "\u30B7\u30B9\u30C6\u30E0\u30D7\u30ED\u30F3\u30D7\u30C8",
      promptDesc: "\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u3078\u306E\u6307\u793A",
      promptPlaceholder: "\u3042\u306A\u305F\u306F\u30B3\u30FC\u30C9\u30EC\u30D3\u30E5\u30A2\u30FC\u3067\u3059\u3002\u4E0E\u3048\u3089\u308C\u305F\u30B3\u30FC\u30C9\u3092\u5206\u6790\u3057\u3066..."
    }
  },
  safety: "\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3",
  loadUserSettings: {
    name: "\u30E6\u30FC\u30B6\u30FCClaude\u8A2D\u5B9A\u3092\u8AAD\u307F\u8FBC\u3080",
    desc: "~/.claude/settings.json \u3092\u8AAD\u307F\u8FBC\u307F\u307E\u3059\u3002\u6709\u52B9\u306B\u3059\u308B\u3068\u3001\u30E6\u30FC\u30B6\u30FC\u306E Claude Code \u8A31\u53EF\u30EB\u30FC\u30EB\u304C\u30BB\u30AD\u30E5\u30EA\u30C6\u30A3\u30E2\u30FC\u30C9\u3092\u30D0\u30A4\u30D1\u30B9\u3059\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002"
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "\u74B0\u5883",
  customVariables: {
    name: "\u30AB\u30B9\u30BF\u30E0\u5909\u6570",
    desc: "Claude SDK\u306E\u74B0\u5883\u5909\u6570\uFF08KEY=VALUE\u5F62\u5F0F\u30011\u884C\u306B1\u3064\uFF09\u3002export\u30D7\u30EC\u30D5\u30A3\u30C3\u30AF\u30B9\u5BFE\u5FDC\u3002"
  },
  envSnippets: {
    name: "\u30B9\u30CB\u30DA\u30C3\u30C8",
    addBtn: "\u30B9\u30CB\u30DA\u30C3\u30C8\u3092\u8FFD\u52A0",
    noSnippets: "\u4FDD\u5B58\u3055\u308C\u305F\u74B0\u5883\u5909\u6570\u30B9\u30CB\u30DA\u30C3\u30C8\u306F\u3042\u308A\u307E\u305B\u3093\u3002+\u3092\u30AF\u30EA\u30C3\u30AF\u3057\u3066\u73FE\u5728\u306E\u8A2D\u5B9A\u3092\u4FDD\u5B58\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
    nameRequired: "\u30B9\u30CB\u30DA\u30C3\u30C8\u306E\u540D\u524D\u3092\u5165\u529B\u3057\u3066\u304F\u3060\u3055\u3044",
    modal: {
      titleEdit: "\u30B9\u30CB\u30DA\u30C3\u30C8\u3092\u7DE8\u96C6",
      titleSave: "\u30B9\u30CB\u30DA\u30C3\u30C8\u3092\u4FDD\u5B58",
      name: "\u540D\u524D",
      namePlaceholder: "\u3053\u306E\u8A2D\u5B9A\u306E\u308F\u304B\u308A\u3084\u3059\u3044\u540D\u524D",
      description: "\u8AAC\u660E",
      descPlaceholder: "\u4EFB\u610F\u306E\u8AAC\u660E",
      envVars: "\u74B0\u5883\u5909\u6570",
      envVarsPlaceholder: "KEY=VALUE\u5F62\u5F0F\u30011\u884C\u306B1\u3064\uFF08export\u30D7\u30EC\u30D5\u30A3\u30C3\u30AF\u30B9\u5BFE\u5FDC\uFF09",
      save: "\u4FDD\u5B58",
      update: "\u66F4\u65B0",
      cancel: "\u30AD\u30E3\u30F3\u30BB\u30EB"
    }
  },
  customContextLimits: {
    name: "\u30AB\u30B9\u30BF\u30E0\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u5236\u9650",
    desc: "\u30AB\u30B9\u30BF\u30E0\u30E2\u30C7\u30EB\u306E\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30A6\u30A3\u30F3\u30C9\u30A6\u30B5\u30A4\u30BA\u3092\u8A2D\u5B9A\u3057\u307E\u3059\u3002\u30C7\u30D5\u30A9\u30EB\u30C8\uFF08200k\u30C8\u30FC\u30AF\u30F3\uFF09\u3092\u4F7F\u7528\u3059\u308B\u5834\u5408\u306F\u7A7A\u6B04\u306E\u307E\u307E\u306B\u3057\u3066\u304F\u3060\u3055\u3044\u3002",
    invalid: "\u7121\u52B9\u306A\u5F62\u5F0F\u3067\u3059\u3002\u4F7F\u7528\uFF1A256k\u30011m\u3001\u307E\u305F\u306F\u6B63\u78BA\u306A\u6570\u5024\uFF081000-10000000\uFF09\u3002"
  },
  enableOpus1M: {
    name: "Opus 1M\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30A6\u30A3\u30F3\u30C9\u30A6",
    desc: "\u30E2\u30C7\u30EB\u30BB\u30EC\u30AF\u30BF\u30FC\u306BOpus 1M\u3092\u8868\u793A\u3057\u307E\u3059\u3002Max\u3001Team\u3001Enterprise\u30D7\u30E9\u30F3\u306B\u542B\u307E\u308C\u307E\u3059\u3002API\u304A\u3088\u3073Pro\u30E6\u30FC\u30B6\u30FC\u306F\u8FFD\u52A0\u4F7F\u7528\u91CF\u304C\u5FC5\u8981\u3067\u3059\u3002"
  },
  enableSonnet1M: {
    name: "Sonnet 1M\u30B3\u30F3\u30C6\u30AD\u30B9\u30C8\u30A6\u30A3\u30F3\u30C9\u30A6",
    desc: "\u30E2\u30C7\u30EB\u30BB\u30EC\u30AF\u30BF\u30FC\u306BSonnet 1M\u3092\u8868\u793A\u3057\u307E\u3059\u3002Max\u3001Team\u3001Enterprise\u30D7\u30E9\u30F3\u3067\u306F\u8FFD\u52A0\u4F7F\u7528\u91CF\u304C\u5FC5\u8981\u3067\u3059\u3002API\u304A\u3088\u3073Pro\u30E6\u30FC\u30B6\u30FC\u306F\u8FFD\u52A0\u4F7F\u7528\u91CF\u304C\u5FC5\u8981\u3067\u3059\u3002"
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "Chrome\u62E1\u5F35\u6A5F\u80FD\u3092\u6709\u52B9\u5316",
    desc: "claude-in-chrome\u62E1\u5F35\u6A5F\u80FD\u3092\u901A\u3058\u3066Claude\u304CChrome\u3068\u9023\u643A\u3067\u304D\u308B\u3088\u3046\u306B\u3057\u307E\u3059\u3002\u62E1\u5F35\u6A5F\u80FD\u306E\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u304C\u5FC5\u8981\u3067\u3059\u3002\u30BB\u30C3\u30B7\u30E7\u30F3\u306E\u518D\u8D77\u52D5\u304C\u5FC5\u8981\u3067\u3059\u3002"
  },
  enableBangBash: {
    name: "bash \u30E2\u30FC\u30C9 (!) \u3092\u6709\u52B9\u5316",
    desc: "\u5165\u529B\u6B04\u304C\u7A7A\u306E\u72B6\u614B\u3067 ! \u3092\u5165\u529B\u3059\u308B\u3068 bash \u30E2\u30FC\u30C9\u306B\u5165\u308A\u307E\u3059\u3002Node.js \u306E child_process \u7D4C\u7531\u3067\u30B3\u30DE\u30F3\u30C9\u3092\u76F4\u63A5\u5B9F\u884C\u3057\u307E\u3059\u3002\u30D3\u30E5\u30FC\u306E\u518D\u30AA\u30FC\u30D7\u30F3\u304C\u5FC5\u8981\u3067\u3059\u3002",
    validation: {
      noNode: "PATH \u306B Node.js \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093\u3002Node.js \u3092\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u3059\u308B\u304B\u3001PATH \u8A2D\u5B9A\u3092\u78BA\u8A8D\u3057\u3066\u304F\u3060\u3055\u3044\u3002"
    }
  },
  maxTabs: {
    name: "\u6700\u5927\u30C1\u30E3\u30C3\u30C8\u30BF\u30D6\u6570",
    desc: "\u540C\u6642\u306B\u958B\u3051\u308B\u6700\u5927\u30C1\u30E3\u30C3\u30C8\u30BF\u30D6\u6570\uFF083-10\uFF09\u3002\u5404\u30BF\u30D6\u306F\u500B\u5225\u306E Claude \u30BB\u30C3\u30B7\u30E7\u30F3\u3092\u4F7F\u7528\u3057\u307E\u3059\u3002",
    warning: "5 \u30BF\u30D6\u3092\u8D85\u3048\u308B\u3068\u30D1\u30D5\u30A9\u30FC\u30DE\u30F3\u30B9\u3084\u30E1\u30E2\u30EA\u4F7F\u7528\u91CF\u306B\u5F71\u97FF\u3059\u308B\u53EF\u80FD\u6027\u304C\u3042\u308A\u307E\u3059\u3002"
  },
  tabBarPosition: {
    name: "\u30BF\u30D6\u30D0\u30FC\u306E\u4F4D\u7F6E",
    desc: "\u30BF\u30D6\u30D0\u30C3\u30B8\u3068\u30A2\u30AF\u30B7\u30E7\u30F3\u30DC\u30BF\u30F3\u306E\u8868\u793A\u4F4D\u7F6E\u3092\u9078\u629E",
    input: "\u5165\u529B\u6B04\u306E\u4E0A\uFF08\u30C7\u30D5\u30A9\u30EB\u30C8\uFF09",
    header: "\u30D8\u30C3\u30C0\u30FC\u5185"
  },
  enableAutoScroll: {
    name: "\u30B9\u30C8\u30EA\u30FC\u30DF\u30F3\u30B0\u4E2D\u306E\u81EA\u52D5\u30B9\u30AF\u30ED\u30FC\u30EB",
    desc: "Claude\u304C\u5FDC\u7B54\u3092\u30B9\u30C8\u30EA\u30FC\u30DF\u30F3\u30B0\u3057\u3066\u3044\u308B\u9593\u3001\u81EA\u52D5\u7684\u306B\u4E0B\u306B\u30B9\u30AF\u30ED\u30FC\u30EB\u3057\u307E\u3059\u3002\u7121\u52B9\u306B\u3059\u308B\u3068\u4E0A\u90E8\u306B\u7559\u307E\u308A\u3001\u6700\u521D\u304B\u3089\u8AAD\u3080\u3053\u3068\u304C\u3067\u304D\u307E\u3059\u3002"
  },
  openInMainTab: {
    name: "\u30E1\u30A4\u30F3\u30A8\u30C7\u30A3\u30BF\u9818\u57DF\u3067\u958B\u304F",
    desc: "\u30C1\u30E3\u30C3\u30C8\u30D1\u30CD\u30EB\u3092\u53F3\u30B5\u30A4\u30C9\u30D0\u30FC\u3067\u306F\u306A\u304F\u3001\u4E2D\u592E\u30A8\u30C7\u30A3\u30BF\u9818\u57DF\u306E\u30E1\u30A4\u30F3\u30BF\u30D6\u3068\u3057\u3066\u958B\u304D\u307E\u3059"
  },
  cliPath: {
    name: "Claude CLI \u30D1\u30B9",
    desc: "Claude Code CLI \u306E\u30AB\u30B9\u30BF\u30E0\u30D1\u30B9\u3002\u7A7A\u6B04\u3067\u81EA\u52D5\u691C\u51FA\u3092\u4F7F\u7528\u3002",
    descWindows: "\u30CD\u30A4\u30C6\u30A3\u30D6\u30A4\u30F3\u30B9\u30C8\u30FC\u30E9\u30FC\u306E\u5834\u5408\u306F claude.exe \u3092\u4F7F\u7528\u3002npm/pnpm/yarn \u3084\u305D\u306E\u4ED6\u306E\u30D1\u30C3\u30B1\u30FC\u30B8\u30DE\u30CD\u30FC\u30B8\u30E3\u30FC\u3067\u306E\u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u306E\u5834\u5408\u306F cli.js \u30D1\u30B9\u3092\u4F7F\u7528\uFF08claude.cmd \u3067\u306F\u306A\u3044\uFF09\u3002",
    descUnix: '"which claude" \u306E\u51FA\u529B\u3092\u8CBC\u308A\u4ED8\u3051\u3066\u304F\u3060\u3055\u3044 - \u30CD\u30A4\u30C6\u30A3\u30D6\u3068 npm/pnpm/yarn \u30A4\u30F3\u30B9\u30C8\u30FC\u30EB\u306E\u4E21\u65B9\u3067\u52D5\u4F5C\u3057\u307E\u3059\u3002',
    validation: {
      notExist: "\u30D1\u30B9\u304C\u5B58\u5728\u3057\u307E\u305B\u3093",
      isDirectory: "\u30D1\u30B9\u306F\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3067\u30D5\u30A1\u30A4\u30EB\u3067\u306F\u3042\u308A\u307E\u305B\u3093"
    }
  },
  language: {
    name: "\u8A00\u8A9E",
    desc: "\u30D7\u30E9\u30B0\u30A4\u30F3\u30A4\u30F3\u30BF\u30FC\u30D5\u30A7\u30FC\u30B9\u306E\u8868\u793A\u8A00\u8A9E\u3092\u5909\u66F4"
  }
};
var ja_default = {
  common: common5,
  chat: chat5,
  settings: settings5
};

// src/i18n/locales/ko.json
var ko_exports = {};
__export(ko_exports, {
  chat: () => chat6,
  common: () => common6,
  default: () => ko_default,
  settings: () => settings6
});
var common6 = {
  save: "\uC800\uC7A5",
  cancel: "\uCDE8\uC18C",
  delete: "\uC0AD\uC81C",
  edit: "\uD3B8\uC9D1",
  add: "\uCD94\uAC00",
  remove: "\uC81C\uAC70",
  clear: "\uC9C0\uC6B0\uAE30",
  clearAll: "\uBAA8\uB450 \uC9C0\uC6B0\uAE30",
  loading: "\uB85C\uB529 \uC911",
  error: "\uC624\uB958",
  success: "\uC131\uACF5",
  warning: "\uACBD\uACE0",
  confirm: "\uD655\uC778",
  settings: "\uC124\uC815",
  advanced: "\uACE0\uAE09",
  enabled: "\uD65C\uC131\uD654",
  disabled: "\uBE44\uD65C\uC131\uD654",
  platform: "\uD50C\uB7AB\uD3FC",
  refresh: "\uC0C8\uB85C\uACE0\uCE68",
  rewind: "\uB418\uAC10\uAE30"
};
var chat6 = {
  rewind: {
    confirmMessage: "\uC774 \uC2DC\uC810\uC73C\uB85C \uB418\uAC10\uC73C\uC2DC\uACA0\uC2B5\uB2C8\uAE4C? \uC774 \uBA54\uC2DC\uC9C0 \uC774\uD6C4\uC758 \uD30C\uC77C \uBCC0\uACBD \uC0AC\uD56D\uC774 \uB418\uB3CC\uB824\uC9D1\uB2C8\uB2E4. \uC218\uB3D9\uC73C\uB85C \uB610\uB294 bash\uB97C \uD1B5\uD574 \uD3B8\uC9D1\uB41C \uD30C\uC77C\uC5D0\uB294 \uC601\uD5A5\uC744 \uBBF8\uCE58\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4.",
    confirmButton: "\uB418\uAC10\uAE30",
    ariaLabel: "\uC5EC\uAE30\uB85C \uB418\uAC10\uAE30",
    notice: "\uB418\uAC10\uAE30 \uC644\uB8CC: {count}\uAC1C \uD30C\uC77C \uBCF5\uC6D0\uB428",
    noticeSaveFailed: "\uB418\uAC10\uAE30 \uC644\uB8CC: {count}\uAC1C \uD30C\uC77C \uBCF5\uC6D0\uB428, \uD558\uC9C0\uB9CC \uC0C1\uD0DC\uB97C \uC800\uC7A5\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: {error}",
    failed: "\uB418\uAC10\uAE30 \uC2E4\uD328: {error}",
    cannot: "\uB418\uAC10\uAE30 \uBD88\uAC00: {error}",
    unavailableStreaming: "\uC2A4\uD2B8\uB9AC\uBC0D \uC911\uC5D0\uB294 \uB418\uAC10\uAE30\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4",
    unavailableNoUuid: "\uB418\uAC10\uAE30 \uBD88\uAC00: \uBA54\uC2DC\uC9C0 \uC2DD\uBCC4\uC790 \uB204\uB77D"
  },
  fork: {
    ariaLabel: "\uB300\uD654 \uBD84\uAE30",
    chooseTarget: "\uB300\uD654 \uBD84\uAE30",
    targetNewTab: "\uC0C8 \uD0ED",
    targetCurrentTab: "\uD604\uC7AC \uD0ED",
    maxTabsReached: "\uBD84\uAE30 \uBD88\uAC00: \uCD5C\uB300 {count}\uAC1C \uD0ED\uC5D0 \uB3C4\uB2EC\uD588\uC2B5\uB2C8\uB2E4",
    notice: "\uC0C8 \uD0ED\uC73C\uB85C \uBD84\uAE30\uB428",
    noticeCurrentTab: "\uD604\uC7AC \uD0ED\uC5D0\uC11C \uBD84\uAE30\uB428",
    failed: "\uBD84\uAE30 \uC2E4\uD328: {error}",
    unavailableStreaming: "\uC2A4\uD2B8\uB9AC\uBC0D \uC911\uC5D0\uB294 \uBD84\uAE30\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4",
    unavailableNoUuid: "\uBD84\uAE30 \uBD88\uAC00: \uBA54\uC2DC\uC9C0 \uC2DD\uBCC4\uC790 \uB204\uB77D",
    unavailableNoResponse: "\uBD84\uAE30 \uBD88\uAC00: \uBD84\uAE30\uD560 \uC751\uB2F5\uC774 \uC5C6\uC2B5\uB2C8\uB2E4",
    errorMessageNotFound: "\uBA54\uC2DC\uC9C0\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4",
    errorNoSession: "\uC0AC\uC6A9 \uAC00\uB2A5\uD55C \uC138\uC158 ID\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4",
    errorNoActiveTab: "\uD65C\uC131 \uD0ED\uC774 \uC5C6\uC2B5\uB2C8\uB2E4",
    commandNoMessages: "\uD3EC\uD06C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: \uB300\uD654\uC5D0 \uBA54\uC2DC\uC9C0\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4",
    commandNoAssistantUuid: "\uD3EC\uD06C\uD560 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4: \uC2DD\uBCC4\uC790\uAC00 \uC788\uB294 \uC5B4\uC2DC\uC2A4\uD134\uD2B8 \uC751\uB2F5\uC774 \uC5C6\uC2B5\uB2C8\uB2E4"
  },
  bangBash: {
    placeholder: "> bash \uBA85\uB839 \uC2E4\uD589...",
    commandPanel: "\uBA85\uB839 \uD328\uB110",
    copyAriaLabel: "\uCD5C\uC2E0 \uBA85\uB839 \uCD9C\uB825\uC744 \uBCF5\uC0AC",
    clearAriaLabel: "bash \uCD9C\uB825 \uC9C0\uC6B0\uAE30",
    commandLabel: "{command}",
    statusLabel: "\uC0C1\uD0DC: {status}",
    collapseOutput: "\uBA85\uB839 \uCD9C\uB825 \uC811\uAE30",
    expandOutput: "\uBA85\uB839 \uCD9C\uB825 \uD3BC\uCE58\uAE30",
    running: "\uC2E4\uD589 \uC911...",
    copyFailed: "\uD074\uB9BD\uBCF4\uB4DC\uC5D0 \uBCF5\uC0AC\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4"
  }
};
var settings6 = {
  title: "Claudian \uC124\uC815",
  tabs: {
    general: "\uC77C\uBC18",
    claude: "Claude",
    codex: "Codex"
  },
  display: "\uD45C\uC2DC",
  conversations: "\uB300\uD654",
  content: "\uCF58\uD150\uCE20",
  input: "\uC785\uB825",
  setup: "\uC124\uC815",
  models: "\uBAA8\uB378",
  experimental: "\uC2E4\uD5D8\uC801 \uAE30\uB2A5",
  userName: {
    name: "Claudian\uC774 \uB2F9\uC2E0\uC744 \uC5B4\uB5BB\uAC8C \uBD88\uB7EC\uC57C \uD569\uB2C8\uAE4C?",
    desc: "\uAC1C\uC778\uD654\uB41C \uC778\uC0AC\uC5D0 \uC0AC\uC6A9\uD560 \uC774\uB984 (\uBE44\uC6CC\uB450\uBA74 \uC77C\uBC18 \uC778\uC0AC)"
  },
  excludedTags: {
    name: "\uC81C\uC678 \uD0DC\uADF8",
    desc: "\uC774 \uD0DC\uADF8\uAC00 \uD3EC\uD568\uB41C \uB178\uD2B8\uB294 \uC790\uB3D9\uC73C\uB85C \uCEE8\uD14D\uC2A4\uD2B8\uB85C \uB85C\uB4DC\uB418\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4 (\uD55C \uC904\uC5D0 \uD558\uB098, # \uC81C\uC678)"
  },
  mediaFolder: {
    name: "\uBBF8\uB514\uC5B4 \uD3F4\uB354",
    desc: "\uCCA8\uBD80 \uD30C\uC77C/\uC774\uBBF8\uC9C0\uB97C \uC800\uC7A5\uD560 \uD3F4\uB354. \uB178\uD2B8\uAC00 ![[image.jpg]]\uB97C \uC0AC\uC6A9\uD560 \uB54C Claude\uAC00 \uC5EC\uAE30\uC11C \uCC3E\uC2B5\uB2C8\uB2E4. \uBE44\uC6CC\uB450\uBA74 \uC800\uC7A5\uC18C \uB8E8\uD2B8 \uC0AC\uC6A9."
  },
  systemPrompt: {
    name: "\uCEE4\uC2A4\uD140 \uC2DC\uC2A4\uD15C \uD504\uB86C\uD504\uD2B8",
    desc: "\uAE30\uBCF8 \uC2DC\uC2A4\uD15C \uD504\uB86C\uD504\uD2B8\uC5D0 \uCD94\uAC00\uB418\uB294 \uCD94\uAC00 \uC9C0\uCE68"
  },
  autoTitle: {
    name: "\uB300\uD654 \uC81C\uBAA9 \uC790\uB3D9 \uC0DD\uC131",
    desc: "\uCCAB \uBC88\uC9F8 \uC0AC\uC6A9\uC790 \uBA54\uC2DC\uC9C0 \uC804\uC1A1 \uD6C4 \uC790\uB3D9\uC73C\uB85C \uB300\uD654 \uC81C\uBAA9\uC744 \uC0DD\uC131\uD569\uB2C8\uB2E4."
  },
  titleModel: {
    name: "\uC81C\uBAA9 \uC0DD\uC131 \uBAA8\uB378",
    desc: "\uB300\uD654 \uC81C\uBAA9\uC744 \uC790\uB3D9 \uC0DD\uC131\uD558\uB294 \uB370 \uC0AC\uC6A9\uB418\uB294 \uBAA8\uB378.",
    auto: "\uC790\uB3D9 (Haiku)"
  },
  navMappings: {
    name: "Vim \uC2A4\uD0C0\uC77C \uB124\uBE44\uAC8C\uC774\uC158 \uB9E4\uD551",
    desc: '\uD55C \uC904\uC5D0 \uD558\uB098\uC758 \uB9E4\uD551. \uD615\uC2DD: "map <\uD0A4> <\uB3D9\uC791>" (\uB3D9\uC791: scrollUp, scrollDown, focusInput).'
  },
  hotkeys: "\uB2E8\uCD95\uD0A4",
  inlineEditHotkey: {
    name: "\uC778\uB77C\uC778 \uD3B8\uC9D1",
    descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}",
    descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815",
    btnChange: "\uBCC0\uACBD",
    btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815"
  },
  openChatHotkey: {
    name: "\uCC44\uD305 \uC5F4\uAE30",
    descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}",
    descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815",
    btnChange: "\uBCC0\uACBD",
    btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815"
  },
  newSessionHotkey: {
    name: "\uC0C8 \uC138\uC158",
    descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}",
    descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815",
    btnChange: "\uBCC0\uACBD",
    btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815"
  },
  newTabHotkey: {
    name: "\uC0C8 \uD0ED",
    descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}",
    descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815",
    btnChange: "\uBCC0\uACBD",
    btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815"
  },
  closeTabHotkey: {
    name: "\uD0ED \uB2EB\uAE30",
    descWithKey: "\uD604\uC7AC \uB2E8\uCD95\uD0A4: {hotkey}",
    descNoKey: "\uB2E8\uCD95\uD0A4 \uBBF8\uC124\uC815",
    btnChange: "\uBCC0\uACBD",
    btnSet: "\uB2E8\uCD95\uD0A4 \uC124\uC815"
  },
  slashCommands: {
    name: "\uBA85\uB839\uC5B4\uC640 \uC2A4\uD0AC",
    desc: ".claude/commands/ \uBC0F .claude/skills/\uC5D0 \uC800\uC7A5\uB41C Vault \uC218\uC900\uC758 \uBA85\uB839\uC5B4\uC640 \uC2A4\uD0AC\uC744 \uAD00\uB9AC\uD569\uB2C8\uB2E4. /\uC774\uB984\uC73C\uB85C \uD2B8\uB9AC\uAC70\uB429\uB2C8\uB2E4."
  },
  hiddenSlashCommands: {
    name: "\uC228\uACA8\uC9C4 \uBA85\uB839\uC5B4\uC640 \uC2A4\uD0AC",
    desc: "\uB4DC\uB86D\uB2E4\uC6B4\uC5D0\uC11C \uD2B9\uC815 \uBA85\uB839\uC5B4\uC640 \uC2A4\uD0AC\uC744 \uC228\uAE41\uB2C8\uB2E4. Claudian\uACFC \uAD00\uB828 \uC5C6\uB294 Claude Code \uD56D\uBAA9\uC744 \uC228\uAE30\uB294 \uB370 \uC720\uC6A9\uD569\uB2C8\uB2E4. \uC55E\uC758 \uC2AC\uB798\uC2DC \uC5C6\uC774 \uC774\uB984\uC744 \uD55C \uC904\uC5D0 \uD558\uB098\uC529 \uC785\uB825\uD558\uC138\uC694.",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "MCP \uC11C\uBC84",
    desc: ".claude/mcp.json\uC5D0 \uC800\uC7A5\uB41C Vault \uC218\uC900\uC758 MCP \uC11C\uBC84 \uAD6C\uC131\uC744 \uAD00\uB9AC\uD569\uB2C8\uB2E4. \uCEE8\uD14D\uC2A4\uD2B8 \uC800\uC7A5 \uBAA8\uB4DC \uC11C\uBC84\uB294 @mention\uC73C\uB85C \uD65C\uC131\uD654\uD574\uC57C \uD569\uB2C8\uB2E4."
  },
  plugins: {
    name: "Claude Code \uD50C\uB7EC\uADF8\uC778",
    desc: "~/.claude/plugins\uC5D0\uC11C \uBC1C\uACAC\uB41C Claude Code \uD50C\uB7EC\uADF8\uC778\uC744 \uAD00\uB9AC\uD569\uB2C8\uB2E4. \uD65C\uC131\uD654\uB41C \uD50C\uB7EC\uADF8\uC778\uC740 .claude/settings.json\uC5D0 Vault\uBCC4\uB85C \uC800\uC7A5\uB429\uB2C8\uB2E4."
  },
  subagents: {
    name: "\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8",
    desc: ".claude/agents/\uC5D0 \uC800\uC7A5\uB41C Vault \uC218\uC900\uC758 \uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8\uB97C \uAD00\uB9AC\uD569\uB2C8\uB2E4. \uAC01 Markdown \uD30C\uC77C\uC774 \uD558\uB098\uC758 \uCEE4\uC2A4\uD140 \uC5D0\uC774\uC804\uD2B8\uB97C \uC815\uC758\uD569\uB2C8\uB2E4.",
    noAgents: "\uAD6C\uC131\uB41C \uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8\uAC00 \uC5C6\uC2B5\uB2C8\uB2E4. +\uB97C \uD074\uB9AD\uD574 \uC0C8\uB85C \uB9CC\uB4DC\uC138\uC694.",
    deleteConfirm: '\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8 "{name}"\uC744 \uC0AD\uC81C\uD558\uC2DC\uACA0\uC2B5\uB2C8\uAE4C?',
    saveFailed: "\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8\uB97C \uC800\uC7A5\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: {message}",
    refreshFailed: "\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8\uB97C \uC0C8\uB85C\uACE0\uCE68\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: {message}",
    deleteFailed: "\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8\uB97C \uC0AD\uC81C\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4: {message}",
    renameCleanupFailed: '\uACBD\uACE0: "{name}"\uC758 \uC774\uC804 \uD30C\uC77C\uC744 \uC81C\uAC70\uD558\uC9C0 \uBABB\uD588\uC2B5\uB2C8\uB2E4',
    created: '\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8 "{name}"\uB97C \uC0DD\uC131\uD588\uC2B5\uB2C8\uB2E4',
    updated: '\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8 "{name}"\uB97C \uC5C5\uB370\uC774\uD2B8\uD588\uC2B5\uB2C8\uB2E4',
    deleted: '\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8 "{name}"\uB97C \uC0AD\uC81C\uD588\uC2B5\uB2C8\uB2E4',
    duplicateName: '"{name}"\uC774\uB77C\uB294 \uC774\uB984\uC758 \uC5D0\uC774\uC804\uD2B8\uAC00 \uC774\uBBF8 \uC788\uC2B5\uB2C8\uB2E4',
    descriptionRequired: "\uC124\uBA85\uC740 \uD544\uC218\uC785\uB2C8\uB2E4",
    promptRequired: "\uC2DC\uC2A4\uD15C \uD504\uB86C\uD504\uD2B8\uB294 \uD544\uC218\uC785\uB2C8\uB2E4",
    modal: {
      titleEdit: "\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8 \uD3B8\uC9D1",
      titleAdd: "\uC11C\uBE0C\uC5D0\uC774\uC804\uD2B8 \uCD94\uAC00",
      name: "\uC774\uB984",
      nameDesc: "\uC18C\uBB38\uC790, \uC22B\uC790, \uD558\uC774\uD508\uB9CC \uC0AC\uC6A9\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4",
      namePlaceholder: "code-reviewer",
      description: "\uC124\uBA85",
      descriptionDesc: "\uC774 \uC5D0\uC774\uC804\uD2B8\uC5D0 \uB300\uD55C \uAC04\uB2E8\uD55C \uC124\uBA85",
      descriptionPlaceholder: "\uCF54\uB4DC\uC758 \uBC84\uADF8\uC640 \uC2A4\uD0C0\uC77C\uC744 \uAC80\uD1A0\uD569\uB2C8\uB2E4",
      advancedOptions: "\uACE0\uAE09 \uC635\uC158",
      model: "\uBAA8\uB378",
      modelDesc: "\uC774 \uC5D0\uC774\uC804\uD2B8\uC5D0 \uC0AC\uC6A9\uD560 \uBAA8\uB378 \uC7AC\uC815\uC758",
      tools: "\uB3C4\uAD6C",
      toolsDesc: "\uD5C8\uC6A9\uD560 \uB3C4\uAD6C\uB97C \uC27C\uD45C\uB85C \uAD6C\uBD84\uD574 \uC785\uB825\uD558\uC138\uC694 (\uBE44\uC6CC\uB450\uBA74 \uBAA8\uB450 \uD5C8\uC6A9)",
      disallowedTools: "\uAE08\uC9C0 \uB3C4\uAD6C",
      disallowedToolsDesc: "\uAE08\uC9C0\uD560 \uB3C4\uAD6C\uB97C \uC27C\uD45C\uB85C \uAD6C\uBD84\uD574 \uC785\uB825\uD558\uC138\uC694",
      skills: "\uC2A4\uD0AC",
      skillsDesc: "\uC2A4\uD0AC \uBAA9\uB85D\uC744 \uC27C\uD45C\uB85C \uAD6C\uBD84\uD574 \uC785\uB825\uD558\uC138\uC694",
      prompt: "\uC2DC\uC2A4\uD15C \uD504\uB86C\uD504\uD2B8",
      promptDesc: "\uC5D0\uC774\uC804\uD2B8\uC6A9 \uC9C0\uCE68",
      promptPlaceholder: "\uB2F9\uC2E0\uC740 \uCF54\uB4DC \uB9AC\uBDF0\uC5B4\uC785\uB2C8\uB2E4. \uC8FC\uC5B4\uC9C4 \uCF54\uB4DC\uB97C \uBD84\uC11D\uD558\uC5EC..."
    }
  },
  safety: "\uBCF4\uC548",
  loadUserSettings: {
    name: "\uC0AC\uC6A9\uC790 Claude \uC124\uC815 \uB85C\uB4DC",
    desc: "~/.claude/settings.json\uC744 \uB85C\uB4DC\uD569\uB2C8\uB2E4. \uD65C\uC131\uD654\uD558\uBA74 \uC0AC\uC6A9\uC790\uC758 Claude Code \uD5C8\uC6A9 \uADDC\uCE59\uC774 \uBCF4\uC548 \uBAA8\uB4DC\uB97C \uC6B0\uD68C\uD560 \uC218 \uC788\uC2B5\uB2C8\uB2E4."
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "\uD658\uACBD",
  customVariables: {
    name: "\uCEE4\uC2A4\uD140 \uBCC0\uC218",
    desc: "Claude SDK \uD658\uACBD \uBCC0\uC218 (KEY=VALUE \uD615\uC2DD, \uD55C \uC904\uC5D0 \uD558\uB098). export \uC811\uB450\uC0AC \uC9C0\uC6D0."
  },
  envSnippets: {
    name: "\uC2A4\uB2C8\uD3AB",
    addBtn: "\uC2A4\uB2C8\uD3AB \uCD94\uAC00",
    noSnippets: "\uC800\uC7A5\uB41C \uD658\uACBD \uBCC0\uC218 \uC2A4\uB2C8\uD3AB\uC774 \uC5C6\uC2B5\uB2C8\uB2E4. +\uB97C \uD074\uB9AD\uD558\uC5EC \uD604\uC7AC \uAD6C\uC131\uC744 \uC800\uC7A5\uD558\uC138\uC694.",
    nameRequired: "\uC2A4\uB2C8\uD3AB \uC774\uB984\uC744 \uC785\uB825\uD558\uC138\uC694",
    modal: {
      titleEdit: "\uC2A4\uB2C8\uD3AB \uD3B8\uC9D1",
      titleSave: "\uC2A4\uB2C8\uD3AB \uC800\uC7A5",
      name: "\uC774\uB984",
      namePlaceholder: "\uC774 \uAD6C\uC131\uC5D0 \uB300\uD55C \uC124\uBA85\uC801\uC778 \uC774\uB984",
      description: "\uC124\uBA85",
      descPlaceholder: "\uC120\uD0DD\uC801 \uC124\uBA85",
      envVars: "\uD658\uACBD \uBCC0\uC218",
      envVarsPlaceholder: "KEY=VALUE \uD615\uC2DD, \uD55C \uC904\uC5D0 \uD558\uB098 (export \uC811\uB450\uC0AC \uC9C0\uC6D0)",
      save: "\uC800\uC7A5",
      update: "\uC5C5\uB370\uC774\uD2B8",
      cancel: "\uCDE8\uC18C"
    }
  },
  customContextLimits: {
    name: "\uC0AC\uC6A9\uC790 \uC815\uC758 \uCEE8\uD14D\uC2A4\uD2B8 \uC81C\uD55C",
    desc: "\uC0AC\uC6A9\uC790 \uC815\uC758 \uBAA8\uB378\uC758 \uCEE8\uD14D\uC2A4\uD2B8 \uCC3D \uD06C\uAE30\uB97C \uC124\uC815\uD569\uB2C8\uB2E4. \uAE30\uBCF8\uAC12(200k \uD1A0\uD070)\uC744 \uC0AC\uC6A9\uD558\uB824\uBA74 \uBE44\uC6CC\uB450\uC138\uC694.",
    invalid: "\uC798\uBABB\uB41C \uD615\uC2DD\uC785\uB2C8\uB2E4. \uC0AC\uC6A9: 256k, 1m \uB610\uB294 \uC815\uD655\uD55C \uC22B\uC790(1000-10000000)."
  },
  enableOpus1M: {
    name: "Opus 1M \uCEE8\uD14D\uC2A4\uD2B8 \uC708\uB3C4\uC6B0",
    desc: "\uBAA8\uB378 \uC120\uD0DD\uAE30\uC5D0\uC11C Opus 1M\uC744 \uD45C\uC2DC\uD569\uB2C8\uB2E4. Max, Team, Enterprise \uD50C\uB79C\uC5D0 \uD3EC\uD568\uB429\uB2C8\uB2E4. API \uBC0F Pro \uC0AC\uC6A9\uC790\uB294 \uCD94\uAC00 \uC0AC\uC6A9\uB7C9\uC774 \uD544\uC694\uD569\uB2C8\uB2E4."
  },
  enableSonnet1M: {
    name: "Sonnet 1M \uCEE8\uD14D\uC2A4\uD2B8 \uC708\uB3C4\uC6B0",
    desc: "\uBAA8\uB378 \uC120\uD0DD\uAE30\uC5D0\uC11C Sonnet 1M\uC744 \uD45C\uC2DC\uD569\uB2C8\uB2E4. Max, Team, Enterprise \uD50C\uB79C\uC5D0\uC11C \uCD94\uAC00 \uC0AC\uC6A9\uB7C9\uC774 \uD544\uC694\uD569\uB2C8\uB2E4. API \uBC0F Pro \uC0AC\uC6A9\uC790\uB294 \uCD94\uAC00 \uC0AC\uC6A9\uB7C9\uC774 \uD544\uC694\uD569\uB2C8\uB2E4."
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "Chrome \uD655\uC7A5 \uD504\uB85C\uADF8\uB7A8 \uD65C\uC131\uD654",
    desc: "claude-in-chrome \uD655\uC7A5 \uD504\uB85C\uADF8\uB7A8\uC744 \uD1B5\uD574 Claude\uAC00 Chrome\uACFC \uC0C1\uD638\uC791\uC6A9\uD560 \uC218 \uC788\uB3C4\uB85D \uD569\uB2C8\uB2E4. \uD655\uC7A5 \uD504\uB85C\uADF8\uB7A8\uC774 \uC124\uCE58\uB418\uC5B4 \uC788\uC5B4\uC57C \uD569\uB2C8\uB2E4. \uC138\uC158 \uC7AC\uC2DC\uC791\uC774 \uD544\uC694\uD569\uB2C8\uB2E4."
  },
  enableBangBash: {
    name: "bash \uBAA8\uB4DC (!) \uD65C\uC131\uD654",
    desc: "\uC785\uB825\uCC3D\uC774 \uBE44\uC5B4 \uC788\uC744 \uB54C !\uB97C \uC785\uB825\uD558\uBA74 bash \uBAA8\uB4DC\uB85C \uB4E4\uC5B4\uAC11\uB2C8\uB2E4. Node.js child_process\uB97C \uD1B5\uD574 \uBA85\uB839\uC744 \uC9C1\uC811 \uC2E4\uD589\uD569\uB2C8\uB2E4. \uBCF4\uAE30\uB97C \uB2E4\uC2DC \uC5F4\uC5B4\uC57C \uD569\uB2C8\uB2E4.",
    validation: {
      noNode: "PATH\uC5D0\uC11C Node.js\uB97C \uCC3E\uC744 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4. Node.js\uB97C \uC124\uCE58\uD558\uAC70\uB098 PATH \uC124\uC815\uC744 \uD655\uC778\uD558\uC138\uC694."
    }
  },
  maxTabs: {
    name: "\uCD5C\uB300 \uCC44\uD305 \uD0ED \uC218",
    desc: "\uB3D9\uC2DC\uC5D0 \uC5F4 \uC218 \uC788\uB294 \uCD5C\uB300 \uCC44\uD305 \uD0ED \uC218(3-10). \uAC01 \uD0ED\uC740 \uBCC4\uB3C4\uC758 Claude \uC138\uC158\uC744 \uC0AC\uC6A9\uD569\uB2C8\uB2E4.",
    warning: "5\uAC1C \uD0ED\uC744 \uCD08\uACFC\uD558\uBA74 \uC131\uB2A5 \uBC0F \uBA54\uBAA8\uB9AC \uC0AC\uC6A9\uB7C9\uC5D0 \uC601\uD5A5\uC744 \uC904 \uC218 \uC788\uC2B5\uB2C8\uB2E4."
  },
  tabBarPosition: {
    name: "\uD0ED \uBC14 \uC704\uCE58",
    desc: "\uD0ED \uBC30\uC9C0\uC640 \uC791\uC5C5 \uBC84\uD2BC\uC758 \uD45C\uC2DC \uC704\uCE58 \uC120\uD0DD",
    input: "\uC785\uB825\uCC3D \uC704(\uAE30\uBCF8\uAC12)",
    header: "\uD5E4\uB354\uC5D0"
  },
  enableAutoScroll: {
    name: "\uC2A4\uD2B8\uB9AC\uBC0D \uC911 \uC790\uB3D9 \uC2A4\uD06C\uB864",
    desc: "Claude\uAC00 \uC751\uB2F5\uC744 \uC2A4\uD2B8\uB9AC\uBC0D\uD558\uB294 \uB3D9\uC548 \uC790\uB3D9\uC73C\uB85C \uC544\uB798\uB85C \uC2A4\uD06C\uB864\uD569\uB2C8\uB2E4. \uBE44\uD65C\uC131\uD654\uD558\uBA74 \uC0C1\uB2E8\uC5D0 \uBA38\uBB3C\uB7EC \uCC98\uC74C\uBD80\uD130 \uC77D\uC744 \uC218 \uC788\uC2B5\uB2C8\uB2E4."
  },
  openInMainTab: {
    name: "\uBA54\uC778 \uD3B8\uC9D1\uAE30 \uC601\uC5ED\uC5D0\uC11C \uC5F4\uAE30",
    desc: "\uCC44\uD305 \uD328\uB110\uC744 \uC624\uB978\uCABD \uC0AC\uC774\uB4DC\uBC14\uAC00 \uC544\uB2CC \uC911\uC559 \uD3B8\uC9D1\uAE30 \uC601\uC5ED\uC758 \uBA54\uC778 \uD0ED\uC73C\uB85C \uC5FD\uB2C8\uB2E4"
  },
  cliPath: {
    name: "Claude CLI \uACBD\uB85C",
    desc: "Claude Code CLI\uC758 \uC0AC\uC6A9\uC790 \uC815\uC758 \uACBD\uB85C. \uBE44\uC6CC\uB450\uBA74 \uC790\uB3D9 \uAC10\uC9C0 \uC0AC\uC6A9.",
    descWindows: "\uB124\uC774\uD2F0\uBE0C \uC124\uCE58 \uD504\uB85C\uADF8\uB7A8\uC758 \uACBD\uC6B0 claude.exe\uB97C \uC0AC\uC6A9\uD558\uC138\uC694. npm/pnpm/yarn \uB610\uB294 \uAE30\uD0C0 \uD328\uD0A4\uC9C0 \uAD00\uB9AC\uC790 \uC124\uCE58\uC758 \uACBD\uC6B0 cli.js \uACBD\uB85C\uB97C \uC0AC\uC6A9\uD558\uC138\uC694 (claude.cmd\uAC00 \uC544\uB2D8).",
    descUnix: '"which claude"\uC758 \uCD9C\uB825\uC744 \uBD99\uC5EC\uB123\uC73C\uC138\uC694 - \uB124\uC774\uD2F0\uBE0C \uBC0F npm/pnpm/yarn \uC124\uCE58 \uBAA8\uB450\uC5D0\uC11C \uC791\uB3D9\uD569\uB2C8\uB2E4.',
    validation: {
      notExist: "\uACBD\uB85C\uAC00 \uC874\uC7AC\uD558\uC9C0 \uC54A\uC2B5\uB2C8\uB2E4",
      isDirectory: "\uACBD\uB85C\uAC00 \uB514\uB809\uD1A0\uB9AC\uC785\uB2C8\uB2E4 \uD30C\uC77C\uC774 \uC544\uB2D9\uB2C8\uB2E4"
    }
  },
  language: {
    name: "\uC5B8\uC5B4",
    desc: "\uD50C\uB7EC\uADF8\uC778 \uC778\uD130\uD398\uC774\uC2A4\uC758 \uD45C\uC2DC \uC5B8\uC5B4 \uBCC0\uACBD"
  }
};
var ko_default = {
  common: common6,
  chat: chat6,
  settings: settings6
};

// src/i18n/locales/pt.json
var pt_exports = {};
__export(pt_exports, {
  chat: () => chat7,
  common: () => common7,
  default: () => pt_default,
  settings: () => settings7
});
var common7 = {
  save: "Salvar",
  cancel: "Cancelar",
  delete: "Excluir",
  edit: "Editar",
  add: "Adicionar",
  remove: "Remover",
  clear: "Limpar",
  clearAll: "Limpar tudo",
  loading: "Carregando",
  error: "Erro",
  success: "Sucesso",
  warning: "Aviso",
  confirm: "Confirmar",
  settings: "Configura\xE7\xF5es",
  advanced: "Avan\xE7ado",
  enabled: "Ativado",
  disabled: "Desativado",
  platform: "Plataforma",
  refresh: "Atualizar",
  rewind: "Retroceder"
};
var chat7 = {
  rewind: {
    confirmMessage: "Retroceder at\xE9 este ponto? As altera\xE7\xF5es de arquivos ap\xF3s esta mensagem ser\xE3o revertidas. O retrocesso n\xE3o afeta arquivos editados manualmente ou via bash.",
    confirmButton: "Retroceder",
    ariaLabel: "Retroceder at\xE9 aqui",
    notice: "Retrocedido: {count} arquivo(s) revertido(s)",
    noticeSaveFailed: "Retrocedido: {count} arquivo(s) revertido(s), mas n\xE3o foi poss\xEDvel salvar o estado: {error}",
    failed: "Falha ao retroceder: {error}",
    cannot: "N\xE3o \xE9 poss\xEDvel retroceder: {error}",
    unavailableStreaming: "N\xE3o \xE9 poss\xEDvel retroceder durante a transmiss\xE3o",
    unavailableNoUuid: "N\xE3o \xE9 poss\xEDvel retroceder: identificadores de mensagem ausentes"
  },
  fork: {
    ariaLabel: "Bifurcar conversa",
    chooseTarget: "Bifurcar conversa",
    targetNewTab: "Nova aba",
    targetCurrentTab: "Aba atual",
    maxTabsReached: "N\xE3o \xE9 poss\xEDvel bifurcar: m\xE1ximo de {count} abas atingido",
    notice: "Bifurcado para nova aba",
    noticeCurrentTab: "Bifurcado na aba atual",
    failed: "Falha ao bifurcar: {error}",
    unavailableStreaming: "N\xE3o \xE9 poss\xEDvel bifurcar durante a transmiss\xE3o",
    unavailableNoUuid: "N\xE3o \xE9 poss\xEDvel bifurcar: identificadores de mensagem ausentes",
    unavailableNoResponse: "N\xE3o \xE9 poss\xEDvel bifurcar: nenhuma resposta para bifurcar",
    errorMessageNotFound: "Mensagem n\xE3o encontrada",
    errorNoSession: "Nenhum ID de sess\xE3o dispon\xEDvel",
    errorNoActiveTab: "Nenhuma aba ativa",
    commandNoMessages: "N\xE3o \xE9 poss\xEDvel bifurcar: n\xE3o h\xE1 mensagens na conversa",
    commandNoAssistantUuid: "N\xE3o \xE9 poss\xEDvel bifurcar: n\xE3o h\xE1 resposta do assistente com identificadores"
  },
  bangBash: {
    placeholder: "> Executar um comando bash...",
    commandPanel: "Painel de comandos",
    copyAriaLabel: "Copiar a sa\xEDda do comando mais recente",
    clearAriaLabel: "Limpar a sa\xEDda do bash",
    commandLabel: "{command}",
    statusLabel: "Estado: {status}",
    collapseOutput: "Recolher a sa\xEDda do comando",
    expandOutput: "Expandir a sa\xEDda do comando",
    running: "Executando...",
    copyFailed: "Falha ao copiar para a \xE1rea de transfer\xEAncia"
  }
};
var settings7 = {
  title: "Configura\xE7\xF5es do Claudian",
  tabs: {
    general: "Geral",
    claude: "Claude",
    codex: "Codex"
  },
  display: "Exibi\xE7\xE3o",
  conversations: "Conversas",
  content: "Conte\xFAdo",
  input: "Entrada",
  setup: "Configura\xE7\xE3o",
  models: "Modelos",
  experimental: "Experimental",
  userName: {
    name: "Como o Claudian deve cham\xE1-lo?",
    desc: "Seu nome para sauda\xE7\xF5es personalizadas (deixe vazio para sauda\xE7\xF5es gen\xE9ricas)"
  },
  excludedTags: {
    name: "Tags exclu\xEDdas",
    desc: "Notas com estas tags n\xE3o ser\xE3o carregadas automaticamente como contexto (uma por linha, sem #)"
  },
  mediaFolder: {
    name: "Pasta de m\xEDdia",
    desc: "Pasta contendo anexos/imagens. Quando notas usam ![[image.jpg]], Claude procurar\xE1 aqui. Deixe vazio para a raiz do reposit\xF3rio."
  },
  systemPrompt: {
    name: "Prompt de sistema personalizado",
    desc: "Instru\xE7\xF5es adicionais anexadas ao prompt de sistema padr\xE3o"
  },
  autoTitle: {
    name: "Gerar automaticamente t\xEDtulos de conversa",
    desc: "Gera automaticamente t\xEDtulos de conversa ap\xF3s a primeira mensagem do usu\xE1rio."
  },
  titleModel: {
    name: "Modelo de gera\xE7\xE3o de t\xEDtulo",
    desc: "Modelo usado para gerar automaticamente t\xEDtulos de conversa.",
    auto: "Autom\xE1tico (Haiku)"
  },
  navMappings: {
    name: "Mapeamentos de navega\xE7\xE3o estilo Vim",
    desc: 'Um mapeamento por linha. Formato: "map <tecla> <a\xE7\xE3o>" (a\xE7\xF5es: scrollUp, scrollDown, focusInput).'
  },
  hotkeys: "Atalhos",
  inlineEditHotkey: {
    name: "Edi\xE7\xE3o em linha",
    descWithKey: "Atalho atual: {hotkey}",
    descNoKey: "Nenhum atalho definido",
    btnChange: "Alterar",
    btnSet: "Definir"
  },
  openChatHotkey: {
    name: "Abrir chat",
    descWithKey: "Atalho atual: {hotkey}",
    descNoKey: "Nenhum atalho definido",
    btnChange: "Alterar",
    btnSet: "Definir"
  },
  newSessionHotkey: {
    name: "Nova sess\xE3o",
    descWithKey: "Atalho atual: {hotkey}",
    descNoKey: "Nenhum atalho definido",
    btnChange: "Alterar",
    btnSet: "Definir"
  },
  newTabHotkey: {
    name: "Nova aba",
    descWithKey: "Atalho atual: {hotkey}",
    descNoKey: "Nenhum atalho definido",
    btnChange: "Alterar",
    btnSet: "Definir"
  },
  closeTabHotkey: {
    name: "Fechar aba",
    descWithKey: "Atalho atual: {hotkey}",
    descNoKey: "Nenhum atalho definido",
    btnChange: "Alterar",
    btnSet: "Definir"
  },
  slashCommands: {
    name: "Comandos e habilidades",
    desc: "Gerencie comandos e habilidades a n\xEDvel de vault armazenados em .claude/commands/ e .claude/skills/. Acionados por /nome."
  },
  hiddenSlashCommands: {
    name: "Comandos e habilidades ocultos",
    desc: "Oculta comandos e habilidades espec\xEDficos do menu suspenso. \xDAtil para ocultar entradas do Claude Code que n\xE3o s\xE3o relevantes para o Claudian. Digite os nomes sem a barra inicial, um por linha.",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "Servidores MCP",
    desc: "Gerencie configura\xE7\xF5es de servidores MCP a n\xEDvel de vault armazenadas em .claude/mcp.json. Servidores com modo de salvamento de contexto exigem @mention para ativar."
  },
  plugins: {
    name: "Plugins do Claude Code",
    desc: "Gerencie plugins do Claude Code descobertos em ~/.claude/plugins. Plugins ativados s\xE3o armazenados por vault em .claude/settings.json."
  },
  subagents: {
    name: "Subagentes",
    desc: "Gerencie subagentes a n\xEDvel de vault armazenados em .claude/agents/. Cada arquivo Markdown define um agente personalizado.",
    noAgents: "Nenhum subagente configurado. Clique em + para criar um.",
    deleteConfirm: 'Excluir o subagente "{name}"?',
    saveFailed: "Falha ao salvar o subagente: {message}",
    refreshFailed: "Falha ao atualizar subagentes: {message}",
    deleteFailed: "Falha ao excluir o subagente: {message}",
    renameCleanupFailed: 'Aviso: n\xE3o foi poss\xEDvel remover o arquivo antigo de "{name}"',
    created: 'Subagente "{name}" criado',
    updated: 'Subagente "{name}" atualizado',
    deleted: 'Subagente "{name}" exclu\xEDdo',
    duplicateName: 'J\xE1 existe um agente chamado "{name}"',
    descriptionRequired: "A descri\xE7\xE3o \xE9 obrigat\xF3ria",
    promptRequired: "O prompt do sistema \xE9 obrigat\xF3rio",
    modal: {
      titleEdit: "Editar subagente",
      titleAdd: "Adicionar subagente",
      name: "Nome",
      nameDesc: "Use apenas letras min\xFAsculas, n\xFAmeros e h\xEDfens",
      namePlaceholder: "code-reviewer",
      description: "Descri\xE7\xE3o",
      descriptionDesc: "Breve descri\xE7\xE3o deste agente",
      descriptionPlaceholder: "Revisa c\xF3digo em busca de bugs e estilo",
      advancedOptions: "Op\xE7\xF5es avan\xE7adas",
      model: "Modelo",
      modelDesc: "Substituir o modelo deste agente",
      tools: "Ferramentas",
      toolsDesc: "Lista de ferramentas permitidas separadas por v\xEDrgula (vazio = todas)",
      disallowedTools: "Ferramentas n\xE3o permitidas",
      disallowedToolsDesc: "Lista de ferramentas a desativar separadas por v\xEDrgula",
      skills: "Habilidades",
      skillsDesc: "Lista de habilidades separadas por v\xEDrgula",
      prompt: "Prompt do sistema",
      promptDesc: "Instru\xE7\xF5es para o agente",
      promptPlaceholder: "Voc\xEA \xE9 um revisor de c\xF3digo. Analise o c\xF3digo fornecido para..."
    }
  },
  safety: "Seguran\xE7a",
  loadUserSettings: {
    name: "Carregar configura\xE7\xF5es do usu\xE1rio Claude",
    desc: "Carrega ~/.claude/settings.json. Quando habilitado, as regras de permiss\xE3o do usu\xE1rio podem ignorar o modo seguro."
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "Ambiente",
  customVariables: {
    name: "Vari\xE1veis personalizadas",
    desc: "Vari\xE1veis de ambiente para Claude SDK (formato KEY=VALUE, uma por linha). Prefixo export suportado."
  },
  envSnippets: {
    name: "Snippets",
    addBtn: "Adicionar snippet",
    noSnippets: "Nenhum snippet de ambiente salvo. Clique em + para salvar sua configura\xE7\xE3o atual.",
    nameRequired: "Por favor, insira um nome para o snippet",
    modal: {
      titleEdit: "Editar snippet",
      titleSave: "Salvar snippet",
      name: "Nome",
      namePlaceholder: "Um nome descritivo para esta configura\xE7\xE3o",
      description: "Descri\xE7\xE3o",
      descPlaceholder: "Descri\xE7\xE3o opcional",
      envVars: "Vari\xE1veis de ambiente",
      envVarsPlaceholder: "Formato KEY=VALUE, uma por linha (prefixo export suportado)",
      save: "Salvar",
      update: "Atualizar",
      cancel: "Cancelar"
    }
  },
  customContextLimits: {
    name: "Limites de contexto personalizados",
    desc: "Defina tamanhos de janela de contexto para seus modelos personalizados. Deixe vazio para usar o padr\xE3o (200k tokens).",
    invalid: "Formato inv\xE1lido. Use: 256k, 1m ou n\xFAmero exato (1000-10000000)."
  },
  enableOpus1M: {
    name: "Janela de contexto Opus 1M",
    desc: "Mostrar Opus 1M no seletor de modelos. Inclu\xEDdo nos planos Max, Team e Enterprise. Usu\xE1rios de API e Pro precisam de uso adicional."
  },
  enableSonnet1M: {
    name: "Janela de contexto Sonnet 1M",
    desc: "Mostrar Sonnet 1M no seletor de modelos. Requer uso adicional nos planos Max, Team e Enterprise. Usu\xE1rios de API e Pro precisam de uso adicional."
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "Habilitar extens\xE3o do Chrome",
    desc: "Permitir que o Claude interaja com o Chrome atrav\xE9s da extens\xE3o claude-in-chrome. Requer que a extens\xE3o esteja instalada. Requer rein\xEDcio de sess\xE3o."
  },
  enableBangBash: {
    name: "Ativar modo bash (!)",
    desc: "Digite ! com a entrada vazia para entrar no modo bash. Executa comandos diretamente via Node.js child_process. Requer reabrir a visualiza\xE7\xE3o.",
    validation: {
      noNode: "Node.js n\xE3o encontrado no PATH. Instale o Node.js ou verifique a configura\xE7\xE3o do PATH."
    }
  },
  maxTabs: {
    name: "M\xE1ximo de abas de chat",
    desc: "N\xFAmero m\xE1ximo de abas de chat simult\xE2neas (3-10). Cada aba usa uma sess\xE3o Claude separada.",
    warning: "Mais de 5 abas pode afetar o desempenho e o uso de mem\xF3ria."
  },
  tabBarPosition: {
    name: "Posi\xE7\xE3o da barra de abas",
    desc: "Escolha onde exibir os emblemas de abas e bot\xF5es de a\xE7\xE3o",
    input: "Acima da entrada (padr\xE3o)",
    header: "No cabe\xE7alho"
  },
  enableAutoScroll: {
    name: "Rolagem autom\xE1tica durante streaming",
    desc: "Rolar automaticamente para baixo enquanto o Claude transmite respostas. Desativar para ficar no topo e ler desde o in\xEDcio."
  },
  openInMainTab: {
    name: "Abrir na \xE1rea do editor principal",
    desc: "Abrir o painel de chat como uma aba principal na \xE1rea do editor central em vez da barra lateral direita"
  },
  cliPath: {
    name: "Caminho CLI Claude",
    desc: "Caminho personalizado para Claude Code CLI. Deixe vazio para detec\xE7\xE3o autom\xE1tica.",
    descWindows: "Para o instalador nativo, use claude.exe. Para instala\xE7\xF5es com npm/pnpm/yarn ou outros gerenciadores de pacotes, use o caminho cli.js (n\xE3o claude.cmd).",
    descUnix: 'Cole a sa\xEDda de "which claude" \u2014 funciona tanto para instala\xE7\xF5es nativas quanto npm/pnpm/yarn.',
    validation: {
      notExist: "Caminho n\xE3o existe",
      isDirectory: "Caminho \xE9 um diret\xF3rio, n\xE3o um arquivo"
    }
  },
  language: {
    name: "Idioma",
    desc: "Alterar o idioma de exibi\xE7\xE3o da interface do plugin"
  }
};
var pt_default = {
  common: common7,
  chat: chat7,
  settings: settings7
};

// src/i18n/locales/ru.json
var ru_exports = {};
__export(ru_exports, {
  chat: () => chat8,
  common: () => common8,
  default: () => ru_default,
  settings: () => settings8
});
var common8 = {
  save: "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C",
  cancel: "\u041E\u0442\u043C\u0435\u043D\u0430",
  delete: "\u0423\u0434\u0430\u043B\u0438\u0442\u044C",
  edit: "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C",
  add: "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C",
  remove: "\u0423\u0434\u0430\u043B\u0438\u0442\u044C",
  clear: "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C",
  clearAll: "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0432\u0441\u0451",
  loading: "\u0417\u0430\u0433\u0440\u0443\u0437\u043A\u0430",
  error: "\u041E\u0448\u0438\u0431\u043A\u0430",
  success: "\u0423\u0441\u043F\u0435\u0445",
  warning: "\u041F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435",
  confirm: "\u041F\u043E\u0434\u0442\u0432\u0435\u0440\u0434\u0438\u0442\u044C",
  settings: "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438",
  advanced: "\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E",
  enabled: "\u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E",
  disabled: "\u041E\u0442\u043A\u043B\u044E\u0447\u0435\u043D\u043E",
  platform: "\u041F\u043B\u0430\u0442\u0444\u043E\u0440\u043C\u0430",
  refresh: "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C",
  rewind: "\u041E\u0442\u043A\u0430\u0442\u0438\u0442\u044C"
};
var chat8 = {
  rewind: {
    confirmMessage: "\u041E\u0442\u043A\u0430\u0442\u0438\u0442\u044C \u0434\u043E \u044D\u0442\u043E\u0439 \u0442\u043E\u0447\u043A\u0438? \u0418\u0437\u043C\u0435\u043D\u0435\u043D\u0438\u044F \u0444\u0430\u0439\u043B\u043E\u0432 \u043F\u043E\u0441\u043B\u0435 \u044D\u0442\u043E\u0433\u043E \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u0431\u0443\u0434\u0443\u0442 \u043E\u0442\u043C\u0435\u043D\u0435\u043D\u044B. \u041E\u0442\u043A\u0430\u0442 \u043D\u0435 \u0437\u0430\u0442\u0440\u0430\u0433\u0438\u0432\u0430\u0435\u0442 \u0444\u0430\u0439\u043B\u044B, \u043E\u0442\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0435 \u0432\u0440\u0443\u0447\u043D\u0443\u044E \u0438\u043B\u0438 \u0447\u0435\u0440\u0435\u0437 bash.",
    confirmButton: "\u041E\u0442\u043A\u0430\u0442\u0438\u0442\u044C",
    ariaLabel: "\u041E\u0442\u043A\u0430\u0442\u0438\u0442\u044C \u0441\u044E\u0434\u0430",
    notice: "\u041E\u0442\u043A\u0430\u0447\u0435\u043D\u043E: \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043E \u0444\u0430\u0439\u043B\u043E\u0432 \u2014 {count}",
    noticeSaveFailed: "\u041E\u0442\u043A\u0430\u0442 \u0432\u044B\u043F\u043E\u043B\u043D\u0435\u043D: \u0432\u043E\u0441\u0441\u0442\u0430\u043D\u043E\u0432\u043B\u0435\u043D\u043E \u0444\u0430\u0439\u043B\u043E\u0432 \u2014 {count}, \u043D\u043E \u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0441\u043E\u0441\u0442\u043E\u044F\u043D\u0438\u0435: {error}",
    failed: "\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0442\u043A\u0430\u0442\u0430: {error}",
    cannot: "\u041D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u043E\u0442\u043A\u0430\u0442\u0438\u0442\u044C: {error}",
    unavailableStreaming: "\u041D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u043E\u0442\u043A\u0430\u0442\u0438\u0442\u044C \u0432\u043E \u0432\u0440\u0435\u043C\u044F \u043F\u043E\u0442\u043E\u043A\u043E\u0432\u043E\u0439 \u043F\u0435\u0440\u0435\u0434\u0430\u0447\u0438",
    unavailableNoUuid: "\u041D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u043E\u0442\u043A\u0430\u0442\u0438\u0442\u044C: \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u044E\u0442 \u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439"
  },
  fork: {
    ariaLabel: "\u041E\u0442\u0432\u0435\u0442\u0432\u0438\u0442\u044C \u0440\u0430\u0437\u0433\u043E\u0432\u043E\u0440",
    chooseTarget: "\u041E\u0442\u0432\u0435\u0442\u0432\u0438\u0442\u044C \u0440\u0430\u0437\u0433\u043E\u0432\u043E\u0440",
    targetNewTab: "\u041D\u043E\u0432\u0430\u044F \u0432\u043A\u043B\u0430\u0434\u043A\u0430",
    targetCurrentTab: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u0432\u043A\u043B\u0430\u0434\u043A\u0430",
    maxTabsReached: "\u041D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u043E\u0442\u0432\u0435\u0442\u0432\u0438\u0442\u044C: \u0434\u043E\u0441\u0442\u0438\u0433\u043D\u0443\u0442 \u043C\u0430\u043A\u0441\u0438\u043C\u0443\u043C {count} \u0432\u043A\u043B\u0430\u0434\u043E\u043A",
    notice: "\u041E\u0442\u0432\u0435\u0442\u0432\u043B\u0435\u043D\u043E \u0432 \u043D\u043E\u0432\u0443\u044E \u0432\u043A\u043B\u0430\u0434\u043A\u0443",
    noticeCurrentTab: "\u041E\u0442\u0432\u0435\u0442\u0432\u043B\u0435\u043D\u043E \u0432 \u0442\u0435\u043A\u0443\u0449\u0435\u0439 \u0432\u043A\u043B\u0430\u0434\u043A\u0435",
    failed: "\u041E\u0448\u0438\u0431\u043A\u0430 \u043E\u0442\u0432\u0435\u0442\u0432\u043B\u0435\u043D\u0438\u044F: {error}",
    unavailableStreaming: "\u041D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u043E\u0442\u0432\u0435\u0442\u0432\u0438\u0442\u044C \u0432\u043E \u0432\u0440\u0435\u043C\u044F \u043F\u043E\u0442\u043E\u043A\u043E\u0432\u043E\u0439 \u043F\u0435\u0440\u0435\u0434\u0430\u0447\u0438",
    unavailableNoUuid: "\u041D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u043E\u0442\u0432\u0435\u0442\u0432\u0438\u0442\u044C: \u043E\u0442\u0441\u0443\u0442\u0441\u0442\u0432\u0443\u044E\u0442 \u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u044B \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439",
    unavailableNoResponse: "\u041D\u0435\u0432\u043E\u0437\u043C\u043E\u0436\u043D\u043E \u043E\u0442\u0432\u0435\u0442\u0432\u0438\u0442\u044C: \u043D\u0435\u0442 \u043E\u0442\u0432\u0435\u0442\u0430 \u0434\u043B\u044F \u043E\u0442\u0432\u0435\u0442\u0432\u043B\u0435\u043D\u0438\u044F",
    errorMessageNotFound: "\u0421\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0435 \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D\u043E",
    errorNoSession: "\u0418\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440 \u0441\u0435\u0441\u0441\u0438\u0438 \u043D\u0435\u0434\u043E\u0441\u0442\u0443\u043F\u0435\u043D",
    errorNoActiveTab: "\u041D\u0435\u0442 \u0430\u043A\u0442\u0438\u0432\u043D\u043E\u0439 \u0432\u043A\u043B\u0430\u0434\u043A\u0438",
    commandNoMessages: "\u041D\u0435\u043B\u044C\u0437\u044F \u0444\u043E\u0440\u043A\u043D\u0443\u0442\u044C: \u0432 \u0434\u0438\u0430\u043B\u043E\u0433\u0435 \u043D\u0435\u0442 \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u0439",
    commandNoAssistantUuid: "\u041D\u0435\u043B\u044C\u0437\u044F \u0444\u043E\u0440\u043A\u043D\u0443\u0442\u044C: \u043D\u0435\u0442 \u043E\u0442\u0432\u0435\u0442\u0430 \u0430\u0441\u0441\u0438\u0441\u0442\u0435\u043D\u0442\u0430 \u0441 \u0438\u0434\u0435\u043D\u0442\u0438\u0444\u0438\u043A\u0430\u0442\u043E\u0440\u0430\u043C\u0438"
  },
  bangBash: {
    placeholder: "> \u0412\u044B\u043F\u043E\u043B\u043D\u0438\u0442\u044C \u043A\u043E\u043C\u0430\u043D\u0434\u0443 bash...",
    commandPanel: "\u041F\u0430\u043D\u0435\u043B\u044C \u043A\u043E\u043C\u0430\u043D\u0434",
    copyAriaLabel: "\u0421\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0432\u044B\u0432\u043E\u0434 \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u0435\u0439 \u043A\u043E\u043C\u0430\u043D\u0434\u044B",
    clearAriaLabel: "\u041E\u0447\u0438\u0441\u0442\u0438\u0442\u044C \u0432\u044B\u0432\u043E\u0434 bash",
    commandLabel: "{command}",
    statusLabel: "\u0421\u0442\u0430\u0442\u0443\u0441: {status}",
    collapseOutput: "\u0421\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u044B\u0432\u043E\u0434 \u043A\u043E\u043C\u0430\u043D\u0434\u044B",
    expandOutput: "\u0420\u0430\u0437\u0432\u0435\u0440\u043D\u0443\u0442\u044C \u0432\u044B\u0432\u043E\u0434 \u043A\u043E\u043C\u0430\u043D\u0434\u044B",
    running: "\u0412\u044B\u043F\u043E\u043B\u043D\u044F\u0435\u0442\u0441\u044F...",
    copyFailed: "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043A\u043E\u043F\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0432 \u0431\u0443\u0444\u0435\u0440 \u043E\u0431\u043C\u0435\u043D\u0430"
  }
};
var settings8 = {
  title: "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 Claudian",
  tabs: {
    general: "\u041E\u0431\u0449\u0438\u0435",
    claude: "Claude",
    codex: "Codex"
  },
  display: "\u041E\u0442\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u0435",
  conversations: "\u0420\u0430\u0437\u0433\u043E\u0432\u043E\u0440\u044B",
  content: "\u0421\u043E\u0434\u0435\u0440\u0436\u0430\u043D\u0438\u0435",
  input: "\u0412\u0432\u043E\u0434",
  setup: "\u041D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0430",
  models: "\u041C\u043E\u0434\u0435\u043B\u0438",
  experimental: "\u042D\u043A\u0441\u043F\u0435\u0440\u0438\u043C\u0435\u043D\u0442\u0430\u043B\u044C\u043D\u043E\u0435",
  userName: {
    name: "\u041A\u0430\u043A Claudian \u0434\u043E\u043B\u0436\u0435\u043D \u043E\u0431\u0440\u0430\u0449\u0430\u0442\u044C\u0441\u044F \u043A \u0432\u0430\u043C?",
    desc: "\u0412\u0430\u0448\u0435 \u0438\u043C\u044F \u0434\u043B\u044F \u043F\u0435\u0440\u0441\u043E\u043D\u0430\u043B\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u044B\u0445 \u043F\u0440\u0438\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0439 (\u043E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u043F\u0443\u0441\u0442\u044B\u043C \u0434\u043B\u044F \u043E\u0431\u0449\u0438\u0445 \u043F\u0440\u0438\u0432\u0435\u0442\u0441\u0442\u0432\u0438\u0439)"
  },
  excludedTags: {
    name: "\u0418\u0441\u043A\u043B\u044E\u0447\u0435\u043D\u043D\u044B\u0435 \u0442\u0435\u0433\u0438",
    desc: "\u0417\u0430\u043C\u0435\u0442\u043A\u0438 \u0441 \u044D\u0442\u0438\u043C\u0438 \u0442\u0435\u0433\u0430\u043C\u0438 \u043D\u0435 \u0431\u0443\u0434\u0443\u0442 \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u0437\u0430\u0433\u0440\u0443\u0436\u0430\u0442\u044C\u0441\u044F \u043A\u0430\u043A \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442 (\u043F\u043E \u043E\u0434\u043D\u043E\u043C\u0443 \u0432 \u0441\u0442\u0440\u043E\u043A\u0435, \u0431\u0435\u0437 #)"
  },
  mediaFolder: {
    name: "\u041F\u0430\u043F\u043A\u0430 \u043C\u0435\u0434\u0438\u0430\u0444\u0430\u0439\u043B\u043E\u0432",
    desc: "\u041F\u0430\u043F\u043A\u0430 \u0441 \u0432\u043B\u043E\u0436\u0435\u043D\u0438\u044F\u043C\u0438/\u0438\u0437\u043E\u0431\u0440\u0430\u0436\u0435\u043D\u0438\u044F\u043C\u0438. \u041A\u043E\u0433\u0434\u0430 \u0437\u0430\u043C\u0435\u0442\u043A\u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u044E\u0442 ![[image.jpg]], Claude \u0431\u0443\u0434\u0435\u0442 \u0438\u0441\u043A\u0430\u0442\u044C \u0437\u0434\u0435\u0441\u044C. \u041E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u043F\u0443\u0441\u0442\u044B\u043C \u0434\u043B\u044F \u043A\u043E\u0440\u043D\u044F \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430."
  },
  systemPrompt: {
    name: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0439 \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442",
    desc: "\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u0438, \u0434\u043E\u0431\u0430\u0432\u043B\u044F\u0435\u043C\u044B\u0435 \u043A \u0441\u0438\u0441\u0442\u0435\u043C\u043D\u043E\u043C\u0443 \u043F\u0440\u043E\u043C\u043F\u0442\u0443 \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E"
  },
  autoTitle: {
    name: "\u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0438 \u0431\u0435\u0441\u0435\u0434",
    desc: "\u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u0433\u0435\u043D\u0435\u0440\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0438 \u0431\u0435\u0441\u0435\u0434 \u043F\u043E\u0441\u043B\u0435 \u043F\u0435\u0440\u0432\u043E\u0433\u043E \u0441\u043E\u043E\u0431\u0449\u0435\u043D\u0438\u044F \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F."
  },
  titleModel: {
    name: "\u041C\u043E\u0434\u0435\u043B\u044C \u0433\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u0438 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432",
    desc: "\u041C\u043E\u0434\u0435\u043B\u044C, \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u043C\u0430\u044F \u0434\u043B\u044F \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0439 \u0433\u0435\u043D\u0435\u0440\u0430\u0446\u0438\u0438 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u043E\u0432 \u0431\u0435\u0441\u0435\u0434.",
    auto: "\u0410\u0432\u0442\u043E (Haiku)"
  },
  navMappings: {
    name: "\u0421\u043E\u043F\u043E\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u044F \u043D\u0430\u0432\u0438\u0433\u0430\u0446\u0438\u0438 \u0432 \u0441\u0442\u0438\u043B\u0435 Vim",
    desc: '\u041F\u043E \u043E\u0434\u043D\u043E\u043C\u0443 \u0441\u043E\u043F\u043E\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u044E \u0432 \u0441\u0442\u0440\u043E\u043A\u0435. \u0424\u043E\u0440\u043C\u0430\u0442: "map <\u043A\u043B\u044E\u0447> <\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0435>" (\u0434\u0435\u0439\u0441\u0442\u0432\u0438\u044F: scrollUp, scrollDown, focusInput).'
  },
  hotkeys: "\u0413\u043E\u0440\u044F\u0447\u0438\u0435 \u043A\u043B\u0430\u0432\u0438\u0448\u0438",
  inlineEditHotkey: {
    name: "\u0418\u043D\u043B\u0430\u0439\u043D-\u0440\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u043D\u0438\u0435",
    descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}",
    descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430",
    btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C",
    btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C"
  },
  openChatHotkey: {
    name: "\u041E\u0442\u043A\u0440\u044B\u0442\u044C \u0447\u0430\u0442",
    descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}",
    descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430",
    btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C",
    btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C"
  },
  newSessionHotkey: {
    name: "\u041D\u043E\u0432\u0430\u044F \u0441\u0435\u0441\u0441\u0438\u044F",
    descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}",
    descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430",
    btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C",
    btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C"
  },
  newTabHotkey: {
    name: "\u041D\u043E\u0432\u0430\u044F \u0432\u043A\u043B\u0430\u0434\u043A\u0430",
    descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}",
    descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430",
    btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C",
    btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C"
  },
  closeTabHotkey: {
    name: "\u0417\u0430\u043A\u0440\u044B\u0442\u044C \u0432\u043A\u043B\u0430\u0434\u043A\u0443",
    descWithKey: "\u0422\u0435\u043A\u0443\u0449\u0430\u044F \u043A\u043B\u0430\u0432\u0438\u0448\u0430: {hotkey}",
    descNoKey: "\u041A\u043B\u0430\u0432\u0438\u0448\u0430 \u043D\u0435 \u043D\u0430\u0437\u043D\u0430\u0447\u0435\u043D\u0430",
    btnChange: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C",
    btnSet: "\u041D\u0430\u0437\u043D\u0430\u0447\u0438\u0442\u044C"
  },
  slashCommands: {
    name: "\u041A\u043E\u043C\u0430\u043D\u0434\u044B \u0438 \u043D\u0430\u0432\u044B\u043A\u0438",
    desc: "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u0430\u043C\u0438 \u0438 \u043D\u0430\u0432\u044B\u043A\u0430\u043C\u0438 \u043D\u0430 \u0443\u0440\u043E\u0432\u043D\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430, \u0440\u0430\u0441\u043F\u043E\u043B\u043E\u0436\u0435\u043D\u043D\u044B\u043C\u0438 \u0432 .claude/commands/ \u0438 .claude/skills/. \u0417\u0430\u043F\u0443\u0441\u043A\u0430\u044E\u0442\u0441\u044F \u0447\u0435\u0440\u0435\u0437 /\u0438\u043C\u044F."
  },
  hiddenSlashCommands: {
    name: "\u0421\u043A\u0440\u044B\u0442\u044B\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0438 \u043D\u0430\u0432\u044B\u043A\u0438",
    desc: "\u0421\u043A\u0440\u044B\u0442\u044C \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0451\u043D\u043D\u044B\u0435 \u043A\u043E\u043C\u0430\u043D\u0434\u044B \u0438 \u043D\u0430\u0432\u044B\u043A\u0438 \u0438\u0437 \u0432\u044B\u043F\u0430\u0434\u0430\u044E\u0449\u0435\u0433\u043E \u0441\u043F\u0438\u0441\u043A\u0430. \u041F\u043E\u043B\u0435\u0437\u043D\u043E \u0434\u043B\u044F \u0441\u043A\u0440\u044B\u0442\u0438\u044F \u0437\u0430\u043F\u0438\u0441\u0435\u0439 Claude Code, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u043D\u0435 \u0430\u043A\u0442\u0443\u0430\u043B\u044C\u043D\u044B \u0434\u043B\u044F Claudian. \u0412\u0432\u043E\u0434\u0438\u0442\u0435 \u0438\u043C\u0435\u043D\u0430 \u0431\u0435\u0437 \u043D\u0430\u0447\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0441\u043B\u044D\u0448\u0430, \u043F\u043E \u043E\u0434\u043D\u043E\u043C\u0443 \u043D\u0430 \u0441\u0442\u0440\u043E\u043A\u0443.",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "MCP \u0441\u0435\u0440\u0432\u0435\u0440\u044B",
    desc: "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044F\u043C\u0438 MCP-\u0441\u0435\u0440\u0432\u0435\u0440\u043E\u0432 \u043D\u0430 \u0443\u0440\u043E\u0432\u043D\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 \u0432 .claude/mcp.json. \u0421\u0435\u0440\u0432\u0435\u0440\u044B \u0441 \u0440\u0435\u0436\u0438\u043C\u043E\u043C \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u0438\u044F \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u0442\u0440\u0435\u0431\u0443\u044E\u0442 @mention \u0434\u043B\u044F \u0430\u043A\u0442\u0438\u0432\u0430\u0446\u0438\u0438."
  },
  plugins: {
    name: "\u041F\u043B\u0430\u0433\u0438\u043D\u044B Claude Code",
    desc: "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u043F\u043B\u0430\u0433\u0438\u043D\u0430\u043C\u0438 Claude Code \u0438\u0437 ~/.claude/plugins. \u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043D\u044B\u0435 \u043F\u043B\u0430\u0433\u0438\u043D\u044B \u0441\u043E\u0445\u0440\u0430\u043D\u044F\u044E\u0442\u0441\u044F \u0434\u043B\u044F \u043A\u0430\u0436\u0434\u043E\u0433\u043E \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 \u0432 .claude/settings.json."
  },
  subagents: {
    name: "\u0421\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u044B",
    desc: "\u0423\u043F\u0440\u0430\u0432\u043B\u0435\u043D\u0438\u0435 \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0430\u043C\u0438 \u043D\u0430 \u0443\u0440\u043E\u0432\u043D\u0435 \u0445\u0440\u0430\u043D\u0438\u043B\u0438\u0449\u0430 \u0432 .claude/agents/. \u041A\u0430\u0436\u0434\u044B\u0439 Markdown-\u0444\u0430\u0439\u043B \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u044F\u0435\u0442 \u043E\u0434\u043D\u043E\u0433\u043E \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u043E\u0433\u043E \u0430\u0433\u0435\u043D\u0442\u0430.",
    noAgents: "\u0421\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u044B \u043D\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0435\u043D\u044B. \u041D\u0430\u0436\u043C\u0438\u0442\u0435 +, \u0447\u0442\u043E\u0431\u044B \u0441\u043E\u0437\u0434\u0430\u0442\u044C \u043E\u0434\u043D\u043E\u0433\u043E.",
    deleteConfirm: '\u0423\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0430 "{name}"?',
    saveFailed: "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0430: {message}",
    refreshFailed: "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0431\u043D\u043E\u0432\u0438\u0442\u044C \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u043E\u0432: {message}",
    deleteFailed: "\u041D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0430: {message}",
    renameCleanupFailed: '\u041F\u0440\u0435\u0434\u0443\u043F\u0440\u0435\u0436\u0434\u0435\u043D\u0438\u0435: \u043D\u0435 \u0443\u0434\u0430\u043B\u043E\u0441\u044C \u0443\u0434\u0430\u043B\u0438\u0442\u044C \u0441\u0442\u0430\u0440\u044B\u0439 \u0444\u0430\u0439\u043B \u0434\u043B\u044F "{name}"',
    created: '\u0421\u0443\u0431\u0430\u0433\u0435\u043D\u0442 "{name}" \u0441\u043E\u0437\u0434\u0430\u043D',
    updated: '\u0421\u0443\u0431\u0430\u0433\u0435\u043D\u0442 "{name}" \u043E\u0431\u043D\u043E\u0432\u043B\u0451\u043D',
    deleted: '\u0421\u0443\u0431\u0430\u0433\u0435\u043D\u0442 "{name}" \u0443\u0434\u0430\u043B\u0451\u043D',
    duplicateName: '\u0410\u0433\u0435\u043D\u0442 \u0441 \u0438\u043C\u0435\u043D\u0435\u043C "{name}" \u0443\u0436\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442',
    descriptionRequired: "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 \u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u044C\u043D\u043E",
    promptRequired: "\u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442 \u043E\u0431\u044F\u0437\u0430\u0442\u0435\u043B\u0435\u043D",
    modal: {
      titleEdit: "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0430",
      titleAdd: "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u0443\u0431\u0430\u0433\u0435\u043D\u0442\u0430",
      name: "\u0418\u043C\u044F",
      nameDesc: "\u0422\u043E\u043B\u044C\u043A\u043E \u0441\u0442\u0440\u043E\u0447\u043D\u044B\u0435 \u0431\u0443\u043A\u0432\u044B, \u0446\u0438\u0444\u0440\u044B \u0438 \u0434\u0435\u0444\u0438\u0441\u044B",
      namePlaceholder: "code-reviewer",
      description: "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435",
      descriptionDesc: "\u041A\u0440\u0430\u0442\u043A\u043E\u0435 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435 \u044D\u0442\u043E\u0433\u043E \u0430\u0433\u0435\u043D\u0442\u0430",
      descriptionPlaceholder: "\u041F\u0440\u043E\u0432\u0435\u0440\u044F\u0435\u0442 \u043A\u043E\u0434 \u043D\u0430 \u043E\u0448\u0438\u0431\u043A\u0438 \u0438 \u0441\u0442\u0438\u043B\u044C",
      advancedOptions: "\u0414\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u044B\u0435 \u043F\u0430\u0440\u0430\u043C\u0435\u0442\u0440\u044B",
      model: "\u041C\u043E\u0434\u0435\u043B\u044C",
      modelDesc: "\u041F\u0435\u0440\u0435\u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u0435 \u043C\u043E\u0434\u0435\u043B\u0438 \u0434\u043B\u044F \u044D\u0442\u043E\u0433\u043E \u0430\u0433\u0435\u043D\u0442\u0430",
      tools: "\u0418\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B",
      toolsDesc: "\u0421\u043F\u0438\u0441\u043E\u043A \u0440\u0430\u0437\u0440\u0435\u0448\u0451\u043D\u043D\u044B\u0445 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432 \u0447\u0435\u0440\u0435\u0437 \u0437\u0430\u043F\u044F\u0442\u0443\u044E (\u043F\u0443\u0441\u0442\u043E = \u0432\u0441\u0435)",
      disallowedTools: "\u0417\u0430\u043F\u0440\u0435\u0449\u0451\u043D\u043D\u044B\u0435 \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u044B",
      disallowedToolsDesc: "\u0421\u043F\u0438\u0441\u043E\u043A \u0438\u043D\u0441\u0442\u0440\u0443\u043C\u0435\u043D\u0442\u043E\u0432, \u043A\u043E\u0442\u043E\u0440\u044B\u0435 \u043D\u0443\u0436\u043D\u043E \u0437\u0430\u043F\u0440\u0435\u0442\u0438\u0442\u044C, \u0447\u0435\u0440\u0435\u0437 \u0437\u0430\u043F\u044F\u0442\u0443\u044E",
      skills: "\u041D\u0430\u0432\u044B\u043A\u0438",
      skillsDesc: "\u0421\u043F\u0438\u0441\u043E\u043A \u043D\u0430\u0432\u044B\u043A\u043E\u0432 \u0447\u0435\u0440\u0435\u0437 \u0437\u0430\u043F\u044F\u0442\u0443\u044E",
      prompt: "\u0421\u0438\u0441\u0442\u0435\u043C\u043D\u044B\u0439 \u043F\u0440\u043E\u043C\u043F\u0442",
      promptDesc: "\u0418\u043D\u0441\u0442\u0440\u0443\u043A\u0446\u0438\u0438 \u0434\u043B\u044F \u0430\u0433\u0435\u043D\u0442\u0430",
      promptPlaceholder: "\u0412\u044B \u0441\u043F\u0435\u0446\u0438\u0430\u043B\u0438\u0441\u0442 \u043F\u043E \u043F\u0440\u043E\u0432\u0435\u0440\u043A\u0435 \u043A\u043E\u0434\u0430. \u041F\u0440\u043E\u0430\u043D\u0430\u043B\u0438\u0437\u0438\u0440\u0443\u0439\u0442\u0435 \u043F\u0440\u0435\u0434\u043E\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u043D\u044B\u0439 \u043A\u043E\u0434 \u043D\u0430 \u043F\u0440\u0435\u0434\u043C\u0435\u0442..."
    }
  },
  safety: "\u0411\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u043E\u0441\u0442\u044C",
  loadUserSettings: {
    name: "\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0442\u044C \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0438 Claude",
    desc: "\u0417\u0430\u0433\u0440\u0443\u0436\u0430\u0435\u0442 ~/.claude/settings.json. \u041F\u0440\u0438 \u0432\u043A\u043B\u044E\u0447\u0435\u043D\u0438\u0438 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043F\u0440\u0430\u0432\u0438\u043B\u0430 \u0440\u0430\u0437\u0440\u0435\u0448\u0435\u043D\u0438\u0439 Claude Code \u043C\u043E\u0433\u0443\u0442 \u043E\u0431\u0445\u043E\u0434\u0438\u0442\u044C \u0431\u0435\u0437\u043E\u043F\u0430\u0441\u043D\u044B\u0439 \u0440\u0435\u0436\u0438\u043C."
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "\u041E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u0435",
  customVariables: {
    name: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0435",
    desc: "\u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0435 \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F \u0434\u043B\u044F Claude SDK (\u0444\u043E\u0440\u043C\u0430\u0442 KEY=VALUE, \u043F\u043E \u043E\u0434\u043D\u043E\u0439 \u0432 \u0441\u0442\u0440\u043E\u043A\u0435). \u041F\u0440\u0435\u0444\u0438\u043A\u0441 export \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F."
  },
  envSnippets: {
    name: "\u0421\u043D\u0438\u043F\u043F\u0435\u0442\u044B",
    addBtn: "\u0414\u043E\u0431\u0430\u0432\u0438\u0442\u044C \u0441\u043D\u0438\u043F\u043F\u0435\u0442",
    noSnippets: "\u041D\u0435\u0442 \u0441\u043E\u0445\u0440\u0430\u043D\u0435\u043D\u043D\u044B\u0445 \u0441\u043D\u0438\u043F\u043F\u0435\u0442\u043E\u0432 \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F. \u041D\u0430\u0436\u043C\u0438\u0442\u0435 +, \u0447\u0442\u043E\u0431\u044B \u0441\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0442\u0435\u043A\u0443\u0449\u0443\u044E \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u044E.",
    nameRequired: "\u041F\u043E\u0436\u0430\u043B\u0443\u0439\u0441\u0442\u0430, \u0432\u0432\u0435\u0434\u0438\u0442\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0441\u043D\u0438\u043F\u043F\u0435\u0442\u0430",
    modal: {
      titleEdit: "\u0420\u0435\u0434\u0430\u043A\u0442\u0438\u0440\u043E\u0432\u0430\u0442\u044C \u0441\u043D\u0438\u043F\u043F\u0435\u0442",
      titleSave: "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C \u0441\u043D\u0438\u043F\u043F\u0435\u0442",
      name: "\u0418\u043C\u044F",
      namePlaceholder: "\u041E\u043F\u0438\u0441\u0430\u0442\u0435\u043B\u044C\u043D\u043E\u0435 \u043D\u0430\u0437\u0432\u0430\u043D\u0438\u0435 \u0434\u043B\u044F \u044D\u0442\u043E\u0439 \u043A\u043E\u043D\u0444\u0438\u0433\u0443\u0440\u0430\u0446\u0438\u0438",
      description: "\u041E\u043F\u0438\u0441\u0430\u043D\u0438\u0435",
      descPlaceholder: "\u041E\u043F\u0446\u0438\u043E\u043D\u0430\u043B\u044C\u043D\u043E\u0435 \u043E\u043F\u0438\u0441\u0430\u043D\u0438\u0435",
      envVars: "\u041F\u0435\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0435 \u043E\u043A\u0440\u0443\u0436\u0435\u043D\u0438\u044F",
      envVarsPlaceholder: "\u0424\u043E\u0440\u043C\u0430\u0442 KEY=VALUE, \u043F\u043E \u043E\u0434\u043D\u043E\u0439 \u0432 \u0441\u0442\u0440\u043E\u043A\u0435 (\u043F\u0440\u0435\u0444\u0438\u043A\u0441 export \u043F\u043E\u0434\u0434\u0435\u0440\u0436\u0438\u0432\u0430\u0435\u0442\u0441\u044F)",
      save: "\u0421\u043E\u0445\u0440\u0430\u043D\u0438\u0442\u044C",
      update: "\u041E\u0431\u043D\u043E\u0432\u0438\u0442\u044C",
      cancel: "\u041E\u0442\u043C\u0435\u043D\u0430"
    }
  },
  customContextLimits: {
    name: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0435 \u043B\u0438\u043C\u0438\u0442\u044B \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430",
    desc: "\u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 \u0440\u0430\u0437\u043C\u0435\u0440\u044B \u043E\u043A\u043D\u0430 \u043A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u0430 \u0434\u043B\u044F \u0432\u0430\u0448\u0438\u0445 \u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0445 \u043C\u043E\u0434\u0435\u043B\u0435\u0439. \u041E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u043F\u0443\u0441\u0442\u044B\u043C \u0434\u043B\u044F \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u044F \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F \u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E (200k \u0442\u043E\u043A\u0435\u043D\u043E\u0432).",
    invalid: "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0444\u043E\u0440\u043C\u0430\u0442. \u0418\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435: 256k, 1m \u0438\u043B\u0438 \u0442\u043E\u0447\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E (1000-10000000)."
  },
  enableOpus1M: {
    name: "\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u043D\u043E\u0435 \u043E\u043A\u043D\u043E Opus 1M",
    desc: "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C Opus 1M \u0432 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440\u0435 \u043C\u043E\u0434\u0435\u043B\u0435\u0439. \u0412\u043A\u043B\u044E\u0447\u0435\u043D\u043E \u0432 \u043F\u043B\u0430\u043D\u044B Max, Team \u0438 Enterprise. \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F\u043C API \u0438 Pro \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435."
  },
  enableSonnet1M: {
    name: "\u041A\u043E\u043D\u0442\u0435\u043A\u0441\u0442\u043D\u043E\u0435 \u043E\u043A\u043D\u043E Sonnet 1M",
    desc: "\u041F\u043E\u043A\u0430\u0437\u0430\u0442\u044C Sonnet 1M \u0432 \u0441\u0435\u043B\u0435\u043A\u0442\u043E\u0440\u0435 \u043C\u043E\u0434\u0435\u043B\u0435\u0439. \u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u0432 \u043F\u043B\u0430\u043D\u0430\u0445 Max, Team \u0438 Enterprise. \u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044F\u043C API \u0438 Pro \u0442\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u0434\u043E\u043F\u043E\u043B\u043D\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0435 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435."
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 Chrome",
    desc: "\u0420\u0430\u0437\u0440\u0435\u0448\u0438\u0442\u044C Claude \u0432\u0437\u0430\u0438\u043C\u043E\u0434\u0435\u0439\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0441 Chrome \u0447\u0435\u0440\u0435\u0437 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u0435 claude-in-chrome. \u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u0440\u0430\u0441\u0448\u0438\u0440\u0435\u043D\u0438\u044F. \u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u0435\u0440\u0435\u0437\u0430\u043F\u0443\u0441\u043A \u0441\u0435\u0441\u0441\u0438\u0438."
  },
  enableBangBash: {
    name: "\u0412\u043A\u043B\u044E\u0447\u0438\u0442\u044C \u0440\u0435\u0436\u0438\u043C bash (!)",
    desc: "\u0412\u0432\u0435\u0434\u0438\u0442\u0435 ! \u0432 \u043F\u0443\u0441\u0442\u043E\u043C \u043F\u043E\u043B\u0435 \u0432\u0432\u043E\u0434\u0430, \u0447\u0442\u043E\u0431\u044B \u043F\u0435\u0440\u0435\u0439\u0442\u0438 \u0432 \u0440\u0435\u0436\u0438\u043C bash. \u041A\u043E\u043C\u0430\u043D\u0434\u044B \u0432\u044B\u043F\u043E\u043B\u043D\u044F\u044E\u0442\u0441\u044F \u043D\u0430\u043F\u0440\u044F\u043C\u0443\u044E \u0447\u0435\u0440\u0435\u0437 Node.js child_process. \u0422\u0440\u0435\u0431\u0443\u0435\u0442\u0441\u044F \u043F\u043E\u0432\u0442\u043E\u0440\u043D\u043E \u043E\u0442\u043A\u0440\u044B\u0442\u044C \u043F\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043B\u0435\u043D\u0438\u0435.",
    validation: {
      noNode: "Node.js \u043D\u0435 \u043D\u0430\u0439\u0434\u0435\u043D \u0432 PATH. \u0423\u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0435 Node.js \u0438\u043B\u0438 \u043F\u0440\u043E\u0432\u0435\u0440\u044C\u0442\u0435 \u043D\u0430\u0441\u0442\u0440\u043E\u0439\u043A\u0443 PATH."
    }
  },
  maxTabs: {
    name: "\u041C\u0430\u043A\u0441\u0438\u043C\u0443\u043C \u0432\u043A\u043B\u0430\u0434\u043E\u043A \u0447\u0430\u0442\u0430",
    desc: "\u041C\u0430\u043A\u0441\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0435 \u043A\u043E\u043B\u0438\u0447\u0435\u0441\u0442\u0432\u043E \u043E\u0434\u043D\u043E\u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0445 \u0432\u043A\u043B\u0430\u0434\u043E\u043A \u0447\u0430\u0442\u0430 (3-10). \u041A\u0430\u0436\u0434\u0430\u044F \u0432\u043A\u043B\u0430\u0434\u043A\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0435\u0442 \u043E\u0442\u0434\u0435\u043B\u044C\u043D\u0443\u044E \u0441\u0435\u0441\u0441\u0438\u044E Claude.",
    warning: "\u0411\u043E\u043B\u0435\u0435 5 \u0432\u043A\u043B\u0430\u0434\u043E\u043A \u043C\u043E\u0436\u0435\u0442 \u043F\u043E\u0432\u043B\u0438\u044F\u0442\u044C \u043D\u0430 \u043F\u0440\u043E\u0438\u0437\u0432\u043E\u0434\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C \u0438 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u043D\u0438\u0435 \u043F\u0430\u043C\u044F\u0442\u0438."
  },
  tabBarPosition: {
    name: "\u041F\u043E\u043B\u043E\u0436\u0435\u043D\u0438\u0435 \u043F\u0430\u043D\u0435\u043B\u0438 \u0432\u043A\u043B\u0430\u0434\u043E\u043A",
    desc: "\u0412\u044B\u0431\u0435\u0440\u0438\u0442\u0435, \u0433\u0434\u0435 \u043E\u0442\u043E\u0431\u0440\u0430\u0436\u0430\u0442\u044C \u0437\u043D\u0430\u0447\u043A\u0438 \u0432\u043A\u043B\u0430\u0434\u043E\u043A \u0438 \u043A\u043D\u043E\u043F\u043A\u0438 \u0434\u0435\u0439\u0441\u0442\u0432\u0438\u0439",
    input: "\u041D\u0430\u0434 \u043F\u043E\u043B\u0435\u043C \u0432\u0432\u043E\u0434\u0430 (\u043F\u043E \u0443\u043C\u043E\u043B\u0447\u0430\u043D\u0438\u044E)",
    header: "\u0412 \u0437\u0430\u0433\u043E\u043B\u043E\u0432\u043A\u0435"
  },
  enableAutoScroll: {
    name: "\u0410\u0432\u0442\u043E\u043F\u0440\u043E\u043A\u0440\u0443\u0442\u043A\u0430 \u0432\u043E \u0432\u0440\u0435\u043C\u044F \u043F\u043E\u0442\u043E\u043A\u043E\u0432\u043E\u0439 \u043F\u0435\u0440\u0435\u0434\u0430\u0447\u0438",
    desc: "\u0410\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u0438 \u043F\u0440\u043E\u043A\u0440\u0443\u0447\u0438\u0432\u0430\u0442\u044C \u0432\u043D\u0438\u0437, \u043F\u043E\u043A\u0430 Claude \u043F\u0435\u0440\u0435\u0434\u0430\u0435\u0442 \u043E\u0442\u0432\u0435\u0442\u044B. \u041E\u0442\u043A\u043B\u044E\u0447\u0438\u0442\u0435, \u0447\u0442\u043E\u0431\u044B \u043E\u0441\u0442\u0430\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430\u0432\u0435\u0440\u0445\u0443 \u0438 \u0447\u0438\u0442\u0430\u0442\u044C \u0441 \u043D\u0430\u0447\u0430\u043B\u0430."
  },
  openInMainTab: {
    name: "\u041E\u0442\u043A\u0440\u044B\u0432\u0430\u0442\u044C \u0432 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0430",
    desc: "\u041E\u0442\u043A\u0440\u044B\u0432\u0430\u0442\u044C \u043F\u0430\u043D\u0435\u043B\u044C \u0447\u0430\u0442\u0430 \u0432 \u0432\u0438\u0434\u0435 \u043E\u0441\u043D\u043E\u0432\u043D\u043E\u0439 \u0432\u043A\u043B\u0430\u0434\u043A\u0438 \u0432 \u0446\u0435\u043D\u0442\u0440\u0430\u043B\u044C\u043D\u043E\u0439 \u043E\u0431\u043B\u0430\u0441\u0442\u0438 \u0440\u0435\u0434\u0430\u043A\u0442\u043E\u0440\u0430 \u0432\u043C\u0435\u0441\u0442\u043E \u043F\u0440\u0430\u0432\u043E\u0439 \u0431\u043E\u043A\u043E\u0432\u043E\u0439 \u043F\u0430\u043D\u0435\u043B\u0438"
  },
  cliPath: {
    name: "\u041F\u0443\u0442\u044C \u043A CLI Claude",
    desc: "\u041F\u043E\u043B\u044C\u0437\u043E\u0432\u0430\u0442\u0435\u043B\u044C\u0441\u043A\u0438\u0439 \u043F\u0443\u0442\u044C \u043A Claude Code CLI. \u041E\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u043F\u0443\u0441\u0442\u044B\u043C \u0434\u043B\u044F \u0430\u0432\u0442\u043E\u043C\u0430\u0442\u0438\u0447\u0435\u0441\u043A\u043E\u0433\u043E \u043E\u043F\u0440\u0435\u0434\u0435\u043B\u0435\u043D\u0438\u044F.",
    descWindows: "\u0414\u043B\u044F \u043D\u0430\u0442\u0438\u0432\u043D\u043E\u0433\u043E \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u0449\u0438\u043A\u0430 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 claude.exe. \u0414\u043B\u044F \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043E\u043A \u0447\u0435\u0440\u0435\u0437 npm/pnpm/yarn \u0438\u043B\u0438 \u0434\u0440\u0443\u0433\u0438\u0435 \u043C\u0435\u043D\u0435\u0434\u0436\u0435\u0440\u044B \u043F\u0430\u043A\u0435\u0442\u043E\u0432 \u0438\u0441\u043F\u043E\u043B\u044C\u0437\u0443\u0439\u0442\u0435 \u043F\u0443\u0442\u044C \u043A cli.js (\u043D\u0435 claude.cmd).",
    descUnix: '\u0412\u0441\u0442\u0430\u0432\u044C\u0442\u0435 \u0432\u044B\u0432\u043E\u0434 \u043A\u043E\u043C\u0430\u043D\u0434\u044B "which claude" \u2014 \u0440\u0430\u0431\u043E\u0442\u0430\u0435\u0442 \u043A\u0430\u043A \u0434\u043B\u044F \u043D\u0430\u0442\u0438\u0432\u043D\u044B\u0445 \u0443\u0441\u0442\u0430\u043D\u043E\u0432\u043E\u043A, \u0442\u0430\u043A \u0438 \u0434\u043B\u044F npm/pnpm/yarn.',
    validation: {
      notExist: "\u041F\u0443\u0442\u044C \u043D\u0435 \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442",
      isDirectory: "\u041F\u0443\u0442\u044C \u044F\u0432\u043B\u044F\u0435\u0442\u0441\u044F \u0434\u0438\u0440\u0435\u043A\u0442\u043E\u0440\u0438\u0435\u0439, \u0430 \u043D\u0435 \u0444\u0430\u0439\u043B\u043E\u043C"
    }
  },
  language: {
    name: "\u042F\u0437\u044B\u043A",
    desc: "\u0418\u0437\u043C\u0435\u043D\u0438\u0442\u044C \u044F\u0437\u044B\u043A \u0438\u043D\u0442\u0435\u0440\u0444\u0435\u0439\u0441\u0430 \u043F\u043B\u0430\u0433\u0438\u043D\u0430"
  }
};
var ru_default = {
  common: common8,
  chat: chat8,
  settings: settings8
};

// src/i18n/locales/zh-CN.json
var zh_CN_exports = {};
__export(zh_CN_exports, {
  chat: () => chat9,
  common: () => common9,
  default: () => zh_CN_default,
  settings: () => settings9
});
var common9 = {
  save: "\u4FDD\u5B58",
  cancel: "\u53D6\u6D88",
  delete: "\u5220\u9664",
  edit: "\u7F16\u8F91",
  add: "\u6DFB\u52A0",
  remove: "\u79FB\u9664",
  clear: "\u6E05\u9664",
  clearAll: "\u6E05\u9664\u5168\u90E8",
  loading: "\u52A0\u8F7D\u4E2D",
  error: "\u9519\u8BEF",
  success: "\u6210\u529F",
  warning: "\u8B66\u544A",
  confirm: "\u786E\u8BA4",
  settings: "\u8BBE\u7F6E",
  advanced: "\u9AD8\u7EA7",
  enabled: "\u5DF2\u542F\u7528",
  disabled: "\u5DF2\u7981\u7528",
  platform: "\u5E73\u53F0",
  refresh: "\u5237\u65B0",
  rewind: "\u56DE\u9000"
};
var chat9 = {
  rewind: {
    confirmMessage: "\u56DE\u9000\u5230\u6B64\u5904\uFF1F\u6B64\u6D88\u606F\u4E4B\u540E\u7684\u6587\u4EF6\u66F4\u6539\u5C06\u88AB\u8FD8\u539F\u3002\u56DE\u9000\u4E0D\u4F1A\u5F71\u54CD\u624B\u52A8\u6216\u901A\u8FC7 bash \u7F16\u8F91\u7684\u6587\u4EF6\u3002",
    confirmButton: "\u56DE\u9000",
    ariaLabel: "\u56DE\u9000\u5230\u6B64\u5904",
    notice: "\u5DF2\u56DE\u9000\uFF1A\u8FD8\u539F\u4E86 {count} \u4E2A\u6587\u4EF6",
    noticeSaveFailed: "\u5DF2\u56DE\u9000\uFF1A\u8FD8\u539F\u4E86 {count} \u4E2A\u6587\u4EF6\uFF0C\u4F46\u65E0\u6CD5\u4FDD\u5B58\u72B6\u6001\uFF1A{error}",
    failed: "\u56DE\u9000\u5931\u8D25\uFF1A{error}",
    cannot: "\u65E0\u6CD5\u56DE\u9000\uFF1A{error}",
    unavailableStreaming: "\u6D41\u5F0F\u54CD\u5E94\u4E2D\u65E0\u6CD5\u56DE\u9000",
    unavailableNoUuid: "\u65E0\u6CD5\u56DE\u9000\uFF1A\u7F3A\u5C11\u6D88\u606F\u6807\u8BC6\u7B26"
  },
  fork: {
    ariaLabel: "\u5206\u53C9\u5BF9\u8BDD",
    chooseTarget: "\u5206\u53C9\u5BF9\u8BDD",
    targetNewTab: "\u65B0\u6807\u7B7E\u9875",
    targetCurrentTab: "\u5F53\u524D\u6807\u7B7E\u9875",
    maxTabsReached: "\u65E0\u6CD5\u5206\u53C9\uFF1A\u5DF2\u8FBE\u5230\u6700\u5927 {count} \u4E2A\u6807\u7B7E\u9875",
    notice: "\u5DF2\u5206\u53C9\u5230\u65B0\u6807\u7B7E\u9875",
    noticeCurrentTab: "\u5DF2\u5728\u5F53\u524D\u6807\u7B7E\u9875\u5206\u53C9",
    failed: "\u5206\u53C9\u5931\u8D25\uFF1A{error}",
    unavailableStreaming: "\u6D41\u5F0F\u54CD\u5E94\u4E2D\u65E0\u6CD5\u5206\u53C9",
    unavailableNoUuid: "\u65E0\u6CD5\u5206\u53C9\uFF1A\u7F3A\u5C11\u6D88\u606F\u6807\u8BC6\u7B26",
    unavailableNoResponse: "\u65E0\u6CD5\u5206\u53C9\uFF1A\u6CA1\u6709\u53EF\u5206\u53C9\u7684\u54CD\u5E94",
    errorMessageNotFound: "\u672A\u627E\u5230\u6D88\u606F",
    errorNoSession: "\u6CA1\u6709\u53EF\u7528\u7684\u4F1A\u8BDD ID",
    errorNoActiveTab: "\u6CA1\u6709\u6D3B\u52A8\u6807\u7B7E\u9875",
    commandNoMessages: "\u65E0\u6CD5\u5206\u53C9\uFF1A\u5BF9\u8BDD\u4E2D\u6CA1\u6709\u6D88\u606F",
    commandNoAssistantUuid: "\u65E0\u6CD5\u5206\u53C9\uFF1A\u6CA1\u6709\u5E26\u6807\u8BC6\u7B26\u7684\u52A9\u624B\u56DE\u590D"
  },
  bangBash: {
    placeholder: "> \u8FD0\u884C\u547D\u4EE4...",
    commandPanel: "\u547D\u4EE4\u9762\u677F",
    copyAriaLabel: "\u590D\u5236\u6700\u65B0\u547D\u4EE4\u8F93\u51FA",
    clearAriaLabel: "\u6E05\u9664\u547D\u4EE4\u8F93\u51FA",
    commandLabel: "{command}",
    statusLabel: "\u72B6\u6001: {status}",
    collapseOutput: "\u6298\u53E0\u547D\u4EE4\u8F93\u51FA",
    expandOutput: "\u5C55\u5F00\u547D\u4EE4\u8F93\u51FA",
    running: "\u8FD0\u884C\u4E2D...",
    copyFailed: "\u590D\u5236\u5230\u526A\u8D34\u677F\u5931\u8D25"
  }
};
var settings9 = {
  title: "Claudian \u8BBE\u7F6E",
  tabs: {
    general: "\u901A\u7528",
    claude: "Claude",
    codex: "Codex"
  },
  display: "\u663E\u793A",
  conversations: "\u5BF9\u8BDD",
  content: "\u5185\u5BB9",
  input: "\u8F93\u5165",
  setup: "\u8BBE\u7F6E",
  models: "\u6A21\u578B",
  experimental: "\u5B9E\u9A8C\u6027\u529F\u80FD",
  userName: {
    name: "Claudian \u5E94\u8BE5\u5982\u4F55\u79F0\u547C\u4F60\uFF1F",
    desc: "\u7528\u4E8E\u4E2A\u6027\u5316\u95EE\u5019\u7684\u7528\u6237\u540D\uFF08\u7559\u7A7A\u4F7F\u7528\u901A\u7528\u95EE\u5019\uFF09"
  },
  excludedTags: {
    name: "\u6392\u9664\u7684\u6807\u7B7E",
    desc: "\u5305\u542B\u8FD9\u4E9B\u6807\u7B7E\u7684\u7B14\u8BB0\u4E0D\u4F1A\u81EA\u52A8\u52A0\u8F7D\u4E3A\u4E0A\u4E0B\u6587\uFF08\u6BCF\u884C\u4E00\u4E2A\uFF0C\u4E0D\u5E26 #\uFF09"
  },
  mediaFolder: {
    name: "\u5A92\u4F53\u6587\u4EF6\u5939",
    desc: "\u5B58\u653E\u9644\u4EF6/\u56FE\u7247\u7684\u6587\u4EF6\u5939\u3002\u5F53\u7B14\u8BB0\u4F7F\u7528 ![[image.jpg]] \u65F6\uFF0CClaude \u4F1A\u5728\u6B64\u67E5\u627E\u3002\u7559\u7A7A\u4F7F\u7528\u4ED3\u5E93\u6839\u76EE\u5F55\u3002"
  },
  systemPrompt: {
    name: "\u81EA\u5B9A\u4E49\u7CFB\u7EDF\u63D0\u793A\u8BCD",
    desc: "\u9644\u52A0\u5230\u9ED8\u8BA4\u7CFB\u7EDF\u63D0\u793A\u8BCD\u7684\u989D\u5916\u6307\u4EE4"
  },
  autoTitle: {
    name: "\u81EA\u52A8\u751F\u6210\u5BF9\u8BDD\u6807\u9898",
    desc: "\u5728\u7528\u6237\u53D1\u9001\u9996\u6761\u6D88\u606F\u540E\u81EA\u52A8\u751F\u6210\u5BF9\u8BDD\u6807\u9898\u3002"
  },
  titleModel: {
    name: "\u6807\u9898\u751F\u6210\u6A21\u578B",
    desc: "\u7528\u4E8E\u81EA\u52A8\u751F\u6210\u5BF9\u8BDD\u6807\u9898\u7684\u6A21\u578B\u3002",
    auto: "\u81EA\u52A8 (Haiku)"
  },
  navMappings: {
    name: "Vim \u98CE\u683C\u5BFC\u822A\u6620\u5C04",
    desc: '\u6BCF\u884C\u4E00\u4E2A\u6620\u5C04\u3002\u683C\u5F0F\uFF1A"map <\u952E> <\u52A8\u4F5C>"\uFF08\u52A8\u4F5C\uFF1AscrollUp, scrollDown, focusInput\uFF09\u3002'
  },
  hotkeys: "\u5FEB\u6377\u952E",
  inlineEditHotkey: {
    name: "\u5185\u8054\u7F16\u8F91",
    descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}",
    descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E",
    btnChange: "\u66F4\u6539",
    btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E"
  },
  openChatHotkey: {
    name: "\u6253\u5F00\u804A\u5929",
    descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}",
    descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E",
    btnChange: "\u66F4\u6539",
    btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E"
  },
  newSessionHotkey: {
    name: "\u65B0\u4F1A\u8BDD",
    descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}",
    descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E",
    btnChange: "\u66F4\u6539",
    btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E"
  },
  newTabHotkey: {
    name: "\u65B0\u6807\u7B7E\u9875",
    descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}",
    descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E",
    btnChange: "\u66F4\u6539",
    btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E"
  },
  closeTabHotkey: {
    name: "\u5173\u95ED\u6807\u7B7E\u9875",
    descWithKey: "\u5F53\u524D\u5FEB\u6377\u952E\uFF1A{hotkey}",
    descNoKey: "\u672A\u8BBE\u7F6E\u5FEB\u6377\u952E",
    btnChange: "\u66F4\u6539",
    btnSet: "\u8BBE\u7F6E\u5FEB\u6377\u952E"
  },
  slashCommands: {
    name: "\u547D\u4EE4\u4E0E\u6280\u80FD",
    desc: "\u7BA1\u7406\u5B58\u50A8\u5728 .claude/commands/ \u548C .claude/skills/ \u4E2D\u7684 Vault \u7EA7\u547D\u4EE4\u4E0E\u6280\u80FD\u3002\u7531 /\u540D\u79F0 \u89E6\u53D1\u3002"
  },
  hiddenSlashCommands: {
    name: "\u9690\u85CF\u547D\u4EE4\u4E0E\u6280\u80FD",
    desc: "\u4ECE\u4E0B\u62C9\u83DC\u5355\u4E2D\u9690\u85CF\u7279\u5B9A\u7684\u547D\u4EE4\u4E0E\u6280\u80FD\u3002\u9002\u7528\u4E8E\u9690\u85CF\u4E0E Claudian \u65E0\u5173\u7684 Claude Code \u6761\u76EE\u3002\u6BCF\u884C\u8F93\u5165\u4E00\u4E2A\u540D\u79F0\uFF0C\u65E0\u9700\u524D\u5BFC\u659C\u6760\u3002",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "MCP \u670D\u52A1\u5668",
    desc: "\u7BA1\u7406\u5B58\u50A8\u5728 .claude/mcp.json \u4E2D\u7684 Vault \u7EA7 MCP \u670D\u52A1\u5668\u914D\u7F6E\u3002\u542F\u7528\u4E0A\u4E0B\u6587\u4FDD\u5B58\u6A21\u5F0F\u7684\u670D\u52A1\u5668\u9700\u8981 @ \u63D0\u53CA\u624D\u80FD\u6FC0\u6D3B\u3002"
  },
  plugins: {
    name: "Claude Code \u63D2\u4EF6",
    desc: "\u7BA1\u7406\u4ECE ~/.claude/plugins \u53D1\u73B0\u7684 Claude Code \u63D2\u4EF6\u3002\u542F\u7528\u7684\u63D2\u4EF6\u6309 Vault \u5B58\u50A8\u5728 .claude/settings.json \u4E2D\u3002"
  },
  subagents: {
    name: "\u5B50\u4EE3\u7406",
    desc: "\u7BA1\u7406\u5B58\u50A8\u5728 .claude/agents/ \u4E2D\u7684 Vault \u7EA7\u5B50\u4EE3\u7406\u3002\u6BCF\u4E2A Markdown \u6587\u4EF6\u5B9A\u4E49\u4E00\u4E2A\u81EA\u5B9A\u4E49\u4EE3\u7406\u3002",
    noAgents: "\u5C1A\u672A\u914D\u7F6E\u5B50\u4EE3\u7406\u3002\u70B9\u51FB + \u521B\u5EFA\u4E00\u4E2A\u3002",
    deleteConfirm: "\u5220\u9664\u5B50\u4EE3\u7406\u201C{name}\u201D\uFF1F",
    saveFailed: "\u4FDD\u5B58\u5B50\u4EE3\u7406\u5931\u8D25\uFF1A{message}",
    refreshFailed: "\u5237\u65B0\u5B50\u4EE3\u7406\u5931\u8D25\uFF1A{message}",
    deleteFailed: "\u5220\u9664\u5B50\u4EE3\u7406\u5931\u8D25\uFF1A{message}",
    renameCleanupFailed: "\u8B66\u544A\uFF1A\u65E0\u6CD5\u5220\u9664\u201C{name}\u201D\u7684\u65E7\u6587\u4EF6",
    created: "\u5DF2\u521B\u5EFA\u5B50\u4EE3\u7406\u201C{name}\u201D",
    updated: "\u5DF2\u66F4\u65B0\u5B50\u4EE3\u7406\u201C{name}\u201D",
    deleted: "\u5DF2\u5220\u9664\u5B50\u4EE3\u7406\u201C{name}\u201D",
    duplicateName: "\u540D\u4E3A\u201C{name}\u201D\u7684\u4EE3\u7406\u5DF2\u5B58\u5728",
    descriptionRequired: "\u63CF\u8FF0\u4E3A\u5FC5\u586B\u9879",
    promptRequired: "\u7CFB\u7EDF\u63D0\u793A\u8BCD\u4E3A\u5FC5\u586B\u9879",
    modal: {
      titleEdit: "\u7F16\u8F91\u5B50\u4EE3\u7406",
      titleAdd: "\u6DFB\u52A0\u5B50\u4EE3\u7406",
      name: "\u540D\u79F0",
      nameDesc: "\u4EC5\u5141\u8BB8\u5C0F\u5199\u5B57\u6BCD\u3001\u6570\u5B57\u548C\u8FDE\u5B57\u7B26",
      namePlaceholder: "code-reviewer",
      description: "\u63CF\u8FF0",
      descriptionDesc: "\u8BE5\u4EE3\u7406\u7684\u7B80\u8981\u63CF\u8FF0",
      descriptionPlaceholder: "\u5BA1\u67E5\u4EE3\u7801\u4E2D\u7684\u9519\u8BEF\u548C\u98CE\u683C\u95EE\u9898",
      advancedOptions: "\u9AD8\u7EA7\u9009\u9879",
      model: "\u6A21\u578B",
      modelDesc: "\u8BE5\u4EE3\u7406\u7684\u6A21\u578B\u8986\u76D6",
      tools: "\u5DE5\u5177",
      toolsDesc: "\u5141\u8BB8\u4F7F\u7528\u7684\u5DE5\u5177\u5217\u8868\uFF0C\u7528\u9017\u53F7\u5206\u9694\uFF08\u7559\u7A7A = \u5168\u90E8\uFF09",
      disallowedTools: "\u7981\u7528\u5DE5\u5177",
      disallowedToolsDesc: "\u8981\u7981\u7528\u7684\u5DE5\u5177\u5217\u8868\uFF0C\u7528\u9017\u53F7\u5206\u9694",
      skills: "\u6280\u80FD",
      skillsDesc: "\u6280\u80FD\u5217\u8868\uFF0C\u7528\u9017\u53F7\u5206\u9694",
      prompt: "\u7CFB\u7EDF\u63D0\u793A\u8BCD",
      promptDesc: "\u7ED9\u4EE3\u7406\u7684\u6307\u4EE4",
      promptPlaceholder: "\u4F60\u662F\u4E00\u540D\u4EE3\u7801\u5BA1\u67E5\u5458\u3002\u8BF7\u5206\u6790\u7ED9\u5B9A\u4EE3\u7801\u4E2D\u7684..."
    }
  },
  safety: "\u5B89\u5168",
  loadUserSettings: {
    name: "\u52A0\u8F7D\u7528\u6237 Claude \u8BBE\u7F6E",
    desc: "\u52A0\u8F7D ~/.claude/settings.json\u3002\u542F\u7528\u540E\uFF0C\u7528\u6237\u7684 Claude Code \u6743\u9650\u89C4\u5219\u53EF\u80FD\u7ED5\u8FC7\u5B89\u5168\u6A21\u5F0F\u3002"
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "\u73AF\u5883",
  customVariables: {
    name: "\u81EA\u5B9A\u4E49\u53D8\u91CF",
    desc: "Claude SDK \u7684\u73AF\u5883\u53D8\u91CF\uFF08KEY=VALUE \u683C\u5F0F\uFF0C\u6BCF\u884C\u4E00\u4E2A\uFF09\u3002\u652F\u6301 export \u524D\u7F00\u3002"
  },
  envSnippets: {
    name: "\u7247\u6BB5",
    addBtn: "\u6DFB\u52A0\u7247\u6BB5",
    noSnippets: "\u5C1A\u65E0\u4FDD\u5B58\u7684\u73AF\u5883\u53D8\u91CF\u7247\u6BB5\u3002\u70B9\u51FB + \u4FDD\u5B58\u5F53\u524D\u914D\u7F6E\u3002",
    nameRequired: "\u8BF7\u8F93\u5165\u7247\u6BB5\u540D\u79F0",
    modal: {
      titleEdit: "\u7F16\u8F91\u7247\u6BB5",
      titleSave: "\u4FDD\u5B58\u7247\u6BB5",
      name: "\u540D\u79F0",
      namePlaceholder: "\u6B64\u914D\u7F6E\u7684\u63CF\u8FF0\u6027\u540D\u79F0",
      description: "\u63CF\u8FF0",
      descPlaceholder: "\u53EF\u9009\u63CF\u8FF0",
      envVars: "\u73AF\u5883\u53D8\u91CF",
      envVarsPlaceholder: "KEY=VALUE \u683C\u5F0F\uFF0C\u6BCF\u884C\u4E00\u4E2A\uFF08\u652F\u6301 export \u524D\u7F00\uFF09",
      save: "\u4FDD\u5B58",
      update: "\u66F4\u65B0",
      cancel: "\u53D6\u6D88"
    }
  },
  customContextLimits: {
    name: "\u81EA\u5B9A\u4E49\u4E0A\u4E0B\u6587\u9650\u5236",
    desc: "\u4E3A\u60A8\u7684\u81EA\u5B9A\u4E49\u6A21\u578B\u8BBE\u7F6E\u4E0A\u4E0B\u6587\u7A97\u53E3\u5927\u5C0F\u3002\u7559\u7A7A\u4F7F\u7528\u9ED8\u8BA4\u503C\uFF08200k \u4EE4\u724C\uFF09\u3002",
    invalid: "\u683C\u5F0F\u65E0\u6548\u3002\u4F7F\u7528\uFF1A256k\u30011m \u6216\u7CBE\u786E\u6570\u91CF\uFF081000-10000000\uFF09\u3002"
  },
  enableOpus1M: {
    name: "Opus 1M \u4E0A\u4E0B\u6587\u7A97\u53E3",
    desc: "\u5728\u6A21\u578B\u9009\u62E9\u5668\u4E2D\u663E\u793A Opus 1M\u3002Max\u3001Team \u548C Enterprise \u8BA1\u5212\u5DF2\u5305\u542B\u3002API \u548C Pro \u7528\u6237\u9700\u8981\u989D\u5916\u7528\u91CF\u3002"
  },
  enableSonnet1M: {
    name: "Sonnet 1M \u4E0A\u4E0B\u6587\u7A97\u53E3",
    desc: "\u5728\u6A21\u578B\u9009\u62E9\u5668\u4E2D\u663E\u793A Sonnet 1M\u3002Max\u3001Team \u548C Enterprise \u8BA1\u5212\u9700\u8981\u989D\u5916\u7528\u91CF\u3002API \u548C Pro \u7528\u6237\u9700\u8981\u989D\u5916\u7528\u91CF\u3002"
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "\u542F\u7528 Chrome \u6269\u5C55",
    desc: "\u5141\u8BB8 Claude \u901A\u8FC7 claude-in-chrome \u6269\u5C55\u4E0E Chrome \u4EA4\u4E92\u3002\u9700\u8981\u5B89\u88C5\u8BE5\u6269\u5C55\u3002\u9700\u8981\u91CD\u542F\u4F1A\u8BDD\u3002"
  },
  enableBangBash: {
    name: "\u542F\u7528\u547D\u4EE4\u6A21\u5F0F (!)",
    desc: "\u5728\u7A7A\u8F93\u5165\u6846\u4E2D\u8F93\u5165 ! \u8FDB\u5165\u547D\u4EE4\u6A21\u5F0F\u3002\u901A\u8FC7 Node.js child_process \u76F4\u63A5\u8FD0\u884C\u547D\u4EE4\u3002\u9700\u8981\u91CD\u65B0\u6253\u5F00\u89C6\u56FE\u3002",
    validation: {
      noNode: "\u672A\u5728 PATH \u4E2D\u627E\u5230 Node.js\u3002\u8BF7\u5B89\u88C5 Node.js \u6216\u68C0\u67E5 PATH \u914D\u7F6E\u3002"
    }
  },
  maxTabs: {
    name: "\u6700\u5927\u804A\u5929\u6807\u7B7E\u6570",
    desc: "\u540C\u65F6\u5F00\u542F\u7684\u6700\u5927\u804A\u5929\u6807\u7B7E\u6570\uFF083-10\uFF09\u3002\u6BCF\u4E2A\u6807\u7B7E\u4F7F\u7528\u72EC\u7ACB\u7684 Claude \u4F1A\u8BDD\u3002",
    warning: "\u8D85\u8FC7 5 \u4E2A\u6807\u7B7E\u53EF\u80FD\u4F1A\u5F71\u54CD\u6027\u80FD\u548C\u5185\u5B58\u4F7F\u7528\u3002"
  },
  tabBarPosition: {
    name: "\u6807\u7B7E\u680F\u4F4D\u7F6E",
    desc: "\u9009\u62E9\u6807\u7B7E\u5FBD\u7AE0\u548C\u64CD\u4F5C\u6309\u94AE\u7684\u663E\u793A\u4F4D\u7F6E",
    input: "\u8F93\u5165\u6846\u4E0A\u65B9\uFF08\u9ED8\u8BA4\uFF09",
    header: "\u5728\u6807\u9898\u680F"
  },
  enableAutoScroll: {
    name: "\u6D41\u5F0F\u4F20\u8F93\u65F6\u81EA\u52A8\u6EDA\u52A8",
    desc: "\u5728 Claude \u6D41\u5F0F\u4F20\u8F93\u54CD\u5E94\u65F6\u81EA\u52A8\u6EDA\u52A8\u5230\u5E95\u90E8\u3002\u7981\u7528\u540E\u5C06\u505C\u7559\u5728\u9876\u90E8\uFF0C\u4ECE\u5934\u5F00\u59CB\u9605\u8BFB\u3002"
  },
  openInMainTab: {
    name: "\u5728\u4E3B\u7F16\u8F91\u5668\u533A\u57DF\u6253\u5F00",
    desc: "\u5728\u4E2D\u592E\u7F16\u8F91\u5668\u533A\u57DF\u4EE5\u4E3B\u6807\u7B7E\u9875\u5F62\u5F0F\u6253\u5F00\u804A\u5929\u9762\u677F\uFF0C\u800C\u4E0D\u662F\u5728\u53F3\u4FA7\u8FB9\u680F"
  },
  cliPath: {
    name: "Claude CLI \u8DEF\u5F84",
    desc: "Claude Code CLI \u7684\u81EA\u5B9A\u4E49\u8DEF\u5F84\u3002\u7559\u7A7A\u4F7F\u7528\u81EA\u52A8\u68C0\u6D4B\u3002",
    descWindows: "\u5BF9\u4E8E\u539F\u751F\u5B89\u88C5\u7A0B\u5E8F\uFF0C\u4F7F\u7528 claude.exe\u3002\u5BF9\u4E8E npm/pnpm/yarn \u6216\u5176\u4ED6\u5305\u7BA1\u7406\u5668\u5B89\u88C5\uFF0C\u4F7F\u7528 cli.js \u8DEF\u5F84\uFF08\u4E0D\u662F claude.cmd\uFF09\u3002",
    descUnix: '\u7C98\u8D34 "which claude" \u7684\u8F93\u51FA - \u9002\u7528\u4E8E\u539F\u751F\u5B89\u88C5\u548C npm/pnpm/yarn \u5B89\u88C5\u3002',
    validation: {
      notExist: "\u8DEF\u5F84\u4E0D\u5B58\u5728",
      isDirectory: "\u8DEF\u5F84\u662F\u76EE\u5F55\uFF0C\u4E0D\u662F\u6587\u4EF6"
    }
  },
  language: {
    name: "\u8BED\u8A00",
    desc: "\u66F4\u6539\u63D2\u4EF6\u754C\u9762\u7684\u663E\u793A\u8BED\u8A00"
  }
};
var zh_CN_default = {
  common: common9,
  chat: chat9,
  settings: settings9
};

// src/i18n/locales/zh-TW.json
var zh_TW_exports = {};
__export(zh_TW_exports, {
  chat: () => chat10,
  common: () => common10,
  default: () => zh_TW_default,
  settings: () => settings10
});
var common10 = {
  save: "\u4FDD\u5B58",
  cancel: "\u53D6\u6D88",
  delete: "\u522A\u9664",
  edit: "\u7DE8\u8F2F",
  add: "\u6DFB\u52A0",
  remove: "\u79FB\u9664",
  clear: "\u6E05\u9664",
  clearAll: "\u6E05\u9664\u5168\u90E8",
  loading: "\u52A0\u8F09\u4E2D",
  error: "\u932F\u8AA4",
  success: "\u6210\u529F",
  warning: "\u8B66\u544A",
  confirm: "\u78BA\u8A8D",
  settings: "\u8A2D\u7F6E",
  advanced: "\u9AD8\u7D1A",
  enabled: "\u5DF2\u555F\u7528",
  disabled: "\u5DF2\u7981\u7528",
  platform: "\u5E73\u53F0",
  refresh: "\u91CD\u65B0\u6574\u7406",
  rewind: "\u56DE\u9000"
};
var chat10 = {
  rewind: {
    confirmMessage: "\u56DE\u9000\u5230\u6B64\u8655\uFF1F\u6B64\u8A0A\u606F\u4E4B\u5F8C\u7684\u6A94\u6848\u8B8A\u66F4\u5C07\u88AB\u9084\u539F\u3002\u56DE\u9000\u4E0D\u6703\u5F71\u97FF\u624B\u52D5\u6216\u900F\u904E bash \u7DE8\u8F2F\u7684\u6A94\u6848\u3002",
    confirmButton: "\u56DE\u9000",
    ariaLabel: "\u56DE\u9000\u5230\u6B64\u8655",
    notice: "\u5DF2\u56DE\u9000\uFF1A\u9084\u539F\u4E86 {count} \u500B\u6A94\u6848",
    noticeSaveFailed: "\u5DF2\u56DE\u9000\uFF1A\u9084\u539F\u4E86 {count} \u500B\u6A94\u6848\uFF0C\u4F46\u7121\u6CD5\u5132\u5B58\u72C0\u614B\uFF1A{error}",
    failed: "\u56DE\u9000\u5931\u6557\uFF1A{error}",
    cannot: "\u7121\u6CD5\u56DE\u9000\uFF1A{error}",
    unavailableStreaming: "\u4E32\u6D41\u56DE\u61C9\u4E2D\u7121\u6CD5\u56DE\u9000",
    unavailableNoUuid: "\u7121\u6CD5\u56DE\u9000\uFF1A\u7F3A\u5C11\u8A0A\u606F\u8B58\u5225\u78BC"
  },
  fork: {
    ariaLabel: "\u5206\u53C9\u5C0D\u8A71",
    chooseTarget: "\u5206\u53C9\u5C0D\u8A71",
    targetNewTab: "\u65B0\u5206\u9801",
    targetCurrentTab: "\u76EE\u524D\u5206\u9801",
    maxTabsReached: "\u7121\u6CD5\u5206\u53C9\uFF1A\u5DF2\u9054\u5230\u6700\u5927 {count} \u500B\u5206\u9801",
    notice: "\u5DF2\u5206\u53C9\u5230\u65B0\u5206\u9801",
    noticeCurrentTab: "\u5DF2\u5728\u76EE\u524D\u5206\u9801\u5206\u53C9",
    failed: "\u5206\u53C9\u5931\u6557\uFF1A{error}",
    unavailableStreaming: "\u4E32\u6D41\u56DE\u61C9\u4E2D\u7121\u6CD5\u5206\u53C9",
    unavailableNoUuid: "\u7121\u6CD5\u5206\u53C9\uFF1A\u7F3A\u5C11\u8A0A\u606F\u8B58\u5225\u78BC",
    unavailableNoResponse: "\u7121\u6CD5\u5206\u53C9\uFF1A\u6C92\u6709\u53EF\u5206\u53C9\u7684\u56DE\u61C9",
    errorMessageNotFound: "\u627E\u4E0D\u5230\u8A0A\u606F",
    errorNoSession: "\u6C92\u6709\u53EF\u7528\u7684\u5DE5\u4F5C\u968E\u6BB5 ID",
    errorNoActiveTab: "\u6C92\u6709\u4F7F\u7528\u4E2D\u7684\u5206\u9801",
    commandNoMessages: "\u7121\u6CD5\u5206\u53C9\uFF1A\u5C0D\u8A71\u4E2D\u6C92\u6709\u8A0A\u606F",
    commandNoAssistantUuid: "\u7121\u6CD5\u5206\u53C9\uFF1A\u6C92\u6709\u5E36\u8B58\u5225\u78BC\u7684\u52A9\u624B\u56DE\u8986"
  },
  bangBash: {
    placeholder: "> \u57F7\u884C bash \u6307\u4EE4...",
    commandPanel: "\u6307\u4EE4\u9762\u677F",
    copyAriaLabel: "\u8907\u88FD\u6700\u65B0\u7684\u6307\u4EE4\u8F38\u51FA",
    clearAriaLabel: "\u6E05\u9664 bash \u8F38\u51FA",
    commandLabel: "{command}",
    statusLabel: "\u72C0\u614B\uFF1A{status}",
    collapseOutput: "\u647A\u758A\u6307\u4EE4\u8F38\u51FA",
    expandOutput: "\u5C55\u958B\u6307\u4EE4\u8F38\u51FA",
    running: "\u57F7\u884C\u4E2D...",
    copyFailed: "\u8907\u88FD\u5230\u526A\u8CBC\u7C3F\u5931\u6557"
  }
};
var settings10 = {
  title: "Claudian \u8A2D\u5B9A",
  tabs: {
    general: "\u4E00\u822C",
    claude: "Claude",
    codex: "Codex"
  },
  display: "\u986F\u793A",
  conversations: "\u5C0D\u8A71",
  content: "\u5167\u5BB9",
  input: "\u8F38\u5165",
  setup: "\u8A2D\u5B9A",
  models: "\u6A21\u578B",
  experimental: "\u5BE6\u9A57\u6027\u529F\u80FD",
  userName: {
    name: "Claudian \u61C9\u8A72\u5982\u4F55\u7A31\u547C\u60A8\uFF1F",
    desc: "\u7528\u65BC\u500B\u4EBA\u5316\u554F\u5019\u7684\u4F7F\u7528\u8005\u540D\u7A31\uFF08\u7559\u7A7A\u4F7F\u7528\u901A\u7528\u554F\u5019\uFF09"
  },
  excludedTags: {
    name: "\u6392\u9664\u7684\u6A19\u7C64",
    desc: "\u5305\u542B\u9019\u4E9B\u6A19\u7C64\u7684\u7B46\u8A18\u4E0D\u6703\u81EA\u52D5\u8F09\u5165\u70BA\u4E0A\u4E0B\u6587\uFF08\u6BCF\u884C\u4E00\u500B\uFF0C\u4E0D\u5E36 #\uFF09"
  },
  mediaFolder: {
    name: "\u5A92\u9AD4\u8CC7\u6599\u593E",
    desc: "\u5B58\u653E\u9644\u4EF6/\u5716\u7247\u7684\u8CC7\u6599\u593E\u3002\u7576\u7B46\u8A18\u4F7F\u7528 ![[image.jpg]] \u6642\uFF0CClaude \u6703\u5728\u6B64\u67E5\u627E\u3002\u7559\u7A7A\u4F7F\u7528\u5132\u5B58\u5EAB\u6839\u76EE\u9304\u3002"
  },
  systemPrompt: {
    name: "\u81EA\u8A02\u7CFB\u7D71\u63D0\u793A\u8A5E",
    desc: "\u9644\u52A0\u5230\u9810\u8A2D\u7CFB\u7D71\u63D0\u793A\u8A5E\u7684\u984D\u5916\u6307\u4EE4"
  },
  autoTitle: {
    name: "\u81EA\u52D5\u751F\u6210\u5C0D\u8A71\u6A19\u984C",
    desc: "\u5728\u4F7F\u7528\u8005\u9001\u51FA\u7B2C\u4E00\u5247\u8A0A\u606F\u5F8C\u81EA\u52D5\u751F\u6210\u5C0D\u8A71\u6A19\u984C\u3002"
  },
  titleModel: {
    name: "\u6A19\u984C\u751F\u6210\u6A21\u578B",
    desc: "\u7528\u65BC\u81EA\u52D5\u751F\u6210\u5C0D\u8A71\u6A19\u984C\u7684\u6A21\u578B\u3002",
    auto: "\u81EA\u52D5 (Haiku)"
  },
  navMappings: {
    name: "Vim \u98A8\u683C\u5C0E\u822A\u6620\u5C04",
    desc: '\u6BCF\u884C\u4E00\u500B\u6620\u5C04\u3002\u683C\u5F0F\uFF1A"map <\u9375> <\u52D5\u4F5C>"\uFF08\u52D5\u4F5C\uFF1AscrollUp, scrollDown, focusInput\uFF09\u3002'
  },
  hotkeys: "\u5FEB\u6377\u9375",
  inlineEditHotkey: {
    name: "\u5167\u5D4C\u7DE8\u8F2F",
    descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}",
    descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375",
    btnChange: "\u8B8A\u66F4",
    btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375"
  },
  openChatHotkey: {
    name: "\u958B\u555F\u804A\u5929",
    descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}",
    descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375",
    btnChange: "\u8B8A\u66F4",
    btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375"
  },
  newSessionHotkey: {
    name: "\u65B0\u5DE5\u4F5C\u968E\u6BB5",
    descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}",
    descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375",
    btnChange: "\u8B8A\u66F4",
    btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375"
  },
  newTabHotkey: {
    name: "\u65B0\u5206\u9801",
    descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}",
    descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375",
    btnChange: "\u8B8A\u66F4",
    btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375"
  },
  closeTabHotkey: {
    name: "\u95DC\u9589\u5206\u9801",
    descWithKey: "\u76EE\u524D\u5FEB\u6377\u9375\uFF1A{hotkey}",
    descNoKey: "\u672A\u8A2D\u5B9A\u5FEB\u6377\u9375",
    btnChange: "\u8B8A\u66F4",
    btnSet: "\u8A2D\u5B9A\u5FEB\u6377\u9375"
  },
  slashCommands: {
    name: "\u547D\u4EE4\u8207\u6280\u80FD",
    desc: "\u7BA1\u7406\u5132\u5B58\u5728 .claude/commands/ \u548C .claude/skills/ \u4E2D\u7684 Vault \u7D1A\u547D\u4EE4\u8207\u6280\u80FD\u3002\u7531 /\u540D\u7A31 \u89F8\u767C\u3002"
  },
  hiddenSlashCommands: {
    name: "\u96B1\u85CF\u547D\u4EE4\u8207\u6280\u80FD",
    desc: "\u5F9E\u4E0B\u62C9\u9078\u55AE\u4E2D\u96B1\u85CF\u7279\u5B9A\u7684\u547D\u4EE4\u8207\u6280\u80FD\u3002\u9069\u7528\u65BC\u96B1\u85CF\u8207 Claudian \u7121\u95DC\u7684 Claude Code \u9805\u76EE\u3002\u6BCF\u884C\u8F38\u5165\u4E00\u500B\u540D\u7A31\uFF0C\u7121\u9700\u524D\u5C0E\u659C\u7DDA\u3002",
    placeholder: "commit\nbuild\ntest"
  },
  mcpServers: {
    name: "MCP \u4F3A\u670D\u5668",
    desc: "\u7BA1\u7406\u5132\u5B58\u5728 .claude/mcp.json \u4E2D\u7684 Vault \u7D1A MCP \u4F3A\u670D\u5668\u914D\u7F6E\u3002\u555F\u7528\u4E0A\u4E0B\u6587\u4FDD\u5B58\u6A21\u5F0F\u7684\u4F3A\u670D\u5668\u9700\u8981 @ \u63D0\u53CA\u624D\u80FD\u555F\u7528\u3002"
  },
  plugins: {
    name: "Claude Code \u5916\u639B\u7A0B\u5F0F",
    desc: "\u7BA1\u7406\u5F9E ~/.claude/plugins \u767C\u73FE\u7684 Claude Code \u5916\u639B\u7A0B\u5F0F\u3002\u5DF2\u555F\u7528\u7684\u5916\u639B\u7A0B\u5F0F\u6309 Vault \u5132\u5B58\u5728 .claude/settings.json \u4E2D\u3002"
  },
  subagents: {
    name: "\u5B50\u4EE3\u7406",
    desc: "\u7BA1\u7406\u5132\u5B58\u5728 .claude/agents/ \u4E2D\u7684 Vault \u7D1A\u5B50\u4EE3\u7406\u3002\u6BCF\u500B Markdown \u6A94\u6848\u5B9A\u7FA9\u4E00\u500B\u81EA\u8A02\u4EE3\u7406\u3002",
    noAgents: "\u5C1A\u672A\u8A2D\u5B9A\u5B50\u4EE3\u7406\u3002\u9EDE\u64CA + \u5EFA\u7ACB\u4E00\u500B\u3002",
    deleteConfirm: "\u522A\u9664\u5B50\u4EE3\u7406\u300C{name}\u300D\uFF1F",
    saveFailed: "\u5132\u5B58\u5B50\u4EE3\u7406\u5931\u6557\uFF1A{message}",
    refreshFailed: "\u91CD\u65B0\u6574\u7406\u5B50\u4EE3\u7406\u5931\u6557\uFF1A{message}",
    deleteFailed: "\u522A\u9664\u5B50\u4EE3\u7406\u5931\u6557\uFF1A{message}",
    renameCleanupFailed: "\u8B66\u544A\uFF1A\u7121\u6CD5\u79FB\u9664\u300C{name}\u300D\u7684\u820A\u6A94\u6848",
    created: "\u5DF2\u5EFA\u7ACB\u5B50\u4EE3\u7406\u300C{name}\u300D",
    updated: "\u5DF2\u66F4\u65B0\u5B50\u4EE3\u7406\u300C{name}\u300D",
    deleted: "\u5DF2\u522A\u9664\u5B50\u4EE3\u7406\u300C{name}\u300D",
    duplicateName: "\u5DF2\u5B58\u5728\u540D\u70BA\u300C{name}\u300D\u7684\u4EE3\u7406",
    descriptionRequired: "\u63CF\u8FF0\u70BA\u5FC5\u586B",
    promptRequired: "\u7CFB\u7D71\u63D0\u793A\u8A5E\u70BA\u5FC5\u586B",
    modal: {
      titleEdit: "\u7DE8\u8F2F\u5B50\u4EE3\u7406",
      titleAdd: "\u65B0\u589E\u5B50\u4EE3\u7406",
      name: "\u540D\u7A31",
      nameDesc: "\u50C5\u9650\u5C0F\u5BEB\u5B57\u6BCD\u3001\u6578\u5B57\u8207\u9023\u5B57\u865F",
      namePlaceholder: "code-reviewer",
      description: "\u63CF\u8FF0",
      descriptionDesc: "\u6B64\u4EE3\u7406\u7684\u7C21\u77ED\u63CF\u8FF0",
      descriptionPlaceholder: "\u6AA2\u67E5\u7A0B\u5F0F\u78BC\u4E2D\u7684\u932F\u8AA4\u8207\u98A8\u683C\u554F\u984C",
      advancedOptions: "\u9032\u968E\u9078\u9805",
      model: "\u6A21\u578B",
      modelDesc: "\u6B64\u4EE3\u7406\u7684\u6A21\u578B\u8986\u5BEB",
      tools: "\u5DE5\u5177",
      toolsDesc: "\u5141\u8A31\u5DE5\u5177\u7684\u9017\u865F\u5206\u9694\u6E05\u55AE\uFF08\u7559\u7A7A = \u5168\u90E8\uFF09",
      disallowedTools: "\u7981\u7528\u5DE5\u5177",
      disallowedToolsDesc: "\u8981\u7981\u7528\u7684\u5DE5\u5177\u6E05\u55AE\uFF0C\u4EE5\u9017\u865F\u5206\u9694",
      skills: "\u6280\u80FD",
      skillsDesc: "\u6280\u80FD\u6E05\u55AE\uFF0C\u4EE5\u9017\u865F\u5206\u9694",
      prompt: "\u7CFB\u7D71\u63D0\u793A\u8A5E",
      promptDesc: "\u7D66\u4EE3\u7406\u7684\u6307\u793A",
      promptPlaceholder: "\u4F60\u662F\u4E00\u540D\u7A0B\u5F0F\u78BC\u5BE9\u67E5\u54E1\u3002\u8ACB\u5206\u6790\u7D66\u5B9A\u7684\u7A0B\u5F0F\u78BC..."
    }
  },
  safety: "\u5B89\u5168",
  loadUserSettings: {
    name: "\u8F09\u5165\u4F7F\u7528\u8005 Claude \u8A2D\u5B9A",
    desc: "\u8F09\u5165 ~/.claude/settings.json\u3002\u555F\u7528\u5F8C\uFF0C\u4F7F\u7528\u8005\u7684 Claude Code \u6B0A\u9650\u898F\u5247\u53EF\u80FD\u7E5E\u904E\u5B89\u5168\u6A21\u5F0F\u3002"
  },
  claudeSafeMode: {
    name: "Safe mode",
    desc: "Permission mode used when the Safe toggle is active."
  },
  codexSafeMode: {
    name: "Safe mode",
    desc: "Sandbox mode used when the Safe toggle is active."
  },
  environment: "\u74B0\u5883",
  customVariables: {
    name: "\u81EA\u8A02\u8B8A\u6578",
    desc: "Claude SDK \u7684\u74B0\u5883\u8B8A\u6578\uFF08KEY=VALUE \u683C\u5F0F\uFF0C\u6BCF\u884C\u4E00\u500B\uFF09\u3002\u652F\u63F4 export \u524D\u7DB4\u3002"
  },
  envSnippets: {
    name: "\u7247\u6BB5",
    addBtn: "\u65B0\u589E\u7247\u6BB5",
    noSnippets: "\u5C1A\u7121\u4FDD\u5B58\u7684\u74B0\u5883\u8B8A\u6578\u7247\u6BB5\u3002\u9EDE\u64CA + \u4FDD\u5B58\u7576\u524D\u914D\u7F6E\u3002",
    nameRequired: "\u8ACB\u8F38\u5165\u7247\u6BB5\u540D\u7A31",
    modal: {
      titleEdit: "\u7DE8\u8F2F\u7247\u6BB5",
      titleSave: "\u4FDD\u5B58\u7247\u6BB5",
      name: "\u540D\u7A31",
      namePlaceholder: "\u6B64\u914D\u7F6E\u7684\u63CF\u8FF0\u6027\u540D\u7A31",
      description: "\u63CF\u8FF0",
      descPlaceholder: "\u53EF\u9078\u63CF\u8FF0",
      envVars: "\u74B0\u5883\u8B8A\u6578",
      envVarsPlaceholder: "KEY=VALUE \u683C\u5F0F\uFF0C\u6BCF\u884C\u4E00\u500B\uFF08\u652F\u63F4 export \u524D\u7DB4\uFF09",
      save: "\u4FDD\u5B58",
      update: "\u66F4\u65B0",
      cancel: "\u53D6\u6D88"
    }
  },
  customContextLimits: {
    name: "\u81EA\u8A02\u4E0A\u4E0B\u6587\u9650\u5236",
    desc: "\u70BA\u60A8\u7684\u81EA\u8A02\u6A21\u578B\u8A2D\u5B9A\u4E0A\u4E0B\u6587\u8996\u7A97\u5927\u5C0F\u3002\u7559\u7A7A\u4F7F\u7528\u9810\u8A2D\u503C\uFF08200k \u6B0A\u6756\uFF09\u3002",
    invalid: "\u683C\u5F0F\u7121\u6548\u3002\u4F7F\u7528\uFF1A256k\u30011m \u6216\u7CBE\u78BA\u6578\u91CF\uFF081000-10000000\uFF09\u3002"
  },
  enableOpus1M: {
    name: "Opus 1M \u4E0A\u4E0B\u6587\u8996\u7A97",
    desc: "\u5728\u6A21\u578B\u9078\u64C7\u5668\u4E2D\u986F\u793A Opus 1M\u3002Max\u3001Team \u548C Enterprise \u65B9\u6848\u5DF2\u5305\u542B\u3002API \u548C Pro \u4F7F\u7528\u8005\u9700\u8981\u984D\u5916\u7528\u91CF\u3002"
  },
  enableSonnet1M: {
    name: "Sonnet 1M \u4E0A\u4E0B\u6587\u8996\u7A97",
    desc: "\u5728\u6A21\u578B\u9078\u64C7\u5668\u4E2D\u986F\u793A Sonnet 1M\u3002Max\u3001Team \u548C Enterprise \u65B9\u6848\u9700\u8981\u984D\u5916\u7528\u91CF\u3002API \u548C Pro \u4F7F\u7528\u8005\u9700\u8981\u984D\u5916\u7528\u91CF\u3002"
  },
  customModels: {
    name: "Custom models",
    desc: "Append additional Claude model IDs to the picker, one per line. Environment model overrides still replace the picker.",
    placeholder: "claude-opus-4-6\nclaude-opus-4-6[1m]\nclaude-opus-4-5-20251101"
  },
  enableChrome: {
    name: "\u555F\u7528 Chrome \u64F4\u5145\u529F\u80FD",
    desc: "\u5141\u8A31 Claude \u900F\u904E claude-in-chrome \u64F4\u5145\u529F\u80FD\u8207 Chrome \u4E92\u52D5\u3002\u9700\u8981\u5B89\u88DD\u8A72\u64F4\u5145\u529F\u80FD\u3002\u9700\u8981\u91CD\u65B0\u555F\u52D5\u5DE5\u4F5C\u968E\u6BB5\u3002"
  },
  enableBangBash: {
    name: "\u555F\u7528 bash \u6A21\u5F0F (!)",
    desc: "\u5728\u7A7A\u767D\u8F38\u5165\u6846\u4E2D\u8F38\u5165 ! \u4EE5\u9032\u5165 bash \u6A21\u5F0F\u3002\u900F\u904E Node.js child_process \u76F4\u63A5\u57F7\u884C\u6307\u4EE4\u3002\u9700\u8981\u91CD\u65B0\u958B\u555F\u6AA2\u8996\u3002",
    validation: {
      noNode: "\u5728 PATH \u4E2D\u627E\u4E0D\u5230 Node.js\u3002\u8ACB\u5B89\u88DD Node.js \u6216\u6AA2\u67E5 PATH \u8A2D\u5B9A\u3002"
    }
  },
  maxTabs: {
    name: "\u6700\u5927\u804A\u5929\u6A19\u7C64\u6578",
    desc: "\u540C\u6642\u958B\u555F\u7684\u6700\u5927\u804A\u5929\u6A19\u7C64\u6578\uFF083-10\uFF09\u3002\u6BCF\u500B\u6A19\u7C64\u4F7F\u7528\u7368\u7ACB\u7684 Claude \u5C0D\u8A71\u3002",
    warning: "\u8D85\u904E 5 \u500B\u6A19\u7C64\u53EF\u80FD\u6703\u5F71\u97FF\u6548\u80FD\u548C\u8A18\u61B6\u9AD4\u4F7F\u7528\u3002"
  },
  tabBarPosition: {
    name: "\u6A19\u7C64\u5217\u4F4D\u7F6E",
    desc: "\u9078\u64C7\u6A19\u7C64\u5FBD\u7AE0\u548C\u64CD\u4F5C\u6309\u9215\u7684\u986F\u793A\u4F4D\u7F6E",
    input: "\u8F38\u5165\u6846\u4E0A\u65B9\uFF08\u9810\u8A2D\uFF09",
    header: "\u5728\u6A19\u984C\u5217"
  },
  enableAutoScroll: {
    name: "\u4E32\u6D41\u50B3\u8F38\u6642\u81EA\u52D5\u6372\u52D5",
    desc: "\u5728 Claude \u4E32\u6D41\u50B3\u8F38\u56DE\u61C9\u6642\u81EA\u52D5\u6372\u52D5\u5230\u5E95\u90E8\u3002\u505C\u7528\u5F8C\u5C07\u505C\u7559\u5728\u9802\u90E8\uFF0C\u5F9E\u982D\u958B\u59CB\u95B1\u8B80\u3002"
  },
  openInMainTab: {
    name: "\u5728\u4E3B\u7DE8\u8F2F\u5668\u5340\u57DF\u958B\u555F",
    desc: "\u5728\u4E2D\u592E\u7DE8\u8F2F\u5668\u5340\u57DF\u4EE5\u4E3B\u5206\u9801\u5F62\u5F0F\u958B\u555F\u804A\u5929\u9762\u677F\uFF0C\u800C\u4E0D\u662F\u5728\u53F3\u5074\u908A\u6B04"
  },
  cliPath: {
    name: "Claude CLI \u8DEF\u5F91",
    desc: "Claude Code CLI \u7684\u81EA\u8A02\u8DEF\u5F91\u3002\u7559\u7A7A\u4F7F\u7528\u81EA\u52D5\u6AA2\u6E2C\u3002",
    descWindows: "\u5C0D\u65BC\u539F\u751F\u5B89\u88DD\u7A0B\u5F0F\uFF0C\u4F7F\u7528 claude.exe\u3002\u5C0D\u65BC npm/pnpm/yarn \u6216\u5176\u4ED6\u5957\u4EF6\u7BA1\u7406\u5668\u5B89\u88DD\uFF0C\u4F7F\u7528 cli.js \u8DEF\u5F91\uFF08\u4E0D\u662F claude.cmd\uFF09\u3002",
    descUnix: '\u8CBC\u4E0A "which claude" \u7684\u8F38\u51FA - \u9069\u7528\u65BC\u539F\u751F\u5B89\u88DD\u548C npm/pnpm/yarn \u5B89\u88DD\u3002',
    validation: {
      notExist: "\u8DEF\u5F91\u4E0D\u5B58\u5728",
      isDirectory: "\u8DEF\u5F91\u662F\u76EE\u9304\uFF0C\u4E0D\u662F\u6A94\u6848"
    }
  },
  language: {
    name: "\u8A9E\u8A00",
    desc: "\u66F4\u6539\u63D2\u4EF6\u4ECB\u9762\u7684\u986F\u793A\u8A9E\u8A00"
  }
};
var zh_TW_default = {
  common: common10,
  chat: chat10,
  settings: settings10
};

// src/i18n/i18n.ts
var translations = {
  en: en_exports,
  "zh-CN": zh_CN_exports,
  "zh-TW": zh_TW_exports,
  ja: ja_exports,
  ko: ko_exports,
  de: de_exports,
  fr: fr_exports,
  es: es_exports,
  ru: ru_exports,
  pt: pt_exports
};
var DEFAULT_LOCALE = "en";
var currentLocale = DEFAULT_LOCALE;
function t(key, params) {
  const dict = translations[currentLocale];
  const keys = key.split(".");
  let value = dict;
  for (const k10 of keys) {
    if (value && typeof value === "object" && k10 in value) {
      value = value[k10];
    } else {
      if (currentLocale !== DEFAULT_LOCALE) {
        return tFallback(key, params);
      }
      return key;
    }
  }
  if (typeof value !== "string") {
    return key;
  }
  if (params) {
    return value.replace(/\{(\w+)\}/g, (_10, param) => {
      var _a3, _b2;
      return (_b2 = (_a3 = params[param]) == null ? void 0 : _a3.toString()) != null ? _b2 : `{${param}}`;
    });
  }
  return value;
}
function tFallback(key, params) {
  const dict = translations[DEFAULT_LOCALE];
  const keys = key.split(".");
  let value = dict;
  for (const k10 of keys) {
    if (value && typeof value === "object" && k10 in value) {
      value = value[k10];
    } else {
      return key;
    }
  }
  if (typeof value !== "string") {
    return key;
  }
  if (params) {
    return value.replace(/\{(\w+)\}/g, (_10, param) => {
      var _a3, _b2;
      return (_b2 = (_a3 = params[param]) == null ? void 0 : _a3.toString()) != null ? _b2 : `{${param}}`;
    });
  }
  return value;
}
function setLocale(locale) {
  if (!translations[locale]) {
    return false;
  }
  currentLocale = locale;
  return true;
}
function getAvailableLocales() {
  return Object.keys(translations);
}
function getLocaleDisplayName(locale) {
  const names = {
    "en": "English",
    "zh-CN": "\u7B80\u4F53\u4E2D\u6587",
    "zh-TW": "\u7E41\u9AD4\u4E2D\u6587",
    "ja": "\u65E5\u672C\u8A9E",
    "ko": "\uD55C\uAD6D\uC5B4",
    "de": "Deutsch",
    "fr": "Fran\xE7ais",
    "es": "Espa\xF1ol",
    "ru": "\u0420\u0443\u0441\u0441\u043A\u0438\u0439",
    "pt": "Portugu\xEAs"
  };
  return names[locale] || locale;
}

// src/features/settings/ui/EnvSnippetManager.ts
init_env();
var EnvSnippetModal = class extends import_obsidian4.Modal {
  constructor(app, plugin, snippet, scope, onSave) {
    super(app);
    this.plugin = plugin;
    this.snippet = snippet;
    this.snippetScope = scope;
    this.onSave = onSave;
  }
  onOpen() {
    const { contentEl } = this;
    this.setTitle(this.snippet ? t("settings.envSnippets.modal.titleEdit") : t("settings.envSnippets.modal.titleSave"));
    this.modalEl.addClass("claudian-env-snippet-modal");
    let nameEl;
    let descEl;
    let envVarsEl;
    const contextLimitInputs = /* @__PURE__ */ new Map();
    let contextLimitsContainer = null;
    const handleKeyDown = (e2) => {
      if (e2.key === "Enter" && !e2.isComposing) {
        e2.preventDefault();
        saveSnippet();
      } else if (e2.key === "Escape" && !e2.isComposing) {
        e2.preventDefault();
        this.close();
      }
    };
    const saveSnippet = () => {
      var _a3, _b2, _c;
      const name = nameEl.value.trim();
      if (!name) {
        new import_obsidian4.Notice(t("settings.envSnippets.nameRequired"));
        return;
      }
      const contextLimits = {};
      for (const [modelId, input] of contextLimitInputs) {
        const value = input.value.trim();
        if (value) {
          const parsed = parseContextLimit(value);
          if (parsed !== null) {
            contextLimits[modelId] = parsed;
          }
        }
      }
      const snippet = {
        id: ((_a3 = this.snippet) == null ? void 0 : _a3.id) || `snippet-${Date.now()}`,
        name,
        description: descEl.value.trim(),
        envVars: envVarsEl.value,
        scope: resolveEnvironmentSnippetScope(
          envVarsEl.value,
          (_c = (_b2 = this.snippet) == null ? void 0 : _b2.scope) != null ? _c : this.snippetScope
        ),
        contextLimits: Object.keys(contextLimits).length > 0 ? contextLimits : void 0
      };
      this.onSave(snippet);
      this.close();
    };
    const renderContextLimitFields = () => {
      var _a3, _b2, _c;
      if (!contextLimitsContainer) return;
      contextLimitsContainer.empty();
      contextLimitInputs.clear();
      const envVars = parseEnvironmentVariables(envVarsEl.value);
      const uniqueModelIds = ProviderRegistry.getCustomModelIds(envVars);
      if (uniqueModelIds.size === 0) {
        contextLimitsContainer.style.display = "none";
        return;
      }
      contextLimitsContainer.style.display = "block";
      const existingLimits = (_c = (_b2 = (_a3 = this.snippet) == null ? void 0 : _a3.contextLimits) != null ? _b2 : this.plugin.settings.customContextLimits) != null ? _c : {};
      contextLimitsContainer.createEl("div", {
        text: t("settings.customContextLimits.name"),
        cls: "setting-item-name"
      });
      contextLimitsContainer.createEl("div", {
        text: t("settings.customContextLimits.desc"),
        cls: "setting-item-description"
      });
      for (const modelId of uniqueModelIds) {
        const row = contextLimitsContainer.createDiv({ cls: "claudian-snippet-limit-row" });
        row.createSpan({ text: modelId, cls: "claudian-snippet-limit-model" });
        row.createSpan({ cls: "claudian-snippet-limit-spacer" });
        const input = row.createEl("input", {
          type: "text",
          placeholder: "200k",
          cls: "claudian-snippet-limit-input"
        });
        input.value = existingLimits[modelId] ? formatContextLimit(existingLimits[modelId]) : "";
        contextLimitInputs.set(modelId, input);
      }
    };
    new import_obsidian4.Setting(contentEl).setName(t("settings.envSnippets.modal.name")).setDesc(t("settings.envSnippets.modal.namePlaceholder")).addText((text) => {
      var _a3;
      nameEl = text.inputEl;
      text.setValue(((_a3 = this.snippet) == null ? void 0 : _a3.name) || "");
      text.inputEl.addEventListener("keydown", handleKeyDown);
    });
    new import_obsidian4.Setting(contentEl).setName(t("settings.envSnippets.modal.description")).setDesc(t("settings.envSnippets.modal.descPlaceholder")).addText((text) => {
      var _a3;
      descEl = text.inputEl;
      text.setValue(((_a3 = this.snippet) == null ? void 0 : _a3.description) || "");
      text.inputEl.addEventListener("keydown", handleKeyDown);
    });
    const envVarsSetting = new import_obsidian4.Setting(contentEl).setName(t("settings.envSnippets.modal.envVars")).setDesc(t("settings.envSnippets.modal.envVarsPlaceholder")).addTextArea((text) => {
      var _a3, _b2;
      envVarsEl = text.inputEl;
      const envVarsToShow = (_b2 = (_a3 = this.snippet) == null ? void 0 : _a3.envVars) != null ? _b2 : this.plugin.getEnvironmentVariablesForScope(this.snippetScope);
      text.setValue(envVarsToShow);
      text.inputEl.rows = 8;
      text.inputEl.addEventListener("blur", () => renderContextLimitFields());
    });
    envVarsSetting.settingEl.addClass("claudian-env-snippet-setting");
    envVarsSetting.controlEl.addClass("claudian-env-snippet-control");
    contextLimitsContainer = contentEl.createDiv({ cls: "claudian-snippet-context-limits" });
    renderContextLimitFields();
    const buttonContainer = contentEl.createDiv({ cls: "claudian-snippet-buttons" });
    const cancelBtn = buttonContainer.createEl("button", {
      text: t("settings.envSnippets.modal.cancel"),
      cls: "claudian-cancel-btn"
    });
    cancelBtn.addEventListener("click", () => this.close());
    const saveBtn = buttonContainer.createEl("button", {
      text: this.snippet ? t("settings.envSnippets.modal.update") : t("settings.envSnippets.modal.save"),
      cls: "claudian-save-btn"
    });
    saveBtn.addEventListener("click", () => saveSnippet());
    setTimeout(() => nameEl == null ? void 0 : nameEl.focus(), 50);
  }
  onClose() {
    const { contentEl } = this;
    contentEl.empty();
  }
};
var EnvSnippetManager = class {
  constructor(containerEl, plugin, scope, onContextLimitsChange) {
    this.containerEl = containerEl;
    this.plugin = plugin;
    this.scope = scope;
    this.onContextLimitsChange = onContextLimitsChange;
    this.render();
  }
  render() {
    this.containerEl.empty();
    const headerEl = this.containerEl.createDiv({ cls: "claudian-snippet-header" });
    headerEl.createSpan({ text: t("settings.envSnippets.name"), cls: "claudian-snippet-label" });
    const saveBtn = headerEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": t("settings.envSnippets.addBtn") }
    });
    (0, import_obsidian4.setIcon)(saveBtn, "plus");
    saveBtn.addEventListener("click", () => this.saveCurrentEnv());
    const snippets = this.plugin.settings.envSnippets.filter((snippet) => this.shouldDisplaySnippet(snippet));
    if (snippets.length === 0) {
      const emptyEl = this.containerEl.createDiv({ cls: "claudian-snippet-empty" });
      emptyEl.setText(t("settings.envSnippets.noSnippets"));
      return;
    }
    const listEl = this.containerEl.createDiv({ cls: "claudian-snippet-list" });
    for (const snippet of snippets) {
      const itemEl = listEl.createDiv({ cls: "claudian-snippet-item" });
      const infoEl = itemEl.createDiv({ cls: "claudian-snippet-info" });
      const nameEl = infoEl.createDiv({ cls: "claudian-snippet-name" });
      nameEl.setText(snippet.name);
      if (snippet.description) {
        const descEl = infoEl.createDiv({ cls: "claudian-snippet-description" });
        descEl.setText(snippet.description);
      }
      const actionsEl = itemEl.createDiv({ cls: "claudian-snippet-actions" });
      const restoreBtn = actionsEl.createEl("button", {
        cls: "claudian-settings-action-btn",
        attr: { "aria-label": "Insert" }
      });
      (0, import_obsidian4.setIcon)(restoreBtn, "clipboard-paste");
      restoreBtn.addEventListener("click", async () => {
        try {
          await this.insertSnippet(snippet);
        } catch (e2) {
          new import_obsidian4.Notice("Failed to insert snippet");
        }
      });
      const editBtn = actionsEl.createEl("button", {
        cls: "claudian-settings-action-btn",
        attr: { "aria-label": "Edit" }
      });
      (0, import_obsidian4.setIcon)(editBtn, "pencil");
      editBtn.addEventListener("click", () => {
        this.editSnippet(snippet);
      });
      const deleteBtn = actionsEl.createEl("button", {
        cls: "claudian-settings-action-btn claudian-settings-delete-btn",
        attr: { "aria-label": "Delete" }
      });
      (0, import_obsidian4.setIcon)(deleteBtn, "trash-2");
      deleteBtn.addEventListener("click", async () => {
        try {
          if (confirm(`Delete environment snippet "${snippet.name}"?`)) {
            await this.deleteSnippet(snippet);
          }
        } catch (e2) {
          new import_obsidian4.Notice("Failed to delete snippet");
        }
      });
    }
  }
  async saveCurrentEnv() {
    const modal = new EnvSnippetModal(
      this.plugin.app,
      this.plugin,
      null,
      this.scope,
      async (snippet) => {
        this.plugin.settings.envSnippets.push(snippet);
        await this.plugin.saveSettings();
        this.render();
        new import_obsidian4.Notice(`Environment snippet "${snippet.name}" saved`);
      }
    );
    modal.open();
  }
  async insertSnippet(snippet) {
    var _a3, _b2, _c;
    const snippetContent = snippet.envVars.trim();
    const updates = getEnvironmentScopeUpdates(
      snippetContent,
      (_a3 = snippet.scope) != null ? _a3 : this.scope
    );
    if (updates.length === 1) {
      const [update] = updates;
      this.syncTextareaValue(update.scope, update.envText);
      await this.plugin.applyEnvironmentVariables(update.scope, update.envText);
    } else if (updates.length > 1) {
      for (const update of updates) {
        this.syncTextareaValue(update.scope, update.envText);
      }
      await this.plugin.applyEnvironmentVariablesBatch(updates);
    }
    if (snippet.contextLimits) {
      this.plugin.settings.customContextLimits = {
        ...this.plugin.settings.customContextLimits,
        ...snippet.contextLimits
      };
    }
    await this.plugin.saveSettings();
    (_b2 = this.onContextLimitsChange) == null ? void 0 : _b2.call(this);
    const view = (_c = this.plugin.app.workspace.getLeavesOfType("claudian-view")[0]) == null ? void 0 : _c.view;
    view == null ? void 0 : view.refreshModelSelector();
  }
  editSnippet(snippet) {
    const modal = new EnvSnippetModal(
      this.plugin.app,
      this.plugin,
      snippet,
      this.scope,
      async (updatedSnippet) => {
        const index = this.plugin.settings.envSnippets.findIndex((s4) => s4.id === snippet.id);
        if (index !== -1) {
          this.plugin.settings.envSnippets[index] = updatedSnippet;
          await this.plugin.saveSettings();
          this.render();
          new import_obsidian4.Notice(`Environment snippet "${updatedSnippet.name}" updated`);
        }
      }
    );
    modal.open();
  }
  async deleteSnippet(snippet) {
    this.plugin.settings.envSnippets = this.plugin.settings.envSnippets.filter((s4) => s4.id !== snippet.id);
    await this.plugin.saveSettings();
    this.render();
    new import_obsidian4.Notice(`Environment snippet "${snippet.name}" deleted`);
  }
  refresh() {
    this.render();
  }
  shouldDisplaySnippet(snippet) {
    if (this.scope === "shared") {
      return !snippet.scope || snippet.scope === "shared";
    }
    return snippet.scope === this.scope;
  }
  syncTextareaValue(scope, value) {
    const selector = `.claudian-settings-env-textarea[data-env-scope="${scope}"]`;
    const envTextarea = document.querySelector(selector);
    if (envTextarea) {
      envTextarea.value = value;
    }
  }
};

// src/features/settings/ui/EnvironmentSettingsSection.ts
function renderEnvironmentSettingsSection(options) {
  const {
    container,
    plugin,
    scope,
    heading,
    name,
    desc,
    placeholder,
    renderCustomContextLimits
  } = options;
  if (heading) {
    new import_obsidian5.Setting(container).setName(heading).setHeading();
  }
  let envTextarea = null;
  const reviewEl = container.createDiv({ cls: "claudian-env-review-warning" });
  reviewEl.style.color = "var(--text-warning)";
  reviewEl.style.fontSize = "0.85em";
  reviewEl.style.marginTop = "-0.5em";
  reviewEl.style.marginBottom = "0.5em";
  reviewEl.style.display = "none";
  const updateReviewWarning = () => {
    var _a3;
    const reviewKeys = getEnvironmentReviewKeysForScope((_a3 = envTextarea == null ? void 0 : envTextarea.value) != null ? _a3 : "", scope);
    if (reviewKeys.length === 0) {
      reviewEl.style.display = "none";
      reviewEl.empty();
      return;
    }
    reviewEl.setText(`Review environment ownership for: ${reviewKeys.join(", ")}`);
    reviewEl.style.display = "block";
  };
  new import_obsidian5.Setting(container).setName(name).setDesc(desc).addTextArea((text) => {
    text.setPlaceholder(placeholder).setValue(plugin.getEnvironmentVariablesForScope(scope));
    text.inputEl.rows = 6;
    text.inputEl.cols = 50;
    text.inputEl.addClass("claudian-settings-env-textarea");
    text.inputEl.dataset.envScope = scope;
    text.inputEl.addEventListener("input", () => updateReviewWarning());
    text.inputEl.addEventListener("blur", async () => {
      await plugin.applyEnvironmentVariables(scope, text.inputEl.value);
      renderCustomContextLimits == null ? void 0 : renderCustomContextLimits(contextLimitsContainer);
      updateReviewWarning();
    });
    envTextarea = text.inputEl;
  });
  updateReviewWarning();
  const contextLimitsContainer = container.createDiv({ cls: "claudian-context-limits-container" });
  renderCustomContextLimits == null ? void 0 : renderCustomContextLimits(contextLimitsContainer);
  const envSnippetsContainer = container.createDiv({ cls: "claudian-env-snippets-container" });
  new EnvSnippetManager(envSnippetsContainer, plugin, scope, () => {
    renderCustomContextLimits == null ? void 0 : renderCustomContextLimits(contextLimitsContainer);
  });
}

// src/features/settings/ui/McpSettingsManager.ts
var import_obsidian8 = require("obsidian");

// src/core/mcp/McpConfigParser.ts
function parseClipboardConfig(json2) {
  try {
    const parsed = JSON.parse(json2);
    if (!parsed || typeof parsed !== "object") {
      throw new Error("Invalid JSON object");
    }
    if (parsed.mcpServers && typeof parsed.mcpServers === "object") {
      const servers2 = [];
      for (const [name, config2] of Object.entries(parsed.mcpServers)) {
        if (isValidMcpServerConfig(config2)) {
          servers2.push({ name, config: config2 });
        }
      }
      if (servers2.length === 0) {
        throw new Error("No valid server configs found in mcpServers");
      }
      return { servers: servers2, needsName: false };
    }
    if (isValidMcpServerConfig(parsed)) {
      return {
        servers: [{ name: "", config: parsed }],
        needsName: true
      };
    }
    const entries = Object.entries(parsed);
    if (entries.length === 1) {
      const [name, config2] = entries[0];
      if (isValidMcpServerConfig(config2)) {
        return {
          servers: [{ name, config: config2 }],
          needsName: false
        };
      }
    }
    const servers = [];
    for (const [name, config2] of entries) {
      if (isValidMcpServerConfig(config2)) {
        servers.push({ name, config: config2 });
      }
    }
    if (servers.length > 0) {
      return { servers, needsName: false };
    }
    throw new Error("Invalid MCP configuration format");
  } catch (error48) {
    if (error48 instanceof SyntaxError) {
      throw new Error("Invalid JSON", { cause: error48 });
    }
    throw error48;
  }
}
function tryParseClipboardConfig(text) {
  const trimmed = text.trim();
  if (!trimmed.startsWith("{")) {
    return null;
  }
  try {
    return parseClipboardConfig(trimmed);
  } catch (e2) {
    return null;
  }
}

// node_modules/zod/v3/helpers/util.js
var util;
(function(util2) {
  util2.assertEqual = (_10) => {
  };
  function assertIs2(_arg) {
  }
  util2.assertIs = assertIs2;
  function assertNever2(_x) {
    throw new Error();
  }
  util2.assertNever = assertNever2;
  util2.arrayToEnum = (items) => {
    const obj = {};
    for (const item of items) {
      obj[item] = item;
    }
    return obj;
  };
  util2.getValidEnumValues = (obj) => {
    const validKeys = util2.objectKeys(obj).filter((k10) => typeof obj[obj[k10]] !== "number");
    const filtered = {};
    for (const k10 of validKeys) {
      filtered[k10] = obj[k10];
    }
    return util2.objectValues(filtered);
  };
  util2.objectValues = (obj) => {
    return util2.objectKeys(obj).map(function(e2) {
      return obj[e2];
    });
  };
  util2.objectKeys = typeof Object.keys === "function" ? (obj) => Object.keys(obj) : (object3) => {
    const keys = [];
    for (const key in object3) {
      if (Object.prototype.hasOwnProperty.call(object3, key)) {
        keys.push(key);
      }
    }
    return keys;
  };
  util2.find = (arr, checker) => {
    for (const item of arr) {
      if (checker(item))
        return item;
    }
    return void 0;
  };
  util2.isInteger = typeof Number.isInteger === "function" ? (val) => Number.isInteger(val) : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val;
  function joinValues2(array2, separator = " | ") {
    return array2.map((val) => typeof val === "string" ? `'${val}'` : val).join(separator);
  }
  util2.joinValues = joinValues2;
  util2.jsonStringifyReplacer = (_10, value) => {
    if (typeof value === "bigint") {
      return value.toString();
    }
    return value;
  };
})(util || (util = {}));
var objectUtil;
(function(objectUtil2) {
  objectUtil2.mergeShapes = (first, second) => {
    return {
      ...first,
      ...second
      // second overwrites first
    };
  };
})(objectUtil || (objectUtil = {}));
var ZodParsedType = util.arrayToEnum([
  "string",
  "nan",
  "number",
  "integer",
  "float",
  "boolean",
  "date",
  "bigint",
  "symbol",
  "function",
  "undefined",
  "null",
  "array",
  "object",
  "unknown",
  "promise",
  "void",
  "never",
  "map",
  "set"
]);
var getParsedType = (data) => {
  const t2 = typeof data;
  switch (t2) {
    case "undefined":
      return ZodParsedType.undefined;
    case "string":
      return ZodParsedType.string;
    case "number":
      return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;
    case "boolean":
      return ZodParsedType.boolean;
    case "function":
      return ZodParsedType.function;
    case "bigint":
      return ZodParsedType.bigint;
    case "symbol":
      return ZodParsedType.symbol;
    case "object":
      if (Array.isArray(data)) {
        return ZodParsedType.array;
      }
      if (data === null) {
        return ZodParsedType.null;
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return ZodParsedType.promise;
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return ZodParsedType.map;
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return ZodParsedType.set;
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return ZodParsedType.date;
      }
      return ZodParsedType.object;
    default:
      return ZodParsedType.unknown;
  }
};

// node_modules/zod/v3/ZodError.js
var ZodIssueCode = util.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"
]);
var ZodError = class _ZodError extends Error {
  get errors() {
    return this.issues;
  }
  constructor(issues) {
    super();
    this.issues = [];
    this.addIssue = (sub) => {
      this.issues = [...this.issues, sub];
    };
    this.addIssues = (subs = []) => {
      this.issues = [...this.issues, ...subs];
    };
    const actualProto = new.target.prototype;
    if (Object.setPrototypeOf) {
      Object.setPrototypeOf(this, actualProto);
    } else {
      this.__proto__ = actualProto;
    }
    this.name = "ZodError";
    this.issues = issues;
  }
  format(_mapper) {
    const mapper = _mapper || function(issue2) {
      return issue2.message;
    };
    const fieldErrors = { _errors: [] };
    const processError = (error48) => {
      for (const issue2 of error48.issues) {
        if (issue2.code === "invalid_union") {
          issue2.unionErrors.map(processError);
        } else if (issue2.code === "invalid_return_type") {
          processError(issue2.returnTypeError);
        } else if (issue2.code === "invalid_arguments") {
          processError(issue2.argumentsError);
        } else if (issue2.path.length === 0) {
          fieldErrors._errors.push(mapper(issue2));
        } else {
          let curr = fieldErrors;
          let i2 = 0;
          while (i2 < issue2.path.length) {
            const el = issue2.path[i2];
            const terminal = i2 === issue2.path.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue2));
            }
            curr = curr[el];
            i2++;
          }
        }
      }
    };
    processError(this);
    return fieldErrors;
  }
  static assert(value) {
    if (!(value instanceof _ZodError)) {
      throw new Error(`Not a ZodError: ${value}`);
    }
  }
  toString() {
    return this.message;
  }
  get message() {
    return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);
  }
  get isEmpty() {
    return this.issues.length === 0;
  }
  flatten(mapper = (issue2) => issue2.message) {
    const fieldErrors = /* @__PURE__ */ Object.create(null);
    const formErrors = [];
    for (const sub of this.issues) {
      if (sub.path.length > 0) {
        const firstEl = sub.path[0];
        fieldErrors[firstEl] = fieldErrors[firstEl] || [];
        fieldErrors[firstEl].push(mapper(sub));
      } else {
        formErrors.push(mapper(sub));
      }
    }
    return { formErrors, fieldErrors };
  }
  get formErrors() {
    return this.flatten();
  }
};
ZodError.create = (issues) => {
  const error48 = new ZodError(issues);
  return error48;
};

// node_modules/zod/v3/locales/en.js
var errorMap = (issue2, _ctx) => {
  let message;
  switch (issue2.code) {
    case ZodIssueCode.invalid_type:
      if (issue2.received === ZodParsedType.undefined) {
        message = "Required";
      } else {
        message = `Expected ${issue2.expected}, received ${issue2.received}`;
      }
      break;
    case ZodIssueCode.invalid_literal:
      message = `Invalid literal value, expected ${JSON.stringify(issue2.expected, util.jsonStringifyReplacer)}`;
      break;
    case ZodIssueCode.unrecognized_keys:
      message = `Unrecognized key(s) in object: ${util.joinValues(issue2.keys, ", ")}`;
      break;
    case ZodIssueCode.invalid_union:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_union_discriminator:
      message = `Invalid discriminator value. Expected ${util.joinValues(issue2.options)}`;
      break;
    case ZodIssueCode.invalid_enum_value:
      message = `Invalid enum value. Expected ${util.joinValues(issue2.options)}, received '${issue2.received}'`;
      break;
    case ZodIssueCode.invalid_arguments:
      message = `Invalid function arguments`;
      break;
    case ZodIssueCode.invalid_return_type:
      message = `Invalid function return type`;
      break;
    case ZodIssueCode.invalid_date:
      message = `Invalid date`;
      break;
    case ZodIssueCode.invalid_string:
      if (typeof issue2.validation === "object") {
        if ("includes" in issue2.validation) {
          message = `Invalid input: must include "${issue2.validation.includes}"`;
          if (typeof issue2.validation.position === "number") {
            message = `${message} at one or more positions greater than or equal to ${issue2.validation.position}`;
          }
        } else if ("startsWith" in issue2.validation) {
          message = `Invalid input: must start with "${issue2.validation.startsWith}"`;
        } else if ("endsWith" in issue2.validation) {
          message = `Invalid input: must end with "${issue2.validation.endsWith}"`;
        } else {
          util.assertNever(issue2.validation);
        }
      } else if (issue2.validation !== "regex") {
        message = `Invalid ${issue2.validation}`;
      } else {
        message = "Invalid";
      }
      break;
    case ZodIssueCode.too_small:
      if (issue2.type === "array")
        message = `Array must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `more than`} ${issue2.minimum} element(s)`;
      else if (issue2.type === "string")
        message = `String must contain ${issue2.exact ? "exactly" : issue2.inclusive ? `at least` : `over`} ${issue2.minimum} character(s)`;
      else if (issue2.type === "number")
        message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
      else if (issue2.type === "bigint")
        message = `Number must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${issue2.minimum}`;
      else if (issue2.type === "date")
        message = `Date must be ${issue2.exact ? `exactly equal to ` : issue2.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue2.minimum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.too_big:
      if (issue2.type === "array")
        message = `Array must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `less than`} ${issue2.maximum} element(s)`;
      else if (issue2.type === "string")
        message = `String must contain ${issue2.exact ? `exactly` : issue2.inclusive ? `at most` : `under`} ${issue2.maximum} character(s)`;
      else if (issue2.type === "number")
        message = `Number must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
      else if (issue2.type === "bigint")
        message = `BigInt must be ${issue2.exact ? `exactly` : issue2.inclusive ? `less than or equal to` : `less than`} ${issue2.maximum}`;
      else if (issue2.type === "date")
        message = `Date must be ${issue2.exact ? `exactly` : issue2.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue2.maximum))}`;
      else
        message = "Invalid input";
      break;
    case ZodIssueCode.custom:
      message = `Invalid input`;
      break;
    case ZodIssueCode.invalid_intersection_types:
      message = `Intersection results could not be merged`;
      break;
    case ZodIssueCode.not_multiple_of:
      message = `Number must be a multiple of ${issue2.multipleOf}`;
      break;
    case ZodIssueCode.not_finite:
      message = "Number must be finite";
      break;
    default:
      message = _ctx.defaultError;
      util.assertNever(issue2);
  }
  return { message };
};
var en_default2 = errorMap;

// node_modules/zod/v3/errors.js
var overrideErrorMap = en_default2;
function getErrorMap() {
  return overrideErrorMap;
}

// node_modules/zod/v3/helpers/parseUtil.js
var makeIssue = (params) => {
  const { data, path: path24, errorMaps, issueData } = params;
  const fullPath = [...path24, ...issueData.path || []];
  const fullIssue = {
    ...issueData,
    path: fullPath
  };
  if (issueData.message !== void 0) {
    return {
      ...issueData,
      path: fullPath,
      message: issueData.message
    };
  }
  let errorMessage = "";
  const maps = errorMaps.filter((m2) => !!m2).slice().reverse();
  for (const map2 of maps) {
    errorMessage = map2(fullIssue, { data, defaultError: errorMessage }).message;
  }
  return {
    ...issueData,
    path: fullPath,
    message: errorMessage
  };
};
function addIssueToContext(ctx, issueData) {
  const overrideMap = getErrorMap();
  const issue2 = makeIssue({
    issueData,
    data: ctx.data,
    path: ctx.path,
    errorMaps: [
      ctx.common.contextualErrorMap,
      // contextual error map is first priority
      ctx.schemaErrorMap,
      // then schema-bound map if available
      overrideMap,
      // then global override map
      overrideMap === en_default2 ? void 0 : en_default2
      // then global default map
    ].filter((x) => !!x)
  });
  ctx.common.issues.push(issue2);
}
var ParseStatus = class _ParseStatus {
  constructor() {
    this.value = "valid";
  }
  dirty() {
    if (this.value === "valid")
      this.value = "dirty";
  }
  abort() {
    if (this.value !== "aborted")
      this.value = "aborted";
  }
  static mergeArray(status, results) {
    const arrayValue = [];
    for (const s4 of results) {
      if (s4.status === "aborted")
        return INVALID;
      if (s4.status === "dirty")
        status.dirty();
      arrayValue.push(s4.value);
    }
    return { status: status.value, value: arrayValue };
  }
  static async mergeObjectAsync(status, pairs) {
    const syncPairs = [];
    for (const pair of pairs) {
      const key = await pair.key;
      const value = await pair.value;
      syncPairs.push({
        key,
        value
      });
    }
    return _ParseStatus.mergeObjectSync(status, syncPairs);
  }
  static mergeObjectSync(status, pairs) {
    const finalObject = {};
    for (const pair of pairs) {
      const { key, value } = pair;
      if (key.status === "aborted")
        return INVALID;
      if (value.status === "aborted")
        return INVALID;
      if (key.status === "dirty")
        status.dirty();
      if (value.status === "dirty")
        status.dirty();
      if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) {
        finalObject[key.value] = value.value;
      }
    }
    return { status: status.value, value: finalObject };
  }
};
var INVALID = Object.freeze({
  status: "aborted"
});
var DIRTY = (value) => ({ status: "dirty", value });
var OK2 = (value) => ({ status: "valid", value });
var isAborted = (x) => x.status === "aborted";
var isDirty = (x) => x.status === "dirty";
var isValid = (x) => x.status === "valid";
var isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise;

// node_modules/zod/v3/helpers/errorUtil.js
var errorUtil;
(function(errorUtil2) {
  errorUtil2.errToObj = (message) => typeof message === "string" ? { message } : message || {};
  errorUtil2.toString = (message) => typeof message === "string" ? message : message == null ? void 0 : message.message;
})(errorUtil || (errorUtil = {}));

// node_modules/zod/v3/types.js
var ParseInputLazyPath = class {
  constructor(parent, value, path24, key) {
    this._cachedPath = [];
    this.parent = parent;
    this.data = value;
    this._path = path24;
    this._key = key;
  }
  get path() {
    if (!this._cachedPath.length) {
      if (Array.isArray(this._key)) {
        this._cachedPath.push(...this._path, ...this._key);
      } else {
        this._cachedPath.push(...this._path, this._key);
      }
    }
    return this._cachedPath;
  }
};
var handleResult = (ctx, result) => {
  if (isValid(result)) {
    return { success: true, data: result.value };
  } else {
    if (!ctx.common.issues.length) {
      throw new Error("Validation failed but no issues detected.");
    }
    return {
      success: false,
      get error() {
        if (this._error)
          return this._error;
        const error48 = new ZodError(ctx.common.issues);
        this._error = error48;
        return this._error;
      }
    };
  }
};
function processCreateParams(params) {
  if (!params)
    return {};
  const { errorMap: errorMap2, invalid_type_error, required_error, description } = params;
  if (errorMap2 && (invalid_type_error || required_error)) {
    throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);
  }
  if (errorMap2)
    return { errorMap: errorMap2, description };
  const customMap = (iss, ctx) => {
    var _a3, _b2;
    const { message } = params;
    if (iss.code === "invalid_enum_value") {
      return { message: message != null ? message : ctx.defaultError };
    }
    if (typeof ctx.data === "undefined") {
      return { message: (_a3 = message != null ? message : required_error) != null ? _a3 : ctx.defaultError };
    }
    if (iss.code !== "invalid_type")
      return { message: ctx.defaultError };
    return { message: (_b2 = message != null ? message : invalid_type_error) != null ? _b2 : ctx.defaultError };
  };
  return { errorMap: customMap, description };
}
var ZodType = class {
  get description() {
    return this._def.description;
  }
  _getType(input) {
    return getParsedType(input.data);
  }
  _getOrReturnCtx(input, ctx) {
    return ctx || {
      common: input.parent.common,
      data: input.data,
      parsedType: getParsedType(input.data),
      schemaErrorMap: this._def.errorMap,
      path: input.path,
      parent: input.parent
    };
  }
  _processInputParams(input) {
    return {
      status: new ParseStatus(),
      ctx: {
        common: input.parent.common,
        data: input.data,
        parsedType: getParsedType(input.data),
        schemaErrorMap: this._def.errorMap,
        path: input.path,
        parent: input.parent
      }
    };
  }
  _parseSync(input) {
    const result = this._parse(input);
    if (isAsync(result)) {
      throw new Error("Synchronous parse encountered promise.");
    }
    return result;
  }
  _parseAsync(input) {
    const result = this._parse(input);
    return Promise.resolve(result);
  }
  parse(data, params) {
    const result = this.safeParse(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  safeParse(data, params) {
    var _a3;
    const ctx = {
      common: {
        issues: [],
        async: (_a3 = params == null ? void 0 : params.async) != null ? _a3 : false,
        contextualErrorMap: params == null ? void 0 : params.errorMap
      },
      path: (params == null ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const result = this._parseSync({ data, path: ctx.path, parent: ctx });
    return handleResult(ctx, result);
  }
  "~validate"(data) {
    var _a3, _b2;
    const ctx = {
      common: {
        issues: [],
        async: !!this["~standard"].async
      },
      path: [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    if (!this["~standard"].async) {
      try {
        const result = this._parseSync({ data, path: [], parent: ctx });
        return isValid(result) ? {
          value: result.value
        } : {
          issues: ctx.common.issues
        };
      } catch (err) {
        if ((_b2 = (_a3 = err == null ? void 0 : err.message) == null ? void 0 : _a3.toLowerCase()) == null ? void 0 : _b2.includes("encountered")) {
          this["~standard"].async = true;
        }
        ctx.common = {
          issues: [],
          async: true
        };
      }
    }
    return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) ? {
      value: result.value
    } : {
      issues: ctx.common.issues
    });
  }
  async parseAsync(data, params) {
    const result = await this.safeParseAsync(data, params);
    if (result.success)
      return result.data;
    throw result.error;
  }
  async safeParseAsync(data, params) {
    const ctx = {
      common: {
        issues: [],
        contextualErrorMap: params == null ? void 0 : params.errorMap,
        async: true
      },
      path: (params == null ? void 0 : params.path) || [],
      schemaErrorMap: this._def.errorMap,
      parent: null,
      data,
      parsedType: getParsedType(data)
    };
    const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });
    const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));
    return handleResult(ctx, result);
  }
  refine(check2, message) {
    const getIssueProperties = (val) => {
      if (typeof message === "string" || typeof message === "undefined") {
        return { message };
      } else if (typeof message === "function") {
        return message(val);
      } else {
        return message;
      }
    };
    return this._refinement((val, ctx) => {
      const result = check2(val);
      const setError = () => ctx.addIssue({
        code: ZodIssueCode.custom,
        ...getIssueProperties(val)
      });
      if (typeof Promise !== "undefined" && result instanceof Promise) {
        return result.then((data) => {
          if (!data) {
            setError();
            return false;
          } else {
            return true;
          }
        });
      }
      if (!result) {
        setError();
        return false;
      } else {
        return true;
      }
    });
  }
  refinement(check2, refinementData) {
    return this._refinement((val, ctx) => {
      if (!check2(val)) {
        ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData);
        return false;
      } else {
        return true;
      }
    });
  }
  _refinement(refinement) {
    return new ZodEffects({
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "refinement", refinement }
    });
  }
  superRefine(refinement) {
    return this._refinement(refinement);
  }
  constructor(def) {
    this.spa = this.safeParseAsync;
    this._def = def;
    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: (data) => this["~validate"](data)
    };
  }
  optional() {
    return ZodOptional.create(this, this._def);
  }
  nullable() {
    return ZodNullable.create(this, this._def);
  }
  nullish() {
    return this.nullable().optional();
  }
  array() {
    return ZodArray.create(this);
  }
  promise() {
    return ZodPromise.create(this, this._def);
  }
  or(option) {
    return ZodUnion.create([this, option], this._def);
  }
  and(incoming) {
    return ZodIntersection.create(this, incoming, this._def);
  }
  transform(transform2) {
    return new ZodEffects({
      ...processCreateParams(this._def),
      schema: this,
      typeName: ZodFirstPartyTypeKind.ZodEffects,
      effect: { type: "transform", transform: transform2 }
    });
  }
  default(def) {
    const defaultValueFunc = typeof def === "function" ? def : () => def;
    return new ZodDefault({
      ...processCreateParams(this._def),
      innerType: this,
      defaultValue: defaultValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodDefault
    });
  }
  brand() {
    return new ZodBranded({
      typeName: ZodFirstPartyTypeKind.ZodBranded,
      type: this,
      ...processCreateParams(this._def)
    });
  }
  catch(def) {
    const catchValueFunc = typeof def === "function" ? def : () => def;
    return new ZodCatch({
      ...processCreateParams(this._def),
      innerType: this,
      catchValue: catchValueFunc,
      typeName: ZodFirstPartyTypeKind.ZodCatch
    });
  }
  describe(description) {
    const This = this.constructor;
    return new This({
      ...this._def,
      description
    });
  }
  pipe(target) {
    return ZodPipeline.create(this, target);
  }
  readonly() {
    return ZodReadonly.create(this);
  }
  isOptional() {
    return this.safeParse(void 0).success;
  }
  isNullable() {
    return this.safeParse(null).success;
  }
};
var cuidRegex = /^c[^\s-]{8,}$/i;
var cuid2Regex = /^[0-9a-z]+$/;
var ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;
var uuidRegex = /^[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;
var nanoidRegex = /^[a-z0-9_-]{21}$/i;
var jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/;
var durationRegex = /^[-+]?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)?)??$/;
var emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;
var _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
var emojiRegex;
var ipv4Regex = /^(?:(?: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])$/;
var ipv4CidrRegex = /^(?:(?: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])$/;
var ipv6Regex = /^(([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]))$/;
var ipv6CidrRegex = /^(([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])$/;
var base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;
var base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;
var dateRegexSource = `((\\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])))`;
var dateRegex = new RegExp(`^${dateRegexSource}$`);
function timeRegexSource(args) {
  let secondsRegexSource = `[0-5]\\d`;
  if (args.precision) {
    secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`;
  } else if (args.precision == null) {
    secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`;
  }
  const secondsQuantifier = args.precision ? "+" : "?";
  return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`;
}
function timeRegex(args) {
  return new RegExp(`^${timeRegexSource(args)}$`);
}
function datetimeRegex(args) {
  let regex = `${dateRegexSource}T${timeRegexSource(args)}`;
  const opts = [];
  opts.push(args.local ? `Z?` : `Z`);
  if (args.offset)
    opts.push(`([+-]\\d{2}:?\\d{2})`);
  regex = `${regex}(${opts.join("|")})`;
  return new RegExp(`^${regex}$`);
}
function isValidIP(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4Regex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6Regex.test(ip)) {
    return true;
  }
  return false;
}
function isValidJWT(jwt2, alg) {
  if (!jwtRegex.test(jwt2))
    return false;
  try {
    const [header] = jwt2.split(".");
    if (!header)
      return false;
    const base643 = header.replace(/-/g, "+").replace(/_/g, "/").padEnd(header.length + (4 - header.length % 4) % 4, "=");
    const decoded = JSON.parse(atob(base643));
    if (typeof decoded !== "object" || decoded === null)
      return false;
    if ("typ" in decoded && (decoded == null ? void 0 : decoded.typ) !== "JWT")
      return false;
    if (!decoded.alg)
      return false;
    if (alg && decoded.alg !== alg)
      return false;
    return true;
  } catch (e2) {
    return false;
  }
}
function isValidCidr(ip, version2) {
  if ((version2 === "v4" || !version2) && ipv4CidrRegex.test(ip)) {
    return true;
  }
  if ((version2 === "v6" || !version2) && ipv6CidrRegex.test(ip)) {
    return true;
  }
  return false;
}
var ZodString = class _ZodString2 extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = String(input.data);
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.string) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.string,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check2 of this._def.checks) {
      if (check2.kind === "min") {
        if (input.data.length < check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check2.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        if (input.data.length > check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check2.value,
            type: "string",
            inclusive: true,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "length") {
        const tooBig = input.data.length > check2.value;
        const tooSmall = input.data.length < check2.value;
        if (tooBig || tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          if (tooBig) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_big,
              maximum: check2.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check2.message
            });
          } else if (tooSmall) {
            addIssueToContext(ctx, {
              code: ZodIssueCode.too_small,
              minimum: check2.value,
              type: "string",
              inclusive: true,
              exact: true,
              message: check2.message
            });
          }
          status.dirty();
        }
      } else if (check2.kind === "email") {
        if (!emailRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "email",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "emoji") {
        if (!emojiRegex) {
          emojiRegex = new RegExp(_emojiRegex, "u");
        }
        if (!emojiRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "emoji",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "uuid") {
        if (!uuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "uuid",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "nanoid") {
        if (!nanoidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "nanoid",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "cuid") {
        if (!cuidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "cuid2") {
        if (!cuid2Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cuid2",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "ulid") {
        if (!ulidRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ulid",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "url") {
        try {
          new URL(input.data);
        } catch (e2) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "url",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "regex") {
        check2.regex.lastIndex = 0;
        const testResult = check2.regex.test(input.data);
        if (!testResult) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "regex",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "trim") {
        input.data = input.data.trim();
      } else if (check2.kind === "includes") {
        if (!input.data.includes(check2.value, check2.position)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { includes: check2.value, position: check2.position },
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "toLowerCase") {
        input.data = input.data.toLowerCase();
      } else if (check2.kind === "toUpperCase") {
        input.data = input.data.toUpperCase();
      } else if (check2.kind === "startsWith") {
        if (!input.data.startsWith(check2.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { startsWith: check2.value },
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "endsWith") {
        if (!input.data.endsWith(check2.value)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: { endsWith: check2.value },
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "datetime") {
        const regex = datetimeRegex(check2);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "datetime",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "date") {
        const regex = dateRegex;
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "date",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "time") {
        const regex = timeRegex(check2);
        if (!regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_string,
            validation: "time",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "duration") {
        if (!durationRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "duration",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "ip") {
        if (!isValidIP(input.data, check2.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "ip",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "jwt") {
        if (!isValidJWT(input.data, check2.alg)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "jwt",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "cidr") {
        if (!isValidCidr(input.data, check2.version)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "cidr",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "base64") {
        if (!base64Regex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "base64url") {
        if (!base64urlRegex.test(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            validation: "base64url",
            code: ZodIssueCode.invalid_string,
            message: check2.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check2);
      }
    }
    return { status: status.value, value: input.data };
  }
  _regex(regex, validation, message) {
    return this.refinement((data) => regex.test(data), {
      validation,
      code: ZodIssueCode.invalid_string,
      ...errorUtil.errToObj(message)
    });
  }
  _addCheck(check2) {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  email(message) {
    return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) });
  }
  url(message) {
    return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) });
  }
  emoji(message) {
    return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) });
  }
  uuid(message) {
    return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) });
  }
  nanoid(message) {
    return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) });
  }
  cuid(message) {
    return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) });
  }
  cuid2(message) {
    return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) });
  }
  ulid(message) {
    return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) });
  }
  base64(message) {
    return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) });
  }
  base64url(message) {
    return this._addCheck({
      kind: "base64url",
      ...errorUtil.errToObj(message)
    });
  }
  jwt(options) {
    return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) });
  }
  ip(options) {
    return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) });
  }
  cidr(options) {
    return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) });
  }
  datetime(options) {
    var _a3, _b2;
    if (typeof options === "string") {
      return this._addCheck({
        kind: "datetime",
        precision: null,
        offset: false,
        local: false,
        message: options
      });
    }
    return this._addCheck({
      kind: "datetime",
      precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
      offset: (_a3 = options == null ? void 0 : options.offset) != null ? _a3 : false,
      local: (_b2 = options == null ? void 0 : options.local) != null ? _b2 : false,
      ...errorUtil.errToObj(options == null ? void 0 : options.message)
    });
  }
  date(message) {
    return this._addCheck({ kind: "date", message });
  }
  time(options) {
    if (typeof options === "string") {
      return this._addCheck({
        kind: "time",
        precision: null,
        message: options
      });
    }
    return this._addCheck({
      kind: "time",
      precision: typeof (options == null ? void 0 : options.precision) === "undefined" ? null : options == null ? void 0 : options.precision,
      ...errorUtil.errToObj(options == null ? void 0 : options.message)
    });
  }
  duration(message) {
    return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) });
  }
  regex(regex, message) {
    return this._addCheck({
      kind: "regex",
      regex,
      ...errorUtil.errToObj(message)
    });
  }
  includes(value, options) {
    return this._addCheck({
      kind: "includes",
      value,
      position: options == null ? void 0 : options.position,
      ...errorUtil.errToObj(options == null ? void 0 : options.message)
    });
  }
  startsWith(value, message) {
    return this._addCheck({
      kind: "startsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  endsWith(value, message) {
    return this._addCheck({
      kind: "endsWith",
      value,
      ...errorUtil.errToObj(message)
    });
  }
  min(minLength, message) {
    return this._addCheck({
      kind: "min",
      value: minLength,
      ...errorUtil.errToObj(message)
    });
  }
  max(maxLength, message) {
    return this._addCheck({
      kind: "max",
      value: maxLength,
      ...errorUtil.errToObj(message)
    });
  }
  length(len, message) {
    return this._addCheck({
      kind: "length",
      value: len,
      ...errorUtil.errToObj(message)
    });
  }
  /**
   * Equivalent to `.min(1)`
   */
  nonempty(message) {
    return this.min(1, errorUtil.errToObj(message));
  }
  trim() {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "trim" }]
    });
  }
  toLowerCase() {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "toLowerCase" }]
    });
  }
  toUpperCase() {
    return new _ZodString2({
      ...this._def,
      checks: [...this._def.checks, { kind: "toUpperCase" }]
    });
  }
  get isDatetime() {
    return !!this._def.checks.find((ch) => ch.kind === "datetime");
  }
  get isDate() {
    return !!this._def.checks.find((ch) => ch.kind === "date");
  }
  get isTime() {
    return !!this._def.checks.find((ch) => ch.kind === "time");
  }
  get isDuration() {
    return !!this._def.checks.find((ch) => ch.kind === "duration");
  }
  get isEmail() {
    return !!this._def.checks.find((ch) => ch.kind === "email");
  }
  get isURL() {
    return !!this._def.checks.find((ch) => ch.kind === "url");
  }
  get isEmoji() {
    return !!this._def.checks.find((ch) => ch.kind === "emoji");
  }
  get isUUID() {
    return !!this._def.checks.find((ch) => ch.kind === "uuid");
  }
  get isNANOID() {
    return !!this._def.checks.find((ch) => ch.kind === "nanoid");
  }
  get isCUID() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid");
  }
  get isCUID2() {
    return !!this._def.checks.find((ch) => ch.kind === "cuid2");
  }
  get isULID() {
    return !!this._def.checks.find((ch) => ch.kind === "ulid");
  }
  get isIP() {
    return !!this._def.checks.find((ch) => ch.kind === "ip");
  }
  get isCIDR() {
    return !!this._def.checks.find((ch) => ch.kind === "cidr");
  }
  get isBase64() {
    return !!this._def.checks.find((ch) => ch.kind === "base64");
  }
  get isBase64url() {
    return !!this._def.checks.find((ch) => ch.kind === "base64url");
  }
  get minLength() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxLength() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodString.create = (params) => {
  var _a3;
  return new ZodString({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodString,
    coerce: (_a3 = params == null ? void 0 : params.coerce) != null ? _a3 : false,
    ...processCreateParams(params)
  });
};
function floatSafeRemainder(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepDecCount = (step.toString().split(".")[1] || "").length;
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
var ZodNumber = class _ZodNumber extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
    this.step = this.multipleOf;
  }
  _parse(input) {
    if (this._def.coerce) {
      input.data = Number(input.data);
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.number) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.number,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check2 of this._def.checks) {
      if (check2.kind === "int") {
        if (!util.isInteger(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.invalid_type,
            expected: "integer",
            received: "float",
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "min") {
        const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            minimum: check2.value,
            type: "number",
            inclusive: check2.inclusive,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            maximum: check2.value,
            type: "number",
            inclusive: check2.inclusive,
            exact: false,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "multipleOf") {
        if (floatSafeRemainder(input.data, check2.value) !== 0) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check2.value,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "finite") {
        if (!Number.isFinite(input.data)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_finite,
            message: check2.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check2);
      }
    }
    return { status: status.value, value: input.data };
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodNumber({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check2) {
    return new _ZodNumber({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  int(message) {
    return this._addCheck({
      kind: "int",
      message: errorUtil.toString(message)
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: 0,
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  finite(message) {
    return this._addCheck({
      kind: "finite",
      message: errorUtil.toString(message)
    });
  }
  safe(message) {
    return this._addCheck({
      kind: "min",
      inclusive: true,
      value: Number.MIN_SAFE_INTEGER,
      message: errorUtil.toString(message)
    })._addCheck({
      kind: "max",
      inclusive: true,
      value: Number.MAX_SAFE_INTEGER,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
  get isInt() {
    return !!this._def.checks.find((ch) => ch.kind === "int" || ch.kind === "multipleOf" && util.isInteger(ch.value));
  }
  get isFinite() {
    let max = null;
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") {
        return true;
      } else if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      } else if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return Number.isFinite(min) && Number.isFinite(max);
  }
};
ZodNumber.create = (params) => {
  return new ZodNumber({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodNumber,
    coerce: (params == null ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
var ZodBigInt = class _ZodBigInt extends ZodType {
  constructor() {
    super(...arguments);
    this.min = this.gte;
    this.max = this.lte;
  }
  _parse(input) {
    if (this._def.coerce) {
      try {
        input.data = BigInt(input.data);
      } catch (e2) {
        return this._getInvalidInput(input);
      }
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.bigint) {
      return this._getInvalidInput(input);
    }
    let ctx = void 0;
    const status = new ParseStatus();
    for (const check2 of this._def.checks) {
      if (check2.kind === "min") {
        const tooSmall = check2.inclusive ? input.data < check2.value : input.data <= check2.value;
        if (tooSmall) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            type: "bigint",
            minimum: check2.value,
            inclusive: check2.inclusive,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        const tooBig = check2.inclusive ? input.data > check2.value : input.data >= check2.value;
        if (tooBig) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            type: "bigint",
            maximum: check2.value,
            inclusive: check2.inclusive,
            message: check2.message
          });
          status.dirty();
        }
      } else if (check2.kind === "multipleOf") {
        if (input.data % check2.value !== BigInt(0)) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.not_multiple_of,
            multipleOf: check2.value,
            message: check2.message
          });
          status.dirty();
        }
      } else {
        util.assertNever(check2);
      }
    }
    return { status: status.value, value: input.data };
  }
  _getInvalidInput(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.bigint,
      received: ctx.parsedType
    });
    return INVALID;
  }
  gte(value, message) {
    return this.setLimit("min", value, true, errorUtil.toString(message));
  }
  gt(value, message) {
    return this.setLimit("min", value, false, errorUtil.toString(message));
  }
  lte(value, message) {
    return this.setLimit("max", value, true, errorUtil.toString(message));
  }
  lt(value, message) {
    return this.setLimit("max", value, false, errorUtil.toString(message));
  }
  setLimit(kind, value, inclusive, message) {
    return new _ZodBigInt({
      ...this._def,
      checks: [
        ...this._def.checks,
        {
          kind,
          value,
          inclusive,
          message: errorUtil.toString(message)
        }
      ]
    });
  }
  _addCheck(check2) {
    return new _ZodBigInt({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  positive(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  negative(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: false,
      message: errorUtil.toString(message)
    });
  }
  nonpositive(message) {
    return this._addCheck({
      kind: "max",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  nonnegative(message) {
    return this._addCheck({
      kind: "min",
      value: BigInt(0),
      inclusive: true,
      message: errorUtil.toString(message)
    });
  }
  multipleOf(value, message) {
    return this._addCheck({
      kind: "multipleOf",
      value,
      message: errorUtil.toString(message)
    });
  }
  get minValue() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min;
  }
  get maxValue() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max;
  }
};
ZodBigInt.create = (params) => {
  var _a3;
  return new ZodBigInt({
    checks: [],
    typeName: ZodFirstPartyTypeKind.ZodBigInt,
    coerce: (_a3 = params == null ? void 0 : params.coerce) != null ? _a3 : false,
    ...processCreateParams(params)
  });
};
var ZodBoolean = class extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = Boolean(input.data);
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.boolean) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.boolean,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK2(input.data);
  }
};
ZodBoolean.create = (params) => {
  return new ZodBoolean({
    typeName: ZodFirstPartyTypeKind.ZodBoolean,
    coerce: (params == null ? void 0 : params.coerce) || false,
    ...processCreateParams(params)
  });
};
var ZodDate = class _ZodDate extends ZodType {
  _parse(input) {
    if (this._def.coerce) {
      input.data = new Date(input.data);
    }
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.date) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.date,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    if (Number.isNaN(input.data.getTime())) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_date
      });
      return INVALID;
    }
    const status = new ParseStatus();
    let ctx = void 0;
    for (const check2 of this._def.checks) {
      if (check2.kind === "min") {
        if (input.data.getTime() < check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_small,
            message: check2.message,
            inclusive: true,
            exact: false,
            minimum: check2.value,
            type: "date"
          });
          status.dirty();
        }
      } else if (check2.kind === "max") {
        if (input.data.getTime() > check2.value) {
          ctx = this._getOrReturnCtx(input, ctx);
          addIssueToContext(ctx, {
            code: ZodIssueCode.too_big,
            message: check2.message,
            inclusive: true,
            exact: false,
            maximum: check2.value,
            type: "date"
          });
          status.dirty();
        }
      } else {
        util.assertNever(check2);
      }
    }
    return {
      status: status.value,
      value: new Date(input.data.getTime())
    };
  }
  _addCheck(check2) {
    return new _ZodDate({
      ...this._def,
      checks: [...this._def.checks, check2]
    });
  }
  min(minDate, message) {
    return this._addCheck({
      kind: "min",
      value: minDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  max(maxDate, message) {
    return this._addCheck({
      kind: "max",
      value: maxDate.getTime(),
      message: errorUtil.toString(message)
    });
  }
  get minDate() {
    let min = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "min") {
        if (min === null || ch.value > min)
          min = ch.value;
      }
    }
    return min != null ? new Date(min) : null;
  }
  get maxDate() {
    let max = null;
    for (const ch of this._def.checks) {
      if (ch.kind === "max") {
        if (max === null || ch.value < max)
          max = ch.value;
      }
    }
    return max != null ? new Date(max) : null;
  }
};
ZodDate.create = (params) => {
  return new ZodDate({
    checks: [],
    coerce: (params == null ? void 0 : params.coerce) || false,
    typeName: ZodFirstPartyTypeKind.ZodDate,
    ...processCreateParams(params)
  });
};
var ZodSymbol = class extends ZodType {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.symbol) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.symbol,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK2(input.data);
  }
};
ZodSymbol.create = (params) => {
  return new ZodSymbol({
    typeName: ZodFirstPartyTypeKind.ZodSymbol,
    ...processCreateParams(params)
  });
};
var ZodUndefined = class extends ZodType {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.undefined,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK2(input.data);
  }
};
ZodUndefined.create = (params) => {
  return new ZodUndefined({
    typeName: ZodFirstPartyTypeKind.ZodUndefined,
    ...processCreateParams(params)
  });
};
var ZodNull = class extends ZodType {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.null) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.null,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK2(input.data);
  }
};
ZodNull.create = (params) => {
  return new ZodNull({
    typeName: ZodFirstPartyTypeKind.ZodNull,
    ...processCreateParams(params)
  });
};
var ZodAny = class extends ZodType {
  constructor() {
    super(...arguments);
    this._any = true;
  }
  _parse(input) {
    return OK2(input.data);
  }
};
ZodAny.create = (params) => {
  return new ZodAny({
    typeName: ZodFirstPartyTypeKind.ZodAny,
    ...processCreateParams(params)
  });
};
var ZodUnknown = class extends ZodType {
  constructor() {
    super(...arguments);
    this._unknown = true;
  }
  _parse(input) {
    return OK2(input.data);
  }
};
ZodUnknown.create = (params) => {
  return new ZodUnknown({
    typeName: ZodFirstPartyTypeKind.ZodUnknown,
    ...processCreateParams(params)
  });
};
var ZodNever = class extends ZodType {
  _parse(input) {
    const ctx = this._getOrReturnCtx(input);
    addIssueToContext(ctx, {
      code: ZodIssueCode.invalid_type,
      expected: ZodParsedType.never,
      received: ctx.parsedType
    });
    return INVALID;
  }
};
ZodNever.create = (params) => {
  return new ZodNever({
    typeName: ZodFirstPartyTypeKind.ZodNever,
    ...processCreateParams(params)
  });
};
var ZodVoid = class extends ZodType {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.undefined) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.void,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return OK2(input.data);
  }
};
ZodVoid.create = (params) => {
  return new ZodVoid({
    typeName: ZodFirstPartyTypeKind.ZodVoid,
    ...processCreateParams(params)
  });
};
var ZodArray = class _ZodArray extends ZodType {
  _parse(input) {
    const { ctx, status } = this._processInputParams(input);
    const def = this._def;
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (def.exactLength !== null) {
      const tooBig = ctx.data.length > def.exactLength.value;
      const tooSmall = ctx.data.length < def.exactLength.value;
      if (tooBig || tooSmall) {
        addIssueToContext(ctx, {
          code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,
          minimum: tooSmall ? def.exactLength.value : void 0,
          maximum: tooBig ? def.exactLength.value : void 0,
          type: "array",
          inclusive: true,
          exact: true,
          message: def.exactLength.message
        });
        status.dirty();
      }
    }
    if (def.minLength !== null) {
      if (ctx.data.length < def.minLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.minLength.message
        });
        status.dirty();
      }
    }
    if (def.maxLength !== null) {
      if (ctx.data.length > def.maxLength.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxLength.value,
          type: "array",
          inclusive: true,
          exact: false,
          message: def.maxLength.message
        });
        status.dirty();
      }
    }
    if (ctx.common.async) {
      return Promise.all([...ctx.data].map((item, i2) => {
        return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
      })).then((result2) => {
        return ParseStatus.mergeArray(status, result2);
      });
    }
    const result = [...ctx.data].map((item, i2) => {
      return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i2));
    });
    return ParseStatus.mergeArray(status, result);
  }
  get element() {
    return this._def.type;
  }
  min(minLength, message) {
    return new _ZodArray({
      ...this._def,
      minLength: { value: minLength, message: errorUtil.toString(message) }
    });
  }
  max(maxLength, message) {
    return new _ZodArray({
      ...this._def,
      maxLength: { value: maxLength, message: errorUtil.toString(message) }
    });
  }
  length(len, message) {
    return new _ZodArray({
      ...this._def,
      exactLength: { value: len, message: errorUtil.toString(message) }
    });
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodArray.create = (schema, params) => {
  return new ZodArray({
    type: schema,
    minLength: null,
    maxLength: null,
    exactLength: null,
    typeName: ZodFirstPartyTypeKind.ZodArray,
    ...processCreateParams(params)
  });
};
function deepPartialify(schema) {
  if (schema instanceof ZodObject) {
    const newShape = {};
    for (const key in schema.shape) {
      const fieldSchema = schema.shape[key];
      newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));
    }
    return new ZodObject({
      ...schema._def,
      shape: () => newShape
    });
  } else if (schema instanceof ZodArray) {
    return new ZodArray({
      ...schema._def,
      type: deepPartialify(schema.element)
    });
  } else if (schema instanceof ZodOptional) {
    return ZodOptional.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodNullable) {
    return ZodNullable.create(deepPartialify(schema.unwrap()));
  } else if (schema instanceof ZodTuple) {
    return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));
  } else {
    return schema;
  }
}
var ZodObject = class _ZodObject extends ZodType {
  constructor() {
    super(...arguments);
    this._cached = null;
    this.nonstrict = this.passthrough;
    this.augment = this.extend;
  }
  _getCached() {
    if (this._cached !== null)
      return this._cached;
    const shape = this._def.shape();
    const keys = util.objectKeys(shape);
    this._cached = { shape, keys };
    return this._cached;
  }
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.object) {
      const ctx2 = this._getOrReturnCtx(input);
      addIssueToContext(ctx2, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx2.parsedType
      });
      return INVALID;
    }
    const { status, ctx } = this._processInputParams(input);
    const { shape, keys: shapeKeys } = this._getCached();
    const extraKeys = [];
    if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) {
      for (const key in ctx.data) {
        if (!shapeKeys.includes(key)) {
          extraKeys.push(key);
        }
      }
    }
    const pairs = [];
    for (const key of shapeKeys) {
      const keyValidator = shape[key];
      const value = ctx.data[key];
      pairs.push({
        key: { status: "valid", value: key },
        value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (this._def.catchall instanceof ZodNever) {
      const unknownKeys = this._def.unknownKeys;
      if (unknownKeys === "passthrough") {
        for (const key of extraKeys) {
          pairs.push({
            key: { status: "valid", value: key },
            value: { status: "valid", value: ctx.data[key] }
          });
        }
      } else if (unknownKeys === "strict") {
        if (extraKeys.length > 0) {
          addIssueToContext(ctx, {
            code: ZodIssueCode.unrecognized_keys,
            keys: extraKeys
          });
          status.dirty();
        }
      } else if (unknownKeys === "strip") {
      } else {
        throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);
      }
    } else {
      const catchall = this._def.catchall;
      for (const key of extraKeys) {
        const value = ctx.data[key];
        pairs.push({
          key: { status: "valid", value: key },
          value: catchall._parse(
            new ParseInputLazyPath(ctx, value, ctx.path, key)
            //, ctx.child(key), value, getParsedType(value)
          ),
          alwaysSet: key in ctx.data
        });
      }
    }
    if (ctx.common.async) {
      return Promise.resolve().then(async () => {
        const syncPairs = [];
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          syncPairs.push({
            key,
            value,
            alwaysSet: pair.alwaysSet
          });
        }
        return syncPairs;
      }).then((syncPairs) => {
        return ParseStatus.mergeObjectSync(status, syncPairs);
      });
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get shape() {
    return this._def.shape();
  }
  strict(message) {
    errorUtil.errToObj;
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strict",
      ...message !== void 0 ? {
        errorMap: (issue2, ctx) => {
          var _a3, _b2, _c, _d2;
          const defaultError = (_c = (_b2 = (_a3 = this._def).errorMap) == null ? void 0 : _b2.call(_a3, issue2, ctx).message) != null ? _c : ctx.defaultError;
          if (issue2.code === "unrecognized_keys")
            return {
              message: (_d2 = errorUtil.errToObj(message).message) != null ? _d2 : defaultError
            };
          return {
            message: defaultError
          };
        }
      } : {}
    });
  }
  strip() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "strip"
    });
  }
  passthrough() {
    return new _ZodObject({
      ...this._def,
      unknownKeys: "passthrough"
    });
  }
  // const AugmentFactory =
  //   <Def extends ZodObjectDef>(def: Def) =>
  //   <Augmentation extends ZodRawShape>(
  //     augmentation: Augmentation
  //   ): ZodObject<
  //     extendShape<ReturnType<Def["shape"]>, Augmentation>,
  //     Def["unknownKeys"],
  //     Def["catchall"]
  //   > => {
  //     return new ZodObject({
  //       ...def,
  //       shape: () => ({
  //         ...def.shape(),
  //         ...augmentation,
  //       }),
  //     }) as any;
  //   };
  extend(augmentation) {
    return new _ZodObject({
      ...this._def,
      shape: () => ({
        ...this._def.shape(),
        ...augmentation
      })
    });
  }
  /**
   * Prior to zod@1.0.12 there was a bug in the
   * inferred type of merged objects. Please
   * upgrade if you are experiencing issues.
   */
  merge(merging) {
    const merged = new _ZodObject({
      unknownKeys: merging._def.unknownKeys,
      catchall: merging._def.catchall,
      shape: () => ({
        ...this._def.shape(),
        ...merging._def.shape()
      }),
      typeName: ZodFirstPartyTypeKind.ZodObject
    });
    return merged;
  }
  // merge<
  //   Incoming extends AnyZodObject,
  //   Augmentation extends Incoming["shape"],
  //   NewOutput extends {
  //     [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation
  //       ? Augmentation[k]["_output"]
  //       : k extends keyof Output
  //       ? Output[k]
  //       : never;
  //   },
  //   NewInput extends {
  //     [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation
  //       ? Augmentation[k]["_input"]
  //       : k extends keyof Input
  //       ? Input[k]
  //       : never;
  //   }
  // >(
  //   merging: Incoming
  // ): ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"],
  //   NewOutput,
  //   NewInput
  // > {
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  setKey(key, schema) {
    return this.augment({ [key]: schema });
  }
  // merge<Incoming extends AnyZodObject>(
  //   merging: Incoming
  // ): //ZodObject<T & Incoming["_shape"], UnknownKeys, Catchall> = (merging) => {
  // ZodObject<
  //   extendShape<T, ReturnType<Incoming["_def"]["shape"]>>,
  //   Incoming["_def"]["unknownKeys"],
  //   Incoming["_def"]["catchall"]
  // > {
  //   // const mergedShape = objectUtil.mergeShapes(
  //   //   this._def.shape(),
  //   //   merging._def.shape()
  //   // );
  //   const merged: any = new ZodObject({
  //     unknownKeys: merging._def.unknownKeys,
  //     catchall: merging._def.catchall,
  //     shape: () =>
  //       objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),
  //     typeName: ZodFirstPartyTypeKind.ZodObject,
  //   }) as any;
  //   return merged;
  // }
  catchall(index) {
    return new _ZodObject({
      ...this._def,
      catchall: index
    });
  }
  pick(mask) {
    const shape = {};
    for (const key of util.objectKeys(mask)) {
      if (mask[key] && this.shape[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  omit(mask) {
    const shape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (!mask[key]) {
        shape[key] = this.shape[key];
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => shape
    });
  }
  /**
   * @deprecated
   */
  deepPartial() {
    return deepPartialify(this);
  }
  partial(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      const fieldSchema = this.shape[key];
      if (mask && !mask[key]) {
        newShape[key] = fieldSchema;
      } else {
        newShape[key] = fieldSchema.optional();
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  required(mask) {
    const newShape = {};
    for (const key of util.objectKeys(this.shape)) {
      if (mask && !mask[key]) {
        newShape[key] = this.shape[key];
      } else {
        const fieldSchema = this.shape[key];
        let newField = fieldSchema;
        while (newField instanceof ZodOptional) {
          newField = newField._def.innerType;
        }
        newShape[key] = newField;
      }
    }
    return new _ZodObject({
      ...this._def,
      shape: () => newShape
    });
  }
  keyof() {
    return createZodEnum(util.objectKeys(this.shape));
  }
};
ZodObject.create = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.strictCreate = (shape, params) => {
  return new ZodObject({
    shape: () => shape,
    unknownKeys: "strict",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
ZodObject.lazycreate = (shape, params) => {
  return new ZodObject({
    shape,
    unknownKeys: "strip",
    catchall: ZodNever.create(),
    typeName: ZodFirstPartyTypeKind.ZodObject,
    ...processCreateParams(params)
  });
};
var ZodUnion = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const options = this._def.options;
    function handleResults(results) {
      for (const result of results) {
        if (result.result.status === "valid") {
          return result.result;
        }
      }
      for (const result of results) {
        if (result.result.status === "dirty") {
          ctx.common.issues.push(...result.ctx.common.issues);
          return result.result;
        }
      }
      const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return Promise.all(options.map(async (option) => {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        return {
          result: await option._parseAsync({
            data: ctx.data,
            path: ctx.path,
            parent: childCtx
          }),
          ctx: childCtx
        };
      })).then(handleResults);
    } else {
      let dirty = void 0;
      const issues = [];
      for (const option of options) {
        const childCtx = {
          ...ctx,
          common: {
            ...ctx.common,
            issues: []
          },
          parent: null
        };
        const result = option._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: childCtx
        });
        if (result.status === "valid") {
          return result;
        } else if (result.status === "dirty" && !dirty) {
          dirty = { result, ctx: childCtx };
        }
        if (childCtx.common.issues.length) {
          issues.push(childCtx.common.issues);
        }
      }
      if (dirty) {
        ctx.common.issues.push(...dirty.ctx.common.issues);
        return dirty.result;
      }
      const unionErrors = issues.map((issues2) => new ZodError(issues2));
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union,
        unionErrors
      });
      return INVALID;
    }
  }
  get options() {
    return this._def.options;
  }
};
ZodUnion.create = (types, params) => {
  return new ZodUnion({
    options: types,
    typeName: ZodFirstPartyTypeKind.ZodUnion,
    ...processCreateParams(params)
  });
};
var getDiscriminator = (type) => {
  if (type instanceof ZodLazy) {
    return getDiscriminator(type.schema);
  } else if (type instanceof ZodEffects) {
    return getDiscriminator(type.innerType());
  } else if (type instanceof ZodLiteral) {
    return [type.value];
  } else if (type instanceof ZodEnum) {
    return type.options;
  } else if (type instanceof ZodNativeEnum) {
    return util.objectValues(type.enum);
  } else if (type instanceof ZodDefault) {
    return getDiscriminator(type._def.innerType);
  } else if (type instanceof ZodUndefined) {
    return [void 0];
  } else if (type instanceof ZodNull) {
    return [null];
  } else if (type instanceof ZodOptional) {
    return [void 0, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodNullable) {
    return [null, ...getDiscriminator(type.unwrap())];
  } else if (type instanceof ZodBranded) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodReadonly) {
    return getDiscriminator(type.unwrap());
  } else if (type instanceof ZodCatch) {
    return getDiscriminator(type._def.innerType);
  } else {
    return [];
  }
};
var ZodDiscriminatedUnion = class _ZodDiscriminatedUnion extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const discriminator = this.discriminator;
    const discriminatorValue = ctx.data[discriminator];
    const option = this.optionsMap.get(discriminatorValue);
    if (!option) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_union_discriminator,
        options: Array.from(this.optionsMap.keys()),
        path: [discriminator]
      });
      return INVALID;
    }
    if (ctx.common.async) {
      return option._parseAsync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    } else {
      return option._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
    }
  }
  get discriminator() {
    return this._def.discriminator;
  }
  get options() {
    return this._def.options;
  }
  get optionsMap() {
    return this._def.optionsMap;
  }
  /**
   * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.
   * However, it only allows a union of objects, all of which need to share a discriminator property. This property must
   * have a different value for each object in the union.
   * @param discriminator the name of the discriminator property
   * @param types an array of object schemas
   * @param params
   */
  static create(discriminator, options, params) {
    const optionsMap = /* @__PURE__ */ new Map();
    for (const type of options) {
      const discriminatorValues = getDiscriminator(type.shape[discriminator]);
      if (!discriminatorValues.length) {
        throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`);
      }
      for (const value of discriminatorValues) {
        if (optionsMap.has(value)) {
          throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);
        }
        optionsMap.set(value, type);
      }
    }
    return new _ZodDiscriminatedUnion({
      typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,
      discriminator,
      options,
      optionsMap,
      ...processCreateParams(params)
    });
  }
};
function mergeValues(a2, b10) {
  const aType = getParsedType(a2);
  const bType = getParsedType(b10);
  if (a2 === b10) {
    return { valid: true, data: a2 };
  } else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {
    const bKeys = util.objectKeys(b10);
    const sharedKeys = util.objectKeys(a2).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a2, ...b10 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a2[key], b10[key]);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  } else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {
    if (a2.length !== b10.length) {
      return { valid: false };
    }
    const newArray = [];
    for (let index = 0; index < a2.length; index++) {
      const itemA = a2[index];
      const itemB = b10[index];
      const sharedValue = mergeValues(itemA, itemB);
      if (!sharedValue.valid) {
        return { valid: false };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  } else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a2 === +b10) {
    return { valid: true, data: a2 };
  } else {
    return { valid: false };
  }
}
var ZodIntersection = class extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const handleParsed = (parsedLeft, parsedRight) => {
      if (isAborted(parsedLeft) || isAborted(parsedRight)) {
        return INVALID;
      }
      const merged = mergeValues(parsedLeft.value, parsedRight.value);
      if (!merged.valid) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.invalid_intersection_types
        });
        return INVALID;
      }
      if (isDirty(parsedLeft) || isDirty(parsedRight)) {
        status.dirty();
      }
      return { status: status.value, value: merged.data };
    };
    if (ctx.common.async) {
      return Promise.all([
        this._def.left._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        }),
        this._def.right._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        })
      ]).then(([left, right]) => handleParsed(left, right));
    } else {
      return handleParsed(this._def.left._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }), this._def.right._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      }));
    }
  }
};
ZodIntersection.create = (left, right, params) => {
  return new ZodIntersection({
    left,
    right,
    typeName: ZodFirstPartyTypeKind.ZodIntersection,
    ...processCreateParams(params)
  });
};
var ZodTuple = class _ZodTuple extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.array) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.array,
        received: ctx.parsedType
      });
      return INVALID;
    }
    if (ctx.data.length < this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_small,
        minimum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      return INVALID;
    }
    const rest = this._def.rest;
    if (!rest && ctx.data.length > this._def.items.length) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.too_big,
        maximum: this._def.items.length,
        inclusive: true,
        exact: false,
        type: "array"
      });
      status.dirty();
    }
    const items = [...ctx.data].map((item, itemIndex) => {
      const schema = this._def.items[itemIndex] || this._def.rest;
      if (!schema)
        return null;
      return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));
    }).filter((x) => !!x);
    if (ctx.common.async) {
      return Promise.all(items).then((results) => {
        return ParseStatus.mergeArray(status, results);
      });
    } else {
      return ParseStatus.mergeArray(status, items);
    }
  }
  get items() {
    return this._def.items;
  }
  rest(rest) {
    return new _ZodTuple({
      ...this._def,
      rest
    });
  }
};
ZodTuple.create = (schemas, params) => {
  if (!Array.isArray(schemas)) {
    throw new Error("You must pass an array of schemas to z.tuple([ ... ])");
  }
  return new ZodTuple({
    items: schemas,
    typeName: ZodFirstPartyTypeKind.ZodTuple,
    rest: null,
    ...processCreateParams(params)
  });
};
var ZodRecord = class _ZodRecord extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.object) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.object,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const pairs = [];
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    for (const key in ctx.data) {
      pairs.push({
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),
        value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),
        alwaysSet: key in ctx.data
      });
    }
    if (ctx.common.async) {
      return ParseStatus.mergeObjectAsync(status, pairs);
    } else {
      return ParseStatus.mergeObjectSync(status, pairs);
    }
  }
  get element() {
    return this._def.valueType;
  }
  static create(first, second, third) {
    if (second instanceof ZodType) {
      return new _ZodRecord({
        keyType: first,
        valueType: second,
        typeName: ZodFirstPartyTypeKind.ZodRecord,
        ...processCreateParams(third)
      });
    }
    return new _ZodRecord({
      keyType: ZodString.create(),
      valueType: first,
      typeName: ZodFirstPartyTypeKind.ZodRecord,
      ...processCreateParams(second)
    });
  }
};
var ZodMap = class extends ZodType {
  get keySchema() {
    return this._def.keyType;
  }
  get valueSchema() {
    return this._def.valueType;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.map) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.map,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const keyType = this._def.keyType;
    const valueType = this._def.valueType;
    const pairs = [...ctx.data.entries()].map(([key, value], index) => {
      return {
        key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])),
        value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"]))
      };
    });
    if (ctx.common.async) {
      const finalMap = /* @__PURE__ */ new Map();
      return Promise.resolve().then(async () => {
        for (const pair of pairs) {
          const key = await pair.key;
          const value = await pair.value;
          if (key.status === "aborted" || value.status === "aborted") {
            return INVALID;
          }
          if (key.status === "dirty" || value.status === "dirty") {
            status.dirty();
          }
          finalMap.set(key.value, value.value);
        }
        return { status: status.value, value: finalMap };
      });
    } else {
      const finalMap = /* @__PURE__ */ new Map();
      for (const pair of pairs) {
        const key = pair.key;
        const value = pair.value;
        if (key.status === "aborted" || value.status === "aborted") {
          return INVALID;
        }
        if (key.status === "dirty" || value.status === "dirty") {
          status.dirty();
        }
        finalMap.set(key.value, value.value);
      }
      return { status: status.value, value: finalMap };
    }
  }
};
ZodMap.create = (keyType, valueType, params) => {
  return new ZodMap({
    valueType,
    keyType,
    typeName: ZodFirstPartyTypeKind.ZodMap,
    ...processCreateParams(params)
  });
};
var ZodSet = class _ZodSet extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.set) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.set,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const def = this._def;
    if (def.minSize !== null) {
      if (ctx.data.size < def.minSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_small,
          minimum: def.minSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.minSize.message
        });
        status.dirty();
      }
    }
    if (def.maxSize !== null) {
      if (ctx.data.size > def.maxSize.value) {
        addIssueToContext(ctx, {
          code: ZodIssueCode.too_big,
          maximum: def.maxSize.value,
          type: "set",
          inclusive: true,
          exact: false,
          message: def.maxSize.message
        });
        status.dirty();
      }
    }
    const valueType = this._def.valueType;
    function finalizeSet(elements2) {
      const parsedSet = /* @__PURE__ */ new Set();
      for (const element of elements2) {
        if (element.status === "aborted")
          return INVALID;
        if (element.status === "dirty")
          status.dirty();
        parsedSet.add(element.value);
      }
      return { status: status.value, value: parsedSet };
    }
    const elements = [...ctx.data.values()].map((item, i2) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i2)));
    if (ctx.common.async) {
      return Promise.all(elements).then((elements2) => finalizeSet(elements2));
    } else {
      return finalizeSet(elements);
    }
  }
  min(minSize, message) {
    return new _ZodSet({
      ...this._def,
      minSize: { value: minSize, message: errorUtil.toString(message) }
    });
  }
  max(maxSize, message) {
    return new _ZodSet({
      ...this._def,
      maxSize: { value: maxSize, message: errorUtil.toString(message) }
    });
  }
  size(size, message) {
    return this.min(size, message).max(size, message);
  }
  nonempty(message) {
    return this.min(1, message);
  }
};
ZodSet.create = (valueType, params) => {
  return new ZodSet({
    valueType,
    minSize: null,
    maxSize: null,
    typeName: ZodFirstPartyTypeKind.ZodSet,
    ...processCreateParams(params)
  });
};
var ZodFunction = class _ZodFunction extends ZodType {
  constructor() {
    super(...arguments);
    this.validate = this.implement;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.function) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.function,
        received: ctx.parsedType
      });
      return INVALID;
    }
    function makeArgsIssue(args, error48) {
      return makeIssue({
        data: args,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default2].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_arguments,
          argumentsError: error48
        }
      });
    }
    function makeReturnsIssue(returns, error48) {
      return makeIssue({
        data: returns,
        path: ctx.path,
        errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), en_default2].filter((x) => !!x),
        issueData: {
          code: ZodIssueCode.invalid_return_type,
          returnTypeError: error48
        }
      });
    }
    const params = { errorMap: ctx.common.contextualErrorMap };
    const fn = ctx.data;
    if (this._def.returns instanceof ZodPromise) {
      const me = this;
      return OK2(async function(...args) {
        const error48 = new ZodError([]);
        const parsedArgs = await me._def.args.parseAsync(args, params).catch((e2) => {
          error48.addIssue(makeArgsIssue(args, e2));
          throw error48;
        });
        const result = await Reflect.apply(fn, this, parsedArgs);
        const parsedReturns = await me._def.returns._def.type.parseAsync(result, params).catch((e2) => {
          error48.addIssue(makeReturnsIssue(result, e2));
          throw error48;
        });
        return parsedReturns;
      });
    } else {
      const me = this;
      return OK2(function(...args) {
        const parsedArgs = me._def.args.safeParse(args, params);
        if (!parsedArgs.success) {
          throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);
        }
        const result = Reflect.apply(fn, this, parsedArgs.data);
        const parsedReturns = me._def.returns.safeParse(result, params);
        if (!parsedReturns.success) {
          throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);
        }
        return parsedReturns.data;
      });
    }
  }
  parameters() {
    return this._def.args;
  }
  returnType() {
    return this._def.returns;
  }
  args(...items) {
    return new _ZodFunction({
      ...this._def,
      args: ZodTuple.create(items).rest(ZodUnknown.create())
    });
  }
  returns(returnType) {
    return new _ZodFunction({
      ...this._def,
      returns: returnType
    });
  }
  implement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  strictImplement(func) {
    const validatedFunc = this.parse(func);
    return validatedFunc;
  }
  static create(args, returns, params) {
    return new _ZodFunction({
      args: args ? args : ZodTuple.create([]).rest(ZodUnknown.create()),
      returns: returns || ZodUnknown.create(),
      typeName: ZodFirstPartyTypeKind.ZodFunction,
      ...processCreateParams(params)
    });
  }
};
var ZodLazy = class extends ZodType {
  get schema() {
    return this._def.getter();
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const lazySchema = this._def.getter();
    return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });
  }
};
ZodLazy.create = (getter, params) => {
  return new ZodLazy({
    getter,
    typeName: ZodFirstPartyTypeKind.ZodLazy,
    ...processCreateParams(params)
  });
};
var ZodLiteral = class extends ZodType {
  _parse(input) {
    if (input.data !== this._def.value) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_literal,
        expected: this._def.value
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
  get value() {
    return this._def.value;
  }
};
ZodLiteral.create = (value, params) => {
  return new ZodLiteral({
    value,
    typeName: ZodFirstPartyTypeKind.ZodLiteral,
    ...processCreateParams(params)
  });
};
function createZodEnum(values, params) {
  return new ZodEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodEnum,
    ...processCreateParams(params)
  });
}
var ZodEnum = class _ZodEnum extends ZodType {
  _parse(input) {
    if (typeof input.data !== "string") {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(this._def.values);
    }
    if (!this._cache.has(input.data)) {
      const ctx = this._getOrReturnCtx(input);
      const expectedValues = this._def.values;
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK2(input.data);
  }
  get options() {
    return this._def.values;
  }
  get enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Values() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  get Enum() {
    const enumValues = {};
    for (const val of this._def.values) {
      enumValues[val] = val;
    }
    return enumValues;
  }
  extract(values, newDef = this._def) {
    return _ZodEnum.create(values, {
      ...this._def,
      ...newDef
    });
  }
  exclude(values, newDef = this._def) {
    return _ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {
      ...this._def,
      ...newDef
    });
  }
};
ZodEnum.create = createZodEnum;
var ZodNativeEnum = class extends ZodType {
  _parse(input) {
    const nativeEnumValues = util.getValidEnumValues(this._def.values);
    const ctx = this._getOrReturnCtx(input);
    if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        expected: util.joinValues(expectedValues),
        received: ctx.parsedType,
        code: ZodIssueCode.invalid_type
      });
      return INVALID;
    }
    if (!this._cache) {
      this._cache = new Set(util.getValidEnumValues(this._def.values));
    }
    if (!this._cache.has(input.data)) {
      const expectedValues = util.objectValues(nativeEnumValues);
      addIssueToContext(ctx, {
        received: ctx.data,
        code: ZodIssueCode.invalid_enum_value,
        options: expectedValues
      });
      return INVALID;
    }
    return OK2(input.data);
  }
  get enum() {
    return this._def.values;
  }
};
ZodNativeEnum.create = (values, params) => {
  return new ZodNativeEnum({
    values,
    typeName: ZodFirstPartyTypeKind.ZodNativeEnum,
    ...processCreateParams(params)
  });
};
var ZodPromise = class extends ZodType {
  unwrap() {
    return this._def.type;
  }
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.promise,
        received: ctx.parsedType
      });
      return INVALID;
    }
    const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);
    return OK2(promisified.then((data) => {
      return this._def.type.parseAsync(data, {
        path: ctx.path,
        errorMap: ctx.common.contextualErrorMap
      });
    }));
  }
};
ZodPromise.create = (schema, params) => {
  return new ZodPromise({
    type: schema,
    typeName: ZodFirstPartyTypeKind.ZodPromise,
    ...processCreateParams(params)
  });
};
var ZodEffects = class extends ZodType {
  innerType() {
    return this._def.schema;
  }
  sourceType() {
    return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects ? this._def.schema.sourceType() : this._def.schema;
  }
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    const effect = this._def.effect || null;
    const checkCtx = {
      addIssue: (arg) => {
        addIssueToContext(ctx, arg);
        if (arg.fatal) {
          status.abort();
        } else {
          status.dirty();
        }
      },
      get path() {
        return ctx.path;
      }
    };
    checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);
    if (effect.type === "preprocess") {
      const processed = effect.transform(ctx.data, checkCtx);
      if (ctx.common.async) {
        return Promise.resolve(processed).then(async (processed2) => {
          if (status.value === "aborted")
            return INVALID;
          const result = await this._def.schema._parseAsync({
            data: processed2,
            path: ctx.path,
            parent: ctx
          });
          if (result.status === "aborted")
            return INVALID;
          if (result.status === "dirty")
            return DIRTY(result.value);
          if (status.value === "dirty")
            return DIRTY(result.value);
          return result;
        });
      } else {
        if (status.value === "aborted")
          return INVALID;
        const result = this._def.schema._parseSync({
          data: processed,
          path: ctx.path,
          parent: ctx
        });
        if (result.status === "aborted")
          return INVALID;
        if (result.status === "dirty")
          return DIRTY(result.value);
        if (status.value === "dirty")
          return DIRTY(result.value);
        return result;
      }
    }
    if (effect.type === "refinement") {
      const executeRefinement = (acc) => {
        const result = effect.refinement(acc, checkCtx);
        if (ctx.common.async) {
          return Promise.resolve(result);
        }
        if (result instanceof Promise) {
          throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");
        }
        return acc;
      };
      if (ctx.common.async === false) {
        const inner = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inner.status === "aborted")
          return INVALID;
        if (inner.status === "dirty")
          status.dirty();
        executeRefinement(inner.value);
        return { status: status.value, value: inner.value };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {
          if (inner.status === "aborted")
            return INVALID;
          if (inner.status === "dirty")
            status.dirty();
          return executeRefinement(inner.value).then(() => {
            return { status: status.value, value: inner.value };
          });
        });
      }
    }
    if (effect.type === "transform") {
      if (ctx.common.async === false) {
        const base = this._def.schema._parseSync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (!isValid(base))
          return INVALID;
        const result = effect.transform(base.value, checkCtx);
        if (result instanceof Promise) {
          throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);
        }
        return { status: status.value, value: result };
      } else {
        return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {
          if (!isValid(base))
            return INVALID;
          return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({
            status: status.value,
            value: result
          }));
        });
      }
    }
    util.assertNever(effect);
  }
};
ZodEffects.create = (schema, effect, params) => {
  return new ZodEffects({
    schema,
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    effect,
    ...processCreateParams(params)
  });
};
ZodEffects.createWithPreprocess = (preprocess2, schema, params) => {
  return new ZodEffects({
    schema,
    effect: { type: "preprocess", transform: preprocess2 },
    typeName: ZodFirstPartyTypeKind.ZodEffects,
    ...processCreateParams(params)
  });
};
var ZodOptional = class extends ZodType {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 === ZodParsedType.undefined) {
      return OK2(void 0);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodOptional.create = (type, params) => {
  return new ZodOptional({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodOptional,
    ...processCreateParams(params)
  });
};
var ZodNullable = class extends ZodType {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 === ZodParsedType.null) {
      return OK2(null);
    }
    return this._def.innerType._parse(input);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodNullable.create = (type, params) => {
  return new ZodNullable({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodNullable,
    ...processCreateParams(params)
  });
};
var ZodDefault = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    let data = ctx.data;
    if (ctx.parsedType === ZodParsedType.undefined) {
      data = this._def.defaultValue();
    }
    return this._def.innerType._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  removeDefault() {
    return this._def.innerType;
  }
};
ZodDefault.create = (type, params) => {
  return new ZodDefault({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodDefault,
    defaultValue: typeof params.default === "function" ? params.default : () => params.default,
    ...processCreateParams(params)
  });
};
var ZodCatch = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const newCtx = {
      ...ctx,
      common: {
        ...ctx.common,
        issues: []
      }
    };
    const result = this._def.innerType._parse({
      data: newCtx.data,
      path: newCtx.path,
      parent: {
        ...newCtx
      }
    });
    if (isAsync(result)) {
      return result.then((result2) => {
        return {
          status: "valid",
          value: result2.status === "valid" ? result2.value : this._def.catchValue({
            get error() {
              return new ZodError(newCtx.common.issues);
            },
            input: newCtx.data
          })
        };
      });
    } else {
      return {
        status: "valid",
        value: result.status === "valid" ? result.value : this._def.catchValue({
          get error() {
            return new ZodError(newCtx.common.issues);
          },
          input: newCtx.data
        })
      };
    }
  }
  removeCatch() {
    return this._def.innerType;
  }
};
ZodCatch.create = (type, params) => {
  return new ZodCatch({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodCatch,
    catchValue: typeof params.catch === "function" ? params.catch : () => params.catch,
    ...processCreateParams(params)
  });
};
var ZodNaN = class extends ZodType {
  _parse(input) {
    const parsedType2 = this._getType(input);
    if (parsedType2 !== ZodParsedType.nan) {
      const ctx = this._getOrReturnCtx(input);
      addIssueToContext(ctx, {
        code: ZodIssueCode.invalid_type,
        expected: ZodParsedType.nan,
        received: ctx.parsedType
      });
      return INVALID;
    }
    return { status: "valid", value: input.data };
  }
};
ZodNaN.create = (params) => {
  return new ZodNaN({
    typeName: ZodFirstPartyTypeKind.ZodNaN,
    ...processCreateParams(params)
  });
};
var ZodBranded = class extends ZodType {
  _parse(input) {
    const { ctx } = this._processInputParams(input);
    const data = ctx.data;
    return this._def.type._parse({
      data,
      path: ctx.path,
      parent: ctx
    });
  }
  unwrap() {
    return this._def.type;
  }
};
var ZodPipeline = class _ZodPipeline extends ZodType {
  _parse(input) {
    const { status, ctx } = this._processInputParams(input);
    if (ctx.common.async) {
      const handleAsync = async () => {
        const inResult = await this._def.in._parseAsync({
          data: ctx.data,
          path: ctx.path,
          parent: ctx
        });
        if (inResult.status === "aborted")
          return INVALID;
        if (inResult.status === "dirty") {
          status.dirty();
          return DIRTY(inResult.value);
        } else {
          return this._def.out._parseAsync({
            data: inResult.value,
            path: ctx.path,
            parent: ctx
          });
        }
      };
      return handleAsync();
    } else {
      const inResult = this._def.in._parseSync({
        data: ctx.data,
        path: ctx.path,
        parent: ctx
      });
      if (inResult.status === "aborted")
        return INVALID;
      if (inResult.status === "dirty") {
        status.dirty();
        return {
          status: "dirty",
          value: inResult.value
        };
      } else {
        return this._def.out._parseSync({
          data: inResult.value,
          path: ctx.path,
          parent: ctx
        });
      }
    }
  }
  static create(a2, b10) {
    return new _ZodPipeline({
      in: a2,
      out: b10,
      typeName: ZodFirstPartyTypeKind.ZodPipeline
    });
  }
};
var ZodReadonly = class extends ZodType {
  _parse(input) {
    const result = this._def.innerType._parse(input);
    const freeze = (data) => {
      if (isValid(data)) {
        data.value = Object.freeze(data.value);
      }
      return data;
    };
    return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);
  }
  unwrap() {
    return this._def.innerType;
  }
};
ZodReadonly.create = (type, params) => {
  return new ZodReadonly({
    innerType: type,
    typeName: ZodFirstPartyTypeKind.ZodReadonly,
    ...processCreateParams(params)
  });
};
var late = {
  object: ZodObject.lazycreate
};
var ZodFirstPartyTypeKind;
(function(ZodFirstPartyTypeKind3) {
  ZodFirstPartyTypeKind3["ZodString"] = "ZodString";
  ZodFirstPartyTypeKind3["ZodNumber"] = "ZodNumber";
  ZodFirstPartyTypeKind3["ZodNaN"] = "ZodNaN";
  ZodFirstPartyTypeKind3["ZodBigInt"] = "ZodBigInt";
  ZodFirstPartyTypeKind3["ZodBoolean"] = "ZodBoolean";
  ZodFirstPartyTypeKind3["ZodDate"] = "ZodDate";
  ZodFirstPartyTypeKind3["ZodSymbol"] = "ZodSymbol";
  ZodFirstPartyTypeKind3["ZodUndefined"] = "ZodUndefined";
  ZodFirstPartyTypeKind3["ZodNull"] = "ZodNull";
  ZodFirstPartyTypeKind3["ZodAny"] = "ZodAny";
  ZodFirstPartyTypeKind3["ZodUnknown"] = "ZodUnknown";
  ZodFirstPartyTypeKind3["ZodNever"] = "ZodNever";
  ZodFirstPartyTypeKind3["ZodVoid"] = "ZodVoid";
  ZodFirstPartyTypeKind3["ZodArray"] = "ZodArray";
  ZodFirstPartyTypeKind3["ZodObject"] = "ZodObject";
  ZodFirstPartyTypeKind3["ZodUnion"] = "ZodUnion";
  ZodFirstPartyTypeKind3["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion";
  ZodFirstPartyTypeKind3["ZodIntersection"] = "ZodIntersection";
  ZodFirstPartyTypeKind3["ZodTuple"] = "ZodTuple";
  ZodFirstPartyTypeKind3["ZodRecord"] = "ZodRecord";
  ZodFirstPartyTypeKind3["ZodMap"] = "ZodMap";
  ZodFirstPartyTypeKind3["ZodSet"] = "ZodSet";
  ZodFirstPartyTypeKind3["ZodFunction"] = "ZodFunction";
  ZodFirstPartyTypeKind3["ZodLazy"] = "ZodLazy";
  ZodFirstPartyTypeKind3["ZodLiteral"] = "ZodLiteral";
  ZodFirstPartyTypeKind3["ZodEnum"] = "ZodEnum";
  ZodFirstPartyTypeKind3["ZodEffects"] = "ZodEffects";
  ZodFirstPartyTypeKind3["ZodNativeEnum"] = "ZodNativeEnum";
  ZodFirstPartyTypeKind3["ZodOptional"] = "ZodOptional";
  ZodFirstPartyTypeKind3["ZodNullable"] = "ZodNullable";
  ZodFirstPartyTypeKind3["ZodDefault"] = "ZodDefault";
  ZodFirstPartyTypeKind3["ZodCatch"] = "ZodCatch";
  ZodFirstPartyTypeKind3["ZodPromise"] = "ZodPromise";
  ZodFirstPartyTypeKind3["ZodBranded"] = "ZodBranded";
  ZodFirstPartyTypeKind3["ZodPipeline"] = "ZodPipeline";
  ZodFirstPartyTypeKind3["ZodReadonly"] = "ZodReadonly";
})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));
var stringType = ZodString.create;
var numberType = ZodNumber.create;
var nanType = ZodNaN.create;
var bigIntType = ZodBigInt.create;
var booleanType = ZodBoolean.create;
var dateType = ZodDate.create;
var symbolType = ZodSymbol.create;
var undefinedType = ZodUndefined.create;
var nullType = ZodNull.create;
var anyType = ZodAny.create;
var unknownType = ZodUnknown.create;
var neverType = ZodNever.create;
var voidType = ZodVoid.create;
var arrayType = ZodArray.create;
var objectType = ZodObject.create;
var strictObjectType = ZodObject.strictCreate;
var unionType = ZodUnion.create;
var discriminatedUnionType = ZodDiscriminatedUnion.create;
var intersectionType = ZodIntersection.create;
var tupleType = ZodTuple.create;
var recordType = ZodRecord.create;
var mapType = ZodMap.create;
var setType = ZodSet.create;
var functionType = ZodFunction.create;
var lazyType = ZodLazy.create;
var literalType = ZodLiteral.create;
var enumType = ZodEnum.create;
var nativeEnumType = ZodNativeEnum.create;
var promiseType = ZodPromise.create;
var effectsType = ZodEffects.create;
var optionalType = ZodOptional.create;
var nullableType = ZodNullable.create;
var preprocessType = ZodEffects.createWithPreprocess;
var pipelineType = ZodPipeline.create;

// node_modules/zod/v4/core/index.js
var core_exports2 = {};
__export(core_exports2, {
  $ZodAny: () => $ZodAny,
  $ZodArray: () => $ZodArray,
  $ZodAsyncError: () => $ZodAsyncError,
  $ZodBase64: () => $ZodBase64,
  $ZodBase64URL: () => $ZodBase64URL,
  $ZodBigInt: () => $ZodBigInt,
  $ZodBigIntFormat: () => $ZodBigIntFormat,
  $ZodBoolean: () => $ZodBoolean,
  $ZodCIDRv4: () => $ZodCIDRv4,
  $ZodCIDRv6: () => $ZodCIDRv6,
  $ZodCUID: () => $ZodCUID,
  $ZodCUID2: () => $ZodCUID2,
  $ZodCatch: () => $ZodCatch,
  $ZodCheck: () => $ZodCheck,
  $ZodCheckBigIntFormat: () => $ZodCheckBigIntFormat,
  $ZodCheckEndsWith: () => $ZodCheckEndsWith,
  $ZodCheckGreaterThan: () => $ZodCheckGreaterThan,
  $ZodCheckIncludes: () => $ZodCheckIncludes,
  $ZodCheckLengthEquals: () => $ZodCheckLengthEquals,
  $ZodCheckLessThan: () => $ZodCheckLessThan,
  $ZodCheckLowerCase: () => $ZodCheckLowerCase,
  $ZodCheckMaxLength: () => $ZodCheckMaxLength,
  $ZodCheckMaxSize: () => $ZodCheckMaxSize,
  $ZodCheckMimeType: () => $ZodCheckMimeType,
  $ZodCheckMinLength: () => $ZodCheckMinLength,
  $ZodCheckMinSize: () => $ZodCheckMinSize,
  $ZodCheckMultipleOf: () => $ZodCheckMultipleOf,
  $ZodCheckNumberFormat: () => $ZodCheckNumberFormat,
  $ZodCheckOverwrite: () => $ZodCheckOverwrite,
  $ZodCheckProperty: () => $ZodCheckProperty,
  $ZodCheckRegex: () => $ZodCheckRegex,
  $ZodCheckSizeEquals: () => $ZodCheckSizeEquals,
  $ZodCheckStartsWith: () => $ZodCheckStartsWith,
  $ZodCheckStringFormat: () => $ZodCheckStringFormat,
  $ZodCheckUpperCase: () => $ZodCheckUpperCase,
  $ZodCodec: () => $ZodCodec,
  $ZodCustom: () => $ZodCustom,
  $ZodCustomStringFormat: () => $ZodCustomStringFormat,
  $ZodDate: () => $ZodDate,
  $ZodDefault: () => $ZodDefault,
  $ZodDiscriminatedUnion: () => $ZodDiscriminatedUnion,
  $ZodE164: () => $ZodE164,
  $ZodEmail: () => $ZodEmail,
  $ZodEmoji: () => $ZodEmoji,
  $ZodEncodeError: () => $ZodEncodeError,
  $ZodEnum: () => $ZodEnum,
  $ZodError: () => $ZodError,
  $ZodExactOptional: () => $ZodExactOptional,
  $ZodFile: () => $ZodFile,
  $ZodFunction: () => $ZodFunction,
  $ZodGUID: () => $ZodGUID,
  $ZodIPv4: () => $ZodIPv4,
  $ZodIPv6: () => $ZodIPv6,
  $ZodISODate: () => $ZodISODate,
  $ZodISODateTime: () => $ZodISODateTime,
  $ZodISODuration: () => $ZodISODuration,
  $ZodISOTime: () => $ZodISOTime,
  $ZodIntersection: () => $ZodIntersection,
  $ZodJWT: () => $ZodJWT,
  $ZodKSUID: () => $ZodKSUID,
  $ZodLazy: () => $ZodLazy,
  $ZodLiteral: () => $ZodLiteral,
  $ZodMAC: () => $ZodMAC,
  $ZodMap: () => $ZodMap,
  $ZodNaN: () => $ZodNaN,
  $ZodNanoID: () => $ZodNanoID,
  $ZodNever: () => $ZodNever,
  $ZodNonOptional: () => $ZodNonOptional,
  $ZodNull: () => $ZodNull,
  $ZodNullable: () => $ZodNullable,
  $ZodNumber: () => $ZodNumber,
  $ZodNumberFormat: () => $ZodNumberFormat,
  $ZodObject: () => $ZodObject,
  $ZodObjectJIT: () => $ZodObjectJIT,
  $ZodOptional: () => $ZodOptional,
  $ZodPipe: () => $ZodPipe,
  $ZodPrefault: () => $ZodPrefault,
  $ZodPromise: () => $ZodPromise,
  $ZodReadonly: () => $ZodReadonly,
  $ZodRealError: () => $ZodRealError,
  $ZodRecord: () => $ZodRecord,
  $ZodRegistry: () => $ZodRegistry,
  $ZodSet: () => $ZodSet,
  $ZodString: () => $ZodString,
  $ZodStringFormat: () => $ZodStringFormat,
  $ZodSuccess: () => $ZodSuccess,
  $ZodSymbol: () => $ZodSymbol,
  $ZodTemplateLiteral: () => $ZodTemplateLiteral,
  $ZodTransform: () => $ZodTransform,
  $ZodTuple: () => $ZodTuple,
  $ZodType: () => $ZodType,
  $ZodULID: () => $ZodULID,
  $ZodURL: () => $ZodURL,
  $ZodUUID: () => $ZodUUID,
  $ZodUndefined: () => $ZodUndefined,
  $ZodUnion: () => $ZodUnion,
  $ZodUnknown: () => $ZodUnknown,
  $ZodVoid: () => $ZodVoid,
  $ZodXID: () => $ZodXID,
  $ZodXor: () => $ZodXor,
  $brand: () => $brand,
  $constructor: () => $constructor,
  $input: () => $input,
  $output: () => $output,
  Doc: () => Doc,
  JSONSchema: () => json_schema_exports,
  JSONSchemaGenerator: () => JSONSchemaGenerator,
  NEVER: () => NEVER,
  TimePrecision: () => TimePrecision,
  _any: () => _any,
  _array: () => _array,
  _base64: () => _base64,
  _base64url: () => _base64url,
  _bigint: () => _bigint,
  _boolean: () => _boolean,
  _catch: () => _catch,
  _check: () => _check,
  _cidrv4: () => _cidrv4,
  _cidrv6: () => _cidrv6,
  _coercedBigint: () => _coercedBigint,
  _coercedBoolean: () => _coercedBoolean,
  _coercedDate: () => _coercedDate,
  _coercedNumber: () => _coercedNumber,
  _coercedString: () => _coercedString,
  _cuid: () => _cuid,
  _cuid2: () => _cuid2,
  _custom: () => _custom,
  _date: () => _date,
  _decode: () => _decode,
  _decodeAsync: () => _decodeAsync,
  _default: () => _default,
  _discriminatedUnion: () => _discriminatedUnion,
  _e164: () => _e164,
  _email: () => _email,
  _emoji: () => _emoji2,
  _encode: () => _encode,
  _encodeAsync: () => _encodeAsync,
  _endsWith: () => _endsWith,
  _enum: () => _enum,
  _file: () => _file,
  _float32: () => _float32,
  _float64: () => _float64,
  _gt: () => _gt,
  _gte: () => _gte,
  _guid: () => _guid,
  _includes: () => _includes,
  _int: () => _int,
  _int32: () => _int32,
  _int64: () => _int64,
  _intersection: () => _intersection,
  _ipv4: () => _ipv4,
  _ipv6: () => _ipv6,
  _isoDate: () => _isoDate,
  _isoDateTime: () => _isoDateTime,
  _isoDuration: () => _isoDuration,
  _isoTime: () => _isoTime,
  _jwt: () => _jwt,
  _ksuid: () => _ksuid,
  _lazy: () => _lazy,
  _length: () => _length,
  _literal: () => _literal,
  _lowercase: () => _lowercase,
  _lt: () => _lt,
  _lte: () => _lte,
  _mac: () => _mac,
  _map: () => _map,
  _max: () => _lte,
  _maxLength: () => _maxLength,
  _maxSize: () => _maxSize,
  _mime: () => _mime,
  _min: () => _gte,
  _minLength: () => _minLength,
  _minSize: () => _minSize,
  _multipleOf: () => _multipleOf,
  _nan: () => _nan,
  _nanoid: () => _nanoid,
  _nativeEnum: () => _nativeEnum,
  _negative: () => _negative,
  _never: () => _never,
  _nonnegative: () => _nonnegative,
  _nonoptional: () => _nonoptional,
  _nonpositive: () => _nonpositive,
  _normalize: () => _normalize,
  _null: () => _null2,
  _nullable: () => _nullable,
  _number: () => _number,
  _optional: () => _optional,
  _overwrite: () => _overwrite,
  _parse: () => _parse,
  _parseAsync: () => _parseAsync,
  _pipe: () => _pipe,
  _positive: () => _positive,
  _promise: () => _promise,
  _property: () => _property,
  _readonly: () => _readonly,
  _record: () => _record,
  _refine: () => _refine,
  _regex: () => _regex,
  _safeDecode: () => _safeDecode,
  _safeDecodeAsync: () => _safeDecodeAsync,
  _safeEncode: () => _safeEncode,
  _safeEncodeAsync: () => _safeEncodeAsync,
  _safeParse: () => _safeParse,
  _safeParseAsync: () => _safeParseAsync,
  _set: () => _set,
  _size: () => _size,
  _slugify: () => _slugify,
  _startsWith: () => _startsWith,
  _string: () => _string,
  _stringFormat: () => _stringFormat,
  _stringbool: () => _stringbool,
  _success: () => _success,
  _superRefine: () => _superRefine,
  _symbol: () => _symbol,
  _templateLiteral: () => _templateLiteral,
  _toLowerCase: () => _toLowerCase,
  _toUpperCase: () => _toUpperCase,
  _transform: () => _transform,
  _trim: () => _trim,
  _tuple: () => _tuple,
  _uint32: () => _uint32,
  _uint64: () => _uint64,
  _ulid: () => _ulid,
  _undefined: () => _undefined2,
  _union: () => _union,
  _unknown: () => _unknown,
  _uppercase: () => _uppercase,
  _url: () => _url,
  _uuid: () => _uuid,
  _uuidv4: () => _uuidv4,
  _uuidv6: () => _uuidv6,
  _uuidv7: () => _uuidv7,
  _void: () => _void,
  _xid: () => _xid,
  _xor: () => _xor,
  clone: () => clone,
  config: () => config,
  createStandardJSONSchemaMethod: () => createStandardJSONSchemaMethod,
  createToJSONSchemaMethod: () => createToJSONSchemaMethod,
  decode: () => decode,
  decodeAsync: () => decodeAsync,
  describe: () => describe,
  encode: () => encode,
  encodeAsync: () => encodeAsync,
  extractDefs: () => extractDefs,
  finalize: () => finalize,
  flattenError: () => flattenError,
  formatError: () => formatError,
  globalConfig: () => globalConfig,
  globalRegistry: () => globalRegistry,
  initializeContext: () => initializeContext,
  isValidBase64: () => isValidBase64,
  isValidBase64URL: () => isValidBase64URL,
  isValidJWT: () => isValidJWT2,
  locales: () => locales_exports,
  meta: () => meta,
  parse: () => parse,
  parseAsync: () => parseAsync,
  prettifyError: () => prettifyError,
  process: () => process2,
  regexes: () => regexes_exports,
  registry: () => registry,
  safeDecode: () => safeDecode,
  safeDecodeAsync: () => safeDecodeAsync,
  safeEncode: () => safeEncode,
  safeEncodeAsync: () => safeEncodeAsync,
  safeParse: () => safeParse,
  safeParseAsync: () => safeParseAsync,
  toDotPath: () => toDotPath,
  toJSONSchema: () => toJSONSchema,
  treeifyError: () => treeifyError,
  util: () => util_exports,
  version: () => version
});

// node_modules/zod/v4/core/core.js
var NEVER = Object.freeze({
  status: "aborted"
});
// @__NO_SIDE_EFFECTS__
function $constructor(name, initializer3, params) {
  var _a3;
  function init(inst, def) {
    if (!inst._zod) {
      Object.defineProperty(inst, "_zod", {
        value: {
          def,
          constr: _10,
          traits: /* @__PURE__ */ new Set()
        },
        enumerable: false
      });
    }
    if (inst._zod.traits.has(name)) {
      return;
    }
    inst._zod.traits.add(name);
    initializer3(inst, def);
    const proto = _10.prototype;
    const keys = Object.keys(proto);
    for (let i2 = 0; i2 < keys.length; i2++) {
      const k10 = keys[i2];
      if (!(k10 in inst)) {
        inst[k10] = proto[k10].bind(inst);
      }
    }
  }
  const Parent = (_a3 = params == null ? void 0 : params.Parent) != null ? _a3 : Object;
  class Definition extends Parent {
  }
  Object.defineProperty(Definition, "name", { value: name });
  function _10(def) {
    var _a5;
    var _a4;
    const inst = (params == null ? void 0 : params.Parent) ? new Definition() : this;
    init(inst, def);
    (_a5 = (_a4 = inst._zod).deferred) != null ? _a5 : _a4.deferred = [];
    for (const fn of inst._zod.deferred) {
      fn();
    }
    return inst;
  }
  Object.defineProperty(_10, "init", { value: init });
  Object.defineProperty(_10, Symbol.hasInstance, {
    value: (inst) => {
      var _a4, _b2;
      if ((params == null ? void 0 : params.Parent) && inst instanceof params.Parent)
        return true;
      return (_b2 = (_a4 = inst == null ? void 0 : inst._zod) == null ? void 0 : _a4.traits) == null ? void 0 : _b2.has(name);
    }
  });
  Object.defineProperty(_10, "name", { value: name });
  return _10;
}
var $brand = /* @__PURE__ */ Symbol("zod_brand");
var $ZodAsyncError = class extends Error {
  constructor() {
    super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`);
  }
};
var $ZodEncodeError = class extends Error {
  constructor(name) {
    super(`Encountered unidirectional transform during encode: ${name}`);
    this.name = "ZodEncodeError";
  }
};
var globalConfig = {};
function config(newConfig) {
  if (newConfig)
    Object.assign(globalConfig, newConfig);
  return globalConfig;
}

// node_modules/zod/v4/core/util.js
var util_exports = {};
__export(util_exports, {
  BIGINT_FORMAT_RANGES: () => BIGINT_FORMAT_RANGES,
  Class: () => Class,
  NUMBER_FORMAT_RANGES: () => NUMBER_FORMAT_RANGES,
  aborted: () => aborted,
  allowsEval: () => allowsEval,
  assert: () => assert,
  assertEqual: () => assertEqual,
  assertIs: () => assertIs,
  assertNever: () => assertNever,
  assertNotEqual: () => assertNotEqual,
  assignProp: () => assignProp,
  base64ToUint8Array: () => base64ToUint8Array,
  base64urlToUint8Array: () => base64urlToUint8Array,
  cached: () => cached,
  captureStackTrace: () => captureStackTrace,
  cleanEnum: () => cleanEnum,
  cleanRegex: () => cleanRegex,
  clone: () => clone,
  cloneDef: () => cloneDef,
  createTransparentProxy: () => createTransparentProxy,
  defineLazy: () => defineLazy,
  esc: () => esc,
  escapeRegex: () => escapeRegex,
  extend: () => extend,
  finalizeIssue: () => finalizeIssue,
  floatSafeRemainder: () => floatSafeRemainder2,
  getElementAtPath: () => getElementAtPath,
  getEnumValues: () => getEnumValues,
  getLengthableOrigin: () => getLengthableOrigin,
  getParsedType: () => getParsedType2,
  getSizableOrigin: () => getSizableOrigin,
  hexToUint8Array: () => hexToUint8Array,
  isObject: () => isObject,
  isPlainObject: () => isPlainObject,
  issue: () => issue,
  joinValues: () => joinValues,
  jsonStringifyReplacer: () => jsonStringifyReplacer,
  merge: () => merge,
  mergeDefs: () => mergeDefs,
  normalizeParams: () => normalizeParams,
  nullish: () => nullish,
  numKeys: () => numKeys,
  objectClone: () => objectClone,
  omit: () => omit,
  optionalKeys: () => optionalKeys,
  parsedType: () => parsedType,
  partial: () => partial,
  pick: () => pick,
  prefixIssues: () => prefixIssues,
  primitiveTypes: () => primitiveTypes,
  promiseAllObject: () => promiseAllObject,
  propertyKeyTypes: () => propertyKeyTypes,
  randomString: () => randomString,
  required: () => required,
  safeExtend: () => safeExtend,
  shallowClone: () => shallowClone,
  slugify: () => slugify,
  stringifyPrimitive: () => stringifyPrimitive,
  uint8ArrayToBase64: () => uint8ArrayToBase64,
  uint8ArrayToBase64url: () => uint8ArrayToBase64url,
  uint8ArrayToHex: () => uint8ArrayToHex,
  unwrapMessage: () => unwrapMessage
});
function assertEqual(val) {
  return val;
}
function assertNotEqual(val) {
  return val;
}
function assertIs(_arg) {
}
function assertNever(_x) {
  throw new Error("Unexpected value in exhaustive check");
}
function assert(_10) {
}
function getEnumValues(entries) {
  const numericValues = Object.values(entries).filter((v2) => typeof v2 === "number");
  const values = Object.entries(entries).filter(([k10, _10]) => numericValues.indexOf(+k10) === -1).map(([_10, v2]) => v2);
  return values;
}
function joinValues(array2, separator = "|") {
  return array2.map((val) => stringifyPrimitive(val)).join(separator);
}
function jsonStringifyReplacer(_10, value) {
  if (typeof value === "bigint")
    return value.toString();
  return value;
}
function cached(getter) {
  const set2 = false;
  return {
    get value() {
      if (!set2) {
        const value = getter();
        Object.defineProperty(this, "value", { value });
        return value;
      }
      throw new Error("cached value already set");
    }
  };
}
function nullish(input) {
  return input === null || input === void 0;
}
function cleanRegex(source) {
  const start = source.startsWith("^") ? 1 : 0;
  const end = source.endsWith("$") ? source.length - 1 : source.length;
  return source.slice(start, end);
}
function floatSafeRemainder2(val, step) {
  const valDecCount = (val.toString().split(".")[1] || "").length;
  const stepString = step.toString();
  let stepDecCount = (stepString.split(".")[1] || "").length;
  if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) {
    const match = stepString.match(/\d?e-(\d?)/);
    if (match == null ? void 0 : match[1]) {
      stepDecCount = Number.parseInt(match[1]);
    }
  }
  const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;
  const valInt = Number.parseInt(val.toFixed(decCount).replace(".", ""));
  const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", ""));
  return valInt % stepInt / 10 ** decCount;
}
var EVALUATING = /* @__PURE__ */ Symbol("evaluating");
function defineLazy(object3, key, getter) {
  let value = void 0;
  Object.defineProperty(object3, key, {
    get() {
      if (value === EVALUATING) {
        return void 0;
      }
      if (value === void 0) {
        value = EVALUATING;
        value = getter();
      }
      return value;
    },
    set(v2) {
      Object.defineProperty(object3, key, {
        value: v2
        // configurable: true,
      });
    },
    configurable: true
  });
}
function objectClone(obj) {
  return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
}
function assignProp(target, prop, value) {
  Object.defineProperty(target, prop, {
    value,
    writable: true,
    enumerable: true,
    configurable: true
  });
}
function mergeDefs(...defs) {
  const mergedDescriptors = {};
  for (const def of defs) {
    const descriptors = Object.getOwnPropertyDescriptors(def);
    Object.assign(mergedDescriptors, descriptors);
  }
  return Object.defineProperties({}, mergedDescriptors);
}
function cloneDef(schema) {
  return mergeDefs(schema._zod.def);
}
function getElementAtPath(obj, path24) {
  if (!path24)
    return obj;
  return path24.reduce((acc, key) => acc == null ? void 0 : acc[key], obj);
}
function promiseAllObject(promisesObj) {
  const keys = Object.keys(promisesObj);
  const promises2 = keys.map((key) => promisesObj[key]);
  return Promise.all(promises2).then((results) => {
    const resolvedObj = {};
    for (let i2 = 0; i2 < keys.length; i2++) {
      resolvedObj[keys[i2]] = results[i2];
    }
    return resolvedObj;
  });
}
function randomString(length = 10) {
  const chars = "abcdefghijklmnopqrstuvwxyz";
  let str = "";
  for (let i2 = 0; i2 < length; i2++) {
    str += chars[Math.floor(Math.random() * chars.length)];
  }
  return str;
}
function esc(str) {
  return JSON.stringify(str);
}
function slugify(input) {
  return input.toLowerCase().trim().replace(/[^\w\s-]/g, "").replace(/[\s_-]+/g, "-").replace(/^-+|-+$/g, "");
}
var captureStackTrace = "captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => {
};
function isObject(data) {
  return typeof data === "object" && data !== null && !Array.isArray(data);
}
var allowsEval = cached(() => {
  var _a3;
  if (typeof navigator !== "undefined" && ((_a3 = navigator == null ? void 0 : navigator.userAgent) == null ? void 0 : _a3.includes("Cloudflare"))) {
    return false;
  }
  try {
    const F5 = Function;
    new F5("");
    return true;
  } catch (_10) {
    return false;
  }
});
function isPlainObject(o2) {
  if (isObject(o2) === false)
    return false;
  const ctor = o2.constructor;
  if (ctor === void 0)
    return true;
  if (typeof ctor !== "function")
    return true;
  const prot = ctor.prototype;
  if (isObject(prot) === false)
    return false;
  if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) {
    return false;
  }
  return true;
}
function shallowClone(o2) {
  if (isPlainObject(o2))
    return { ...o2 };
  if (Array.isArray(o2))
    return [...o2];
  return o2;
}
function numKeys(data) {
  let keyCount = 0;
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      keyCount++;
    }
  }
  return keyCount;
}
var getParsedType2 = (data) => {
  const t2 = typeof data;
  switch (t2) {
    case "undefined":
      return "undefined";
    case "string":
      return "string";
    case "number":
      return Number.isNaN(data) ? "nan" : "number";
    case "boolean":
      return "boolean";
    case "function":
      return "function";
    case "bigint":
      return "bigint";
    case "symbol":
      return "symbol";
    case "object":
      if (Array.isArray(data)) {
        return "array";
      }
      if (data === null) {
        return "null";
      }
      if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") {
        return "promise";
      }
      if (typeof Map !== "undefined" && data instanceof Map) {
        return "map";
      }
      if (typeof Set !== "undefined" && data instanceof Set) {
        return "set";
      }
      if (typeof Date !== "undefined" && data instanceof Date) {
        return "date";
      }
      if (typeof File !== "undefined" && data instanceof File) {
        return "file";
      }
      return "object";
    default:
      throw new Error(`Unknown data type: ${t2}`);
  }
};
var propertyKeyTypes = /* @__PURE__ */ new Set(["string", "number", "symbol"]);
var primitiveTypes = /* @__PURE__ */ new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]);
function escapeRegex(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function clone(inst, def, params) {
  const cl = new inst._zod.constr(def != null ? def : inst._zod.def);
  if (!def || (params == null ? void 0 : params.parent))
    cl._zod.parent = inst;
  return cl;
}
function normalizeParams(_params) {
  const params = _params;
  if (!params)
    return {};
  if (typeof params === "string")
    return { error: () => params };
  if ((params == null ? void 0 : params.message) !== void 0) {
    if ((params == null ? void 0 : params.error) !== void 0)
      throw new Error("Cannot specify both `message` and `error` params");
    params.error = params.message;
  }
  delete params.message;
  if (typeof params.error === "string")
    return { ...params, error: () => params.error };
  return params;
}
function createTransparentProxy(getter) {
  let target;
  return new Proxy({}, {
    get(_10, prop, receiver) {
      target != null ? target : target = getter();
      return Reflect.get(target, prop, receiver);
    },
    set(_10, prop, value, receiver) {
      target != null ? target : target = getter();
      return Reflect.set(target, prop, value, receiver);
    },
    has(_10, prop) {
      target != null ? target : target = getter();
      return Reflect.has(target, prop);
    },
    deleteProperty(_10, prop) {
      target != null ? target : target = getter();
      return Reflect.deleteProperty(target, prop);
    },
    ownKeys(_10) {
      target != null ? target : target = getter();
      return Reflect.ownKeys(target);
    },
    getOwnPropertyDescriptor(_10, prop) {
      target != null ? target : target = getter();
      return Reflect.getOwnPropertyDescriptor(target, prop);
    },
    defineProperty(_10, prop, descriptor) {
      target != null ? target : target = getter();
      return Reflect.defineProperty(target, prop, descriptor);
    }
  });
}
function stringifyPrimitive(value) {
  if (typeof value === "bigint")
    return value.toString() + "n";
  if (typeof value === "string")
    return `"${value}"`;
  return `${value}`;
}
function optionalKeys(shape) {
  return Object.keys(shape).filter((k10) => {
    return shape[k10]._zod.optin === "optional" && shape[k10]._zod.optout === "optional";
  });
}
var NUMBER_FORMAT_RANGES = {
  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]
};
var BIGINT_FORMAT_RANGES = {
  int64: [/* @__PURE__ */ BigInt("-9223372036854775808"), /* @__PURE__ */ BigInt("9223372036854775807")],
  uint64: [/* @__PURE__ */ BigInt(0), /* @__PURE__ */ BigInt("18446744073709551615")]
};
function pick(schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".pick() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const newShape = {};
      for (const key in mask) {
        if (!(key in currDef.shape)) {
          throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
          continue;
        newShape[key] = currDef.shape[key];
      }
      assignProp(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone(schema, def);
}
function omit(schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".omit() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const newShape = { ...schema._zod.def.shape };
      for (const key in mask) {
        if (!(key in currDef.shape)) {
          throw new Error(`Unrecognized key: "${key}"`);
        }
        if (!mask[key])
          continue;
        delete newShape[key];
      }
      assignProp(this, "shape", newShape);
      return newShape;
    },
    checks: []
  });
  return clone(schema, def);
}
function extend(schema, shape) {
  if (!isPlainObject(shape)) {
    throw new Error("Invalid input to extend: expected a plain object");
  }
  const checks = schema._zod.def.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    const existingShape = schema._zod.def.shape;
    for (const key in shape) {
      if (Object.getOwnPropertyDescriptor(existingShape, key) !== void 0) {
        throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.");
      }
    }
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp(this, "shape", _shape);
      return _shape;
    }
  });
  return clone(schema, def);
}
function safeExtend(schema, shape) {
  if (!isPlainObject(shape)) {
    throw new Error("Invalid input to safeExtend: expected a plain object");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const _shape = { ...schema._zod.def.shape, ...shape };
      assignProp(this, "shape", _shape);
      return _shape;
    }
  });
  return clone(schema, def);
}
function merge(a2, b10) {
  const def = mergeDefs(a2._zod.def, {
    get shape() {
      const _shape = { ...a2._zod.def.shape, ...b10._zod.def.shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    get catchall() {
      return b10._zod.def.catchall;
    },
    checks: []
    // delete existing checks
  });
  return clone(a2, def);
}
function partial(Class2, schema, mask) {
  const currDef = schema._zod.def;
  const checks = currDef.checks;
  const hasChecks = checks && checks.length > 0;
  if (hasChecks) {
    throw new Error(".partial() cannot be used on object schemas containing refinements");
  }
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const oldShape = schema._zod.def.shape;
      const shape = { ...oldShape };
      if (mask) {
        for (const key in mask) {
          if (!(key in oldShape)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          shape[key] = Class2 ? new Class2({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      } else {
        for (const key in oldShape) {
          shape[key] = Class2 ? new Class2({
            type: "optional",
            innerType: oldShape[key]
          }) : oldShape[key];
        }
      }
      assignProp(this, "shape", shape);
      return shape;
    },
    checks: []
  });
  return clone(schema, def);
}
function required(Class2, schema, mask) {
  const def = mergeDefs(schema._zod.def, {
    get shape() {
      const oldShape = schema._zod.def.shape;
      const shape = { ...oldShape };
      if (mask) {
        for (const key in mask) {
          if (!(key in shape)) {
            throw new Error(`Unrecognized key: "${key}"`);
          }
          if (!mask[key])
            continue;
          shape[key] = new Class2({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      } else {
        for (const key in oldShape) {
          shape[key] = new Class2({
            type: "nonoptional",
            innerType: oldShape[key]
          });
        }
      }
      assignProp(this, "shape", shape);
      return shape;
    }
  });
  return clone(schema, def);
}
function aborted(x, startIndex = 0) {
  var _a3;
  if (x.aborted === true)
    return true;
  for (let i2 = startIndex; i2 < x.issues.length; i2++) {
    if (((_a3 = x.issues[i2]) == null ? void 0 : _a3.continue) !== true) {
      return true;
    }
  }
  return false;
}
function prefixIssues(path24, issues) {
  return issues.map((iss) => {
    var _a4;
    var _a3;
    (_a4 = (_a3 = iss).path) != null ? _a4 : _a3.path = [];
    iss.path.unshift(path24);
    return iss;
  });
}
function unwrapMessage(message) {
  return typeof message === "string" ? message : message == null ? void 0 : message.message;
}
function finalizeIssue(iss, ctx, config2) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k;
  const full = { ...iss, path: (_a3 = iss.path) != null ? _a3 : [] };
  if (!iss.message) {
    const message = (_k = (_j2 = (_h = (_f = unwrapMessage((_d2 = (_c = (_b2 = iss.inst) == null ? void 0 : _b2._zod.def) == null ? void 0 : _c.error) == null ? void 0 : _d2.call(_c, iss))) != null ? _f : unwrapMessage((_e = ctx == null ? void 0 : ctx.error) == null ? void 0 : _e.call(ctx, iss))) != null ? _h : unwrapMessage((_g = config2.customError) == null ? void 0 : _g.call(config2, iss))) != null ? _j2 : unwrapMessage((_i = config2.localeError) == null ? void 0 : _i.call(config2, iss))) != null ? _k : "Invalid input";
    full.message = message;
  }
  delete full.inst;
  delete full.continue;
  if (!(ctx == null ? void 0 : ctx.reportInput)) {
    delete full.input;
  }
  return full;
}
function getSizableOrigin(input) {
  if (input instanceof Set)
    return "set";
  if (input instanceof Map)
    return "map";
  if (input instanceof File)
    return "file";
  return "unknown";
}
function getLengthableOrigin(input) {
  if (Array.isArray(input))
    return "array";
  if (typeof input === "string")
    return "string";
  return "unknown";
}
function parsedType(data) {
  const t2 = typeof data;
  switch (t2) {
    case "number": {
      return Number.isNaN(data) ? "nan" : "number";
    }
    case "object": {
      if (data === null) {
        return "null";
      }
      if (Array.isArray(data)) {
        return "array";
      }
      const obj = data;
      if (obj && Object.getPrototypeOf(obj) !== Object.prototype && "constructor" in obj && obj.constructor) {
        return obj.constructor.name;
      }
    }
  }
  return t2;
}
function issue(...args) {
  const [iss, input, inst] = args;
  if (typeof iss === "string") {
    return {
      message: iss,
      code: "custom",
      input,
      inst
    };
  }
  return { ...iss };
}
function cleanEnum(obj) {
  return Object.entries(obj).filter(([k10, _10]) => {
    return Number.isNaN(Number.parseInt(k10, 10));
  }).map((el) => el[1]);
}
function base64ToUint8Array(base643) {
  const binaryString = atob(base643);
  const bytes = new Uint8Array(binaryString.length);
  for (let i2 = 0; i2 < binaryString.length; i2++) {
    bytes[i2] = binaryString.charCodeAt(i2);
  }
  return bytes;
}
function uint8ArrayToBase64(bytes) {
  let binaryString = "";
  for (let i2 = 0; i2 < bytes.length; i2++) {
    binaryString += String.fromCharCode(bytes[i2]);
  }
  return btoa(binaryString);
}
function base64urlToUint8Array(base64url3) {
  const base643 = base64url3.replace(/-/g, "+").replace(/_/g, "/");
  const padding = "=".repeat((4 - base643.length % 4) % 4);
  return base64ToUint8Array(base643 + padding);
}
function uint8ArrayToBase64url(bytes) {
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function hexToUint8Array(hex3) {
  const cleanHex = hex3.replace(/^0x/, "");
  if (cleanHex.length % 2 !== 0) {
    throw new Error("Invalid hex string length");
  }
  const bytes = new Uint8Array(cleanHex.length / 2);
  for (let i2 = 0; i2 < cleanHex.length; i2 += 2) {
    bytes[i2 / 2] = Number.parseInt(cleanHex.slice(i2, i2 + 2), 16);
  }
  return bytes;
}
function uint8ArrayToHex(bytes) {
  return Array.from(bytes).map((b10) => b10.toString(16).padStart(2, "0")).join("");
}
var Class = class {
  constructor(..._args) {
  }
};

// node_modules/zod/v4/core/errors.js
var initializer = (inst, def) => {
  inst.name = "$ZodError";
  Object.defineProperty(inst, "_zod", {
    value: inst._zod,
    enumerable: false
  });
  Object.defineProperty(inst, "issues", {
    value: def,
    enumerable: false
  });
  inst.message = JSON.stringify(def, jsonStringifyReplacer, 2);
  Object.defineProperty(inst, "toString", {
    value: () => inst.message,
    enumerable: false
  });
};
var $ZodError = $constructor("$ZodError", initializer);
var $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error });
function flattenError(error48, mapper = (issue2) => issue2.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error48.issues) {
    if (sub.path.length > 0) {
      fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];
      fieldErrors[sub.path[0]].push(mapper(sub));
    } else {
      formErrors.push(mapper(sub));
    }
  }
  return { formErrors, fieldErrors };
}
function formatError(error48, mapper = (issue2) => issue2.message) {
  const fieldErrors = { _errors: [] };
  const processError = (error49) => {
    for (const issue2 of error49.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues });
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues });
      } else if (issue2.path.length === 0) {
        fieldErrors._errors.push(mapper(issue2));
      } else {
        let curr = fieldErrors;
        let i2 = 0;
        while (i2 < issue2.path.length) {
          const el = issue2.path[i2];
          const terminal = i2 === issue2.path.length - 1;
          if (!terminal) {
            curr[el] = curr[el] || { _errors: [] };
          } else {
            curr[el] = curr[el] || { _errors: [] };
            curr[el]._errors.push(mapper(issue2));
          }
          curr = curr[el];
          i2++;
        }
      }
    }
  };
  processError(error48);
  return fieldErrors;
}
function treeifyError(error48, mapper = (issue2) => issue2.message) {
  const result = { errors: [] };
  const processError = (error49, path24 = []) => {
    var _a4, _b3, _c, _d2;
    var _a3, _b2;
    for (const issue2 of error49.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }, issue2.path));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues }, issue2.path);
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues }, issue2.path);
      } else {
        const fullpath = [...path24, ...issue2.path];
        if (fullpath.length === 0) {
          result.errors.push(mapper(issue2));
          continue;
        }
        let curr = result;
        let i2 = 0;
        while (i2 < fullpath.length) {
          const el = fullpath[i2];
          const terminal = i2 === fullpath.length - 1;
          if (typeof el === "string") {
            (_a4 = curr.properties) != null ? _a4 : curr.properties = {};
            (_b3 = (_a3 = curr.properties)[el]) != null ? _b3 : _a3[el] = { errors: [] };
            curr = curr.properties[el];
          } else {
            (_c = curr.items) != null ? _c : curr.items = [];
            (_d2 = (_b2 = curr.items)[el]) != null ? _d2 : _b2[el] = { errors: [] };
            curr = curr.items[el];
          }
          if (terminal) {
            curr.errors.push(mapper(issue2));
          }
          i2++;
        }
      }
    }
  };
  processError(error48);
  return result;
}
function toDotPath(_path) {
  const segs = [];
  const path24 = _path.map((seg) => typeof seg === "object" ? seg.key : seg);
  for (const seg of path24) {
    if (typeof seg === "number")
      segs.push(`[${seg}]`);
    else if (typeof seg === "symbol")
      segs.push(`[${JSON.stringify(String(seg))}]`);
    else if (/[^\w$]/.test(seg))
      segs.push(`[${JSON.stringify(seg)}]`);
    else {
      if (segs.length)
        segs.push(".");
      segs.push(seg);
    }
  }
  return segs.join("");
}
function prettifyError(error48) {
  var _a3;
  const lines = [];
  const issues = [...error48.issues].sort((a2, b10) => {
    var _a4, _b2;
    return ((_a4 = a2.path) != null ? _a4 : []).length - ((_b2 = b10.path) != null ? _b2 : []).length;
  });
  for (const issue2 of issues) {
    lines.push(`\u2716 ${issue2.message}`);
    if ((_a3 = issue2.path) == null ? void 0 : _a3.length)
      lines.push(`  \u2192 at ${toDotPath(issue2.path)}`);
  }
  return lines.join("\n");
}

// node_modules/zod/v4/core/parse.js
var _parse = (_Err) => (schema, value, _ctx, _params) => {
  var _a3;
  const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError();
  }
  if (result.issues.length) {
    const e2 = new ((_a3 = _params == null ? void 0 : _params.Err) != null ? _a3 : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e2, _params == null ? void 0 : _params.callee);
    throw e2;
  }
  return result.value;
};
var parse = /* @__PURE__ */ _parse($ZodRealError);
var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
  var _a3;
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  if (result.issues.length) {
    const e2 = new ((_a3 = params == null ? void 0 : params.Err) != null ? _a3 : _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e2, params == null ? void 0 : params.callee);
    throw e2;
  }
  return result.value;
};
var parseAsync = /* @__PURE__ */ _parseAsync($ZodRealError);
var _safeParse = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, async: false } : { async: false };
  const result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise) {
    throw new $ZodAsyncError();
  }
  return result.issues.length ? {
    success: false,
    error: new (_Err != null ? _Err : $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
var safeParse = /* @__PURE__ */ _safeParse($ZodRealError);
var _safeParseAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true };
  let result = schema._zod.run({ value, issues: [] }, ctx);
  if (result instanceof Promise)
    result = await result;
  return result.issues.length ? {
    success: false,
    error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  } : { success: true, data: result.value };
};
var safeParseAsync = /* @__PURE__ */ _safeParseAsync($ZodRealError);
var _encode = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
  return _parse(_Err)(schema, value, ctx);
};
var encode = /* @__PURE__ */ _encode($ZodRealError);
var _decode = (_Err) => (schema, value, _ctx) => {
  return _parse(_Err)(schema, value, _ctx);
};
var decode = /* @__PURE__ */ _decode($ZodRealError);
var _encodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
  return _parseAsync(_Err)(schema, value, ctx);
};
var encodeAsync = /* @__PURE__ */ _encodeAsync($ZodRealError);
var _decodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _parseAsync(_Err)(schema, value, _ctx);
};
var decodeAsync = /* @__PURE__ */ _decodeAsync($ZodRealError);
var _safeEncode = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
  return _safeParse(_Err)(schema, value, ctx);
};
var safeEncode = /* @__PURE__ */ _safeEncode($ZodRealError);
var _safeDecode = (_Err) => (schema, value, _ctx) => {
  return _safeParse(_Err)(schema, value, _ctx);
};
var safeDecode = /* @__PURE__ */ _safeDecode($ZodRealError);
var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" };
  return _safeParseAsync(_Err)(schema, value, ctx);
};
var safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync($ZodRealError);
var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _safeParseAsync(_Err)(schema, value, _ctx);
};
var safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync($ZodRealError);

// node_modules/zod/v4/core/regexes.js
var regexes_exports = {};
__export(regexes_exports, {
  base64: () => base64,
  base64url: () => base64url,
  bigint: () => bigint,
  boolean: () => boolean,
  browserEmail: () => browserEmail,
  cidrv4: () => cidrv4,
  cidrv6: () => cidrv6,
  cuid: () => cuid,
  cuid2: () => cuid2,
  date: () => date,
  datetime: () => datetime,
  domain: () => domain,
  duration: () => duration,
  e164: () => e164,
  email: () => email,
  emoji: () => emoji,
  extendedDuration: () => extendedDuration,
  guid: () => guid,
  hex: () => hex,
  hostname: () => hostname2,
  html5Email: () => html5Email,
  idnEmail: () => idnEmail,
  integer: () => integer,
  ipv4: () => ipv4,
  ipv6: () => ipv6,
  ksuid: () => ksuid,
  lowercase: () => lowercase,
  mac: () => mac,
  md5_base64: () => md5_base64,
  md5_base64url: () => md5_base64url,
  md5_hex: () => md5_hex,
  nanoid: () => nanoid,
  null: () => _null,
  number: () => number,
  rfc5322Email: () => rfc5322Email,
  sha1_base64: () => sha1_base64,
  sha1_base64url: () => sha1_base64url,
  sha1_hex: () => sha1_hex,
  sha256_base64: () => sha256_base64,
  sha256_base64url: () => sha256_base64url,
  sha256_hex: () => sha256_hex,
  sha384_base64: () => sha384_base64,
  sha384_base64url: () => sha384_base64url,
  sha384_hex: () => sha384_hex,
  sha512_base64: () => sha512_base64,
  sha512_base64url: () => sha512_base64url,
  sha512_hex: () => sha512_hex,
  string: () => string,
  time: () => time,
  ulid: () => ulid,
  undefined: () => _undefined,
  unicodeEmail: () => unicodeEmail,
  uppercase: () => uppercase,
  uuid: () => uuid,
  uuid4: () => uuid4,
  uuid6: () => uuid6,
  uuid7: () => uuid7,
  xid: () => xid
});
var cuid = /^[cC][^\s-]{8,}$/;
var cuid2 = /^[0-9a-z]+$/;
var ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/;
var xid = /^[0-9a-vA-V]{20}$/;
var ksuid = /^[A-Za-z0-9]{27}$/;
var nanoid = /^[a-zA-Z0-9_-]{21}$/;
var duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;
var extendedDuration = /^[-+]?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)?)??$/;
var guid = /^([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})$/;
var uuid = (version2) => {
  if (!version2)
    return /^([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|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;
  return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`);
};
var uuid4 = /* @__PURE__ */ uuid(4);
var uuid6 = /* @__PURE__ */ uuid(6);
var uuid7 = /* @__PURE__ */ uuid(7);
var email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
var html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
var unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u;
var idnEmail = unicodeEmail;
var browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
var _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`;
function emoji() {
  return new RegExp(_emoji, "u");
}
var 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])$/;
var ipv6 = /^(([0-9a-fA-F]{1,4}:){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}|:))$/;
var mac = (delimiter) => {
  const escapedDelim = escapeRegex(delimiter != null ? delimiter : ":");
  return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`);
};
var cidrv4 = /^((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])$/;
var cidrv6 = /^(([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])$/;
var base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/;
var base64url = /^[A-Za-z0-9_-]*$/;
var hostname2 = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/;
var domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/;
var e164 = /^\+[1-9]\d{6,14}$/;
var dateSource = `(?:(?:\\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])))`;
var date = /* @__PURE__ */ new RegExp(`^${dateSource}$`);
function timeSource(args) {
  const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`;
  const regex = typeof args.precision === "number" ? args.precision === -1 ? `${hhmm}` : args.precision === 0 ? `${hhmm}:[0-5]\\d` : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`;
  return regex;
}
function time(args) {
  return new RegExp(`^${timeSource(args)}$`);
}
function datetime(args) {
  const time4 = timeSource({ precision: args.precision });
  const opts = ["Z"];
  if (args.local)
    opts.push("");
  if (args.offset)
    opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);
  const timeRegex2 = `${time4}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource}T(?:${timeRegex2})$`);
}
var string = (params) => {
  var _a3, _b2;
  const regex = params ? `[\\s\\S]{${(_a3 = params == null ? void 0 : params.minimum) != null ? _a3 : 0},${(_b2 = params == null ? void 0 : params.maximum) != null ? _b2 : ""}}` : `[\\s\\S]*`;
  return new RegExp(`^${regex}$`);
};
var bigint = /^-?\d+n?$/;
var integer = /^-?\d+$/;
var number = /^-?\d+(?:\.\d+)?$/;
var boolean = /^(?:true|false)$/i;
var _null = /^null$/i;
var _undefined = /^undefined$/i;
var lowercase = /^[^A-Z]*$/;
var uppercase = /^[^a-z]*$/;
var hex = /^[0-9a-fA-F]*$/;
function fixedBase64(bodyLength, padding) {
  return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`);
}
function fixedBase64url(length) {
  return new RegExp(`^[A-Za-z0-9_-]{${length}}$`);
}
var md5_hex = /^[0-9a-fA-F]{32}$/;
var md5_base64 = /* @__PURE__ */ fixedBase64(22, "==");
var md5_base64url = /* @__PURE__ */ fixedBase64url(22);
var sha1_hex = /^[0-9a-fA-F]{40}$/;
var sha1_base64 = /* @__PURE__ */ fixedBase64(27, "=");
var sha1_base64url = /* @__PURE__ */ fixedBase64url(27);
var sha256_hex = /^[0-9a-fA-F]{64}$/;
var sha256_base64 = /* @__PURE__ */ fixedBase64(43, "=");
var sha256_base64url = /* @__PURE__ */ fixedBase64url(43);
var sha384_hex = /^[0-9a-fA-F]{96}$/;
var sha384_base64 = /* @__PURE__ */ fixedBase64(64, "");
var sha384_base64url = /* @__PURE__ */ fixedBase64url(64);
var sha512_hex = /^[0-9a-fA-F]{128}$/;
var sha512_base64 = /* @__PURE__ */ fixedBase64(86, "==");
var sha512_base64url = /* @__PURE__ */ fixedBase64url(86);

// node_modules/zod/v4/core/checks.js
var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
  var _a4, _b2;
  var _a3;
  (_a4 = inst._zod) != null ? _a4 : inst._zod = {};
  inst._zod.def = def;
  (_b2 = (_a3 = inst._zod).onattach) != null ? _b2 : _a3.onattach = [];
});
var numericOriginMap = {
  number: "number",
  bigint: "bigint",
  object: "date"
};
var $ZodCheckLessThan = /* @__PURE__ */ $constructor("$ZodCheckLessThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    var _a3;
    const bag = inst2._zod.bag;
    const curr = (_a3 = def.inclusive ? bag.maximum : bag.exclusiveMaximum) != null ? _a3 : Number.POSITIVE_INFINITY;
    if (def.value < curr) {
      if (def.inclusive)
        bag.maximum = def.value;
      else
        bag.exclusiveMaximum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value <= def.value : payload.value < def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: typeof def.value === "object" ? def.value.getTime() : def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckGreaterThan = /* @__PURE__ */ $constructor("$ZodCheckGreaterThan", (inst, def) => {
  $ZodCheck.init(inst, def);
  const origin = numericOriginMap[typeof def.value];
  inst._zod.onattach.push((inst2) => {
    var _a3;
    const bag = inst2._zod.bag;
    const curr = (_a3 = def.inclusive ? bag.minimum : bag.exclusiveMinimum) != null ? _a3 : Number.NEGATIVE_INFINITY;
    if (def.value > curr) {
      if (def.inclusive)
        bag.minimum = def.value;
      else
        bag.exclusiveMinimum = def.value;
    }
  });
  inst._zod.check = (payload) => {
    if (def.inclusive ? payload.value >= def.value : payload.value > def.value) {
      return;
    }
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: typeof def.value === "object" ? def.value.getTime() : def.value,
      input: payload.value,
      inclusive: def.inclusive,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMultipleOf = /* @__PURE__ */ $constructor("$ZodCheckMultipleOf", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    var _a4;
    var _a3;
    (_a4 = (_a3 = inst2._zod.bag).multipleOf) != null ? _a4 : _a3.multipleOf = def.value;
  });
  inst._zod.check = (payload) => {
    if (typeof payload.value !== typeof def.value)
      throw new Error("Cannot mix number and bigint in multiple_of check.");
    const isMultiple = typeof payload.value === "bigint" ? payload.value % def.value === BigInt(0) : floatSafeRemainder2(payload.value, def.value) === 0;
    if (isMultiple)
      return;
    payload.issues.push({
      origin: typeof payload.value,
      code: "not_multiple_of",
      divisor: def.value,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckNumberFormat = /* @__PURE__ */ $constructor("$ZodCheckNumberFormat", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  def.format = def.format || "float64";
  const isInt = (_a3 = def.format) == null ? void 0 : _a3.includes("int");
  const origin = isInt ? "int" : "number";
  const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    bag.minimum = minimum;
    bag.maximum = maximum;
    if (isInt)
      bag.pattern = integer;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    if (isInt) {
      if (!Number.isInteger(input)) {
        payload.issues.push({
          expected: origin,
          format: def.format,
          code: "invalid_type",
          continue: false,
          input,
          inst
        });
        return;
      }
      if (!Number.isSafeInteger(input)) {
        if (input > 0) {
          payload.issues.push({
            input,
            code: "too_big",
            maximum: Number.MAX_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            inclusive: true,
            continue: !def.abort
          });
        } else {
          payload.issues.push({
            input,
            code: "too_small",
            minimum: Number.MIN_SAFE_INTEGER,
            note: "Integers must be within the safe integer range.",
            inst,
            origin,
            inclusive: true,
            continue: !def.abort
          });
        }
        return;
      }
    }
    if (input < minimum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_small",
        minimum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
    if (input > maximum) {
      payload.issues.push({
        origin: "number",
        input,
        code: "too_big",
        maximum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodCheckBigIntFormat = /* @__PURE__ */ $constructor("$ZodCheckBigIntFormat", (inst, def) => {
  $ZodCheck.init(inst, def);
  const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format];
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    bag.minimum = minimum;
    bag.maximum = maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    if (input < minimum) {
      payload.issues.push({
        origin: "bigint",
        input,
        code: "too_small",
        minimum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
    if (input > maximum) {
      payload.issues.push({
        origin: "bigint",
        input,
        code: "too_big",
        maximum,
        inclusive: true,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodCheckMaxSize = /* @__PURE__ */ $constructor("$ZodCheckMaxSize", (inst, def) => {
  var _a4;
  var _a3;
  $ZodCheck.init(inst, def);
  (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== void 0;
  };
  inst._zod.onattach.push((inst2) => {
    var _a5;
    const curr = (_a5 = inst2._zod.bag.maximum) != null ? _a5 : Number.POSITIVE_INFINITY;
    if (def.maximum < curr)
      inst2._zod.bag.maximum = def.maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size = input.size;
    if (size <= def.maximum)
      return;
    payload.issues.push({
      origin: getSizableOrigin(input),
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinSize = /* @__PURE__ */ $constructor("$ZodCheckMinSize", (inst, def) => {
  var _a4;
  var _a3;
  $ZodCheck.init(inst, def);
  (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== void 0;
  };
  inst._zod.onattach.push((inst2) => {
    var _a5;
    const curr = (_a5 = inst2._zod.bag.minimum) != null ? _a5 : Number.NEGATIVE_INFINITY;
    if (def.minimum > curr)
      inst2._zod.bag.minimum = def.minimum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size = input.size;
    if (size >= def.minimum)
      return;
    payload.issues.push({
      origin: getSizableOrigin(input),
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckSizeEquals = /* @__PURE__ */ $constructor("$ZodCheckSizeEquals", (inst, def) => {
  var _a4;
  var _a3;
  $ZodCheck.init(inst, def);
  (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.size !== void 0;
  };
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.minimum = def.size;
    bag.maximum = def.size;
    bag.size = def.size;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const size = input.size;
    if (size === def.size)
      return;
    const tooBig = size > def.size;
    payload.issues.push({
      origin: getSizableOrigin(input),
      ...tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size },
      inclusive: true,
      exact: true,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
  var _a4;
  var _a3;
  $ZodCheck.init(inst, def);
  (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  };
  inst._zod.onattach.push((inst2) => {
    var _a5;
    const curr = (_a5 = inst2._zod.bag.maximum) != null ? _a5 : Number.POSITIVE_INFINITY;
    if (def.maximum < curr)
      inst2._zod.bag.maximum = def.maximum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length <= def.maximum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_big",
      maximum: def.maximum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckMinLength = /* @__PURE__ */ $constructor("$ZodCheckMinLength", (inst, def) => {
  var _a4;
  var _a3;
  $ZodCheck.init(inst, def);
  (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  };
  inst._zod.onattach.push((inst2) => {
    var _a5;
    const curr = (_a5 = inst2._zod.bag.minimum) != null ? _a5 : Number.NEGATIVE_INFINITY;
    if (def.minimum > curr)
      inst2._zod.bag.minimum = def.minimum;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length >= def.minimum)
      return;
    const origin = getLengthableOrigin(input);
    payload.issues.push({
      origin,
      code: "too_small",
      minimum: def.minimum,
      inclusive: true,
      input,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckLengthEquals = /* @__PURE__ */ $constructor("$ZodCheckLengthEquals", (inst, def) => {
  var _a4;
  var _a3;
  $ZodCheck.init(inst, def);
  (_a4 = (_a3 = inst._zod.def).when) != null ? _a4 : _a3.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  };
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.minimum = def.length;
    bag.maximum = def.length;
    bag.length = def.length;
  });
  inst._zod.check = (payload) => {
    const input = payload.value;
    const length = input.length;
    if (length === def.length)
      return;
    const origin = getLengthableOrigin(input);
    const tooBig = length > def.length;
    payload.issues.push({
      origin,
      ...tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length },
      inclusive: true,
      exact: true,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckStringFormat = /* @__PURE__ */ $constructor("$ZodCheckStringFormat", (inst, def) => {
  var _a4, _b3;
  var _a3, _b2;
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    var _a5;
    const bag = inst2._zod.bag;
    bag.format = def.format;
    if (def.pattern) {
      (_a5 = bag.patterns) != null ? _a5 : bag.patterns = /* @__PURE__ */ new Set();
      bag.patterns.add(def.pattern);
    }
  });
  if (def.pattern)
    (_a4 = (_a3 = inst._zod).check) != null ? _a4 : _a3.check = (payload) => {
      def.pattern.lastIndex = 0;
      if (def.pattern.test(payload.value))
        return;
      payload.issues.push({
        origin: "string",
        code: "invalid_format",
        format: def.format,
        input: payload.value,
        ...def.pattern ? { pattern: def.pattern.toString() } : {},
        inst,
        continue: !def.abort
      });
    };
  else
    (_b3 = (_b2 = inst._zod).check) != null ? _b3 : _b2.check = () => {
    };
});
var $ZodCheckRegex = /* @__PURE__ */ $constructor("$ZodCheckRegex", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    def.pattern.lastIndex = 0;
    if (def.pattern.test(payload.value))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "regex",
      input: payload.value,
      pattern: def.pattern.toString(),
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckLowerCase = /* @__PURE__ */ $constructor("$ZodCheckLowerCase", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = lowercase;
  $ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = uppercase;
  $ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckIncludes = /* @__PURE__ */ $constructor("$ZodCheckIncludes", (inst, def) => {
  $ZodCheck.init(inst, def);
  const escapedRegex = escapeRegex(def.includes);
  const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex);
  def.pattern = pattern;
  inst._zod.onattach.push((inst2) => {
    var _a3;
    const bag = inst2._zod.bag;
    (_a3 = bag.patterns) != null ? _a3 : bag.patterns = /* @__PURE__ */ new Set();
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.includes(def.includes, def.position))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "includes",
      includes: def.includes,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckStartsWith = /* @__PURE__ */ $constructor("$ZodCheckStartsWith", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
  (_a3 = def.pattern) != null ? _a3 : def.pattern = pattern;
  inst._zod.onattach.push((inst2) => {
    var _a4;
    const bag = inst2._zod.bag;
    (_a4 = bag.patterns) != null ? _a4 : bag.patterns = /* @__PURE__ */ new Set();
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.startsWith(def.prefix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "starts_with",
      prefix: def.prefix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckEndsWith = /* @__PURE__ */ $constructor("$ZodCheckEndsWith", (inst, def) => {
  var _a3;
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
  (_a3 = def.pattern) != null ? _a3 : def.pattern = pattern;
  inst._zod.onattach.push((inst2) => {
    var _a4;
    const bag = inst2._zod.bag;
    (_a4 = bag.patterns) != null ? _a4 : bag.patterns = /* @__PURE__ */ new Set();
    bag.patterns.add(pattern);
  });
  inst._zod.check = (payload) => {
    if (payload.value.endsWith(def.suffix))
      return;
    payload.issues.push({
      origin: "string",
      code: "invalid_format",
      format: "ends_with",
      suffix: def.suffix,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function handleCheckPropertyResult(result, payload, property) {
  if (result.issues.length) {
    payload.issues.push(...prefixIssues(property, result.issues));
  }
}
var $ZodCheckProperty = /* @__PURE__ */ $constructor("$ZodCheckProperty", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    const result = def.schema._zod.run({
      value: payload.value[def.property],
      issues: []
    }, {});
    if (result instanceof Promise) {
      return result.then((result2) => handleCheckPropertyResult(result2, payload, def.property));
    }
    handleCheckPropertyResult(result, payload, def.property);
    return;
  };
});
var $ZodCheckMimeType = /* @__PURE__ */ $constructor("$ZodCheckMimeType", (inst, def) => {
  $ZodCheck.init(inst, def);
  const mimeSet = new Set(def.mime);
  inst._zod.onattach.push((inst2) => {
    inst2._zod.bag.mime = def.mime;
  });
  inst._zod.check = (payload) => {
    if (mimeSet.has(payload.value.type))
      return;
    payload.issues.push({
      code: "invalid_value",
      values: def.mime,
      input: payload.value.type,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    payload.value = def.tx(payload.value);
  };
});

// node_modules/zod/v4/core/doc.js
var Doc = class {
  constructor(args = []) {
    this.content = [];
    this.indent = 0;
    if (this)
      this.args = args;
  }
  indented(fn) {
    this.indent += 1;
    fn(this);
    this.indent -= 1;
  }
  write(arg) {
    if (typeof arg === "function") {
      arg(this, { execution: "sync" });
      arg(this, { execution: "async" });
      return;
    }
    const content = arg;
    const lines = content.split("\n").filter((x) => x);
    const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length));
    const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x);
    for (const line of dedented) {
      this.content.push(line);
    }
  }
  compile() {
    var _a3;
    const F5 = Function;
    const args = this == null ? void 0 : this.args;
    const content = (_a3 = this == null ? void 0 : this.content) != null ? _a3 : [``];
    const lines = [...content.map((x) => `  ${x}`)];
    return new F5(...args, lines.join("\n"));
  }
};

// node_modules/zod/v4/core/versions.js
var version = {
  major: 4,
  minor: 3,
  patch: 6
};

// node_modules/zod/v4/core/schemas.js
var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
  var _a4, _b2, _c;
  var _a3;
  inst != null ? inst : inst = {};
  inst._zod.def = def;
  inst._zod.bag = inst._zod.bag || {};
  inst._zod.version = version;
  const checks = [...(_a4 = inst._zod.def.checks) != null ? _a4 : []];
  if (inst._zod.traits.has("$ZodCheck")) {
    checks.unshift(inst);
  }
  for (const ch of checks) {
    for (const fn of ch._zod.onattach) {
      fn(inst);
    }
  }
  if (checks.length === 0) {
    (_b2 = (_a3 = inst._zod).deferred) != null ? _b2 : _a3.deferred = [];
    (_c = inst._zod.deferred) == null ? void 0 : _c.push(() => {
      inst._zod.run = inst._zod.parse;
    });
  } else {
    const runChecks = (payload, checks2, ctx) => {
      let isAborted2 = aborted(payload);
      let asyncResult;
      for (const ch of checks2) {
        if (ch._zod.def.when) {
          const shouldRun = ch._zod.def.when(payload);
          if (!shouldRun)
            continue;
        } else if (isAborted2) {
          continue;
        }
        const currLen = payload.issues.length;
        const _10 = ch._zod.check(payload);
        if (_10 instanceof Promise && (ctx == null ? void 0 : ctx.async) === false) {
          throw new $ZodAsyncError();
        }
        if (asyncResult || _10 instanceof Promise) {
          asyncResult = (asyncResult != null ? asyncResult : Promise.resolve()).then(async () => {
            await _10;
            const nextLen = payload.issues.length;
            if (nextLen === currLen)
              return;
            if (!isAborted2)
              isAborted2 = aborted(payload, currLen);
          });
        } else {
          const nextLen = payload.issues.length;
          if (nextLen === currLen)
            continue;
          if (!isAborted2)
            isAborted2 = aborted(payload, currLen);
        }
      }
      if (asyncResult) {
        return asyncResult.then(() => {
          return payload;
        });
      }
      return payload;
    };
    const handleCanaryResult = (canary, payload, ctx) => {
      if (aborted(canary)) {
        canary.aborted = true;
        return canary;
      }
      const checkResult = runChecks(payload, checks, ctx);
      if (checkResult instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError();
        return checkResult.then((checkResult2) => inst._zod.parse(checkResult2, ctx));
      }
      return inst._zod.parse(checkResult, ctx);
    };
    inst._zod.run = (payload, ctx) => {
      if (ctx.skipChecks) {
        return inst._zod.parse(payload, ctx);
      }
      if (ctx.direction === "backward") {
        const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true });
        if (canary instanceof Promise) {
          return canary.then((canary2) => {
            return handleCanaryResult(canary2, payload, ctx);
          });
        }
        return handleCanaryResult(canary, payload, ctx);
      }
      const result = inst._zod.parse(payload, ctx);
      if (result instanceof Promise) {
        if (ctx.async === false)
          throw new $ZodAsyncError();
        return result.then((result2) => runChecks(result2, checks, ctx));
      }
      return runChecks(result, checks, ctx);
    };
  }
  defineLazy(inst, "~standard", () => ({
    validate: (value) => {
      var _a5;
      try {
        const r2 = safeParse(inst, value);
        return r2.success ? { value: r2.data } : { issues: (_a5 = r2.error) == null ? void 0 : _a5.issues };
      } catch (_10) {
        return safeParseAsync(inst, value).then((r2) => {
          var _a6;
          return r2.success ? { value: r2.data } : { issues: (_a6 = r2.error) == null ? void 0 : _a6.issues };
        });
      }
    },
    vendor: "zod",
    version: 1
  }));
});
var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
  var _a3, _b2, _c;
  $ZodType.init(inst, def);
  inst._zod.pattern = (_c = [...(_b2 = (_a3 = inst == null ? void 0 : inst._zod.bag) == null ? void 0 : _a3.patterns) != null ? _b2 : []].pop()) != null ? _c : string(inst._zod.bag);
  inst._zod.parse = (payload, _10) => {
    if (def.coerce)
      try {
        payload.value = String(payload.value);
      } catch (_11) {
      }
    if (typeof payload.value === "string")
      return payload;
    payload.issues.push({
      expected: "string",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodStringFormat = /* @__PURE__ */ $constructor("$ZodStringFormat", (inst, def) => {
  $ZodCheckStringFormat.init(inst, def);
  $ZodString.init(inst, def);
});
var $ZodGUID = /* @__PURE__ */ $constructor("$ZodGUID", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = guid;
  $ZodStringFormat.init(inst, def);
});
var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
  var _a3, _b2;
  if (def.version) {
    const versionMap = {
      v1: 1,
      v2: 2,
      v3: 3,
      v4: 4,
      v5: 5,
      v6: 6,
      v7: 7,
      v8: 8
    };
    const v2 = versionMap[def.version];
    if (v2 === void 0)
      throw new Error(`Invalid UUID version: "${def.version}"`);
    (_a3 = def.pattern) != null ? _a3 : def.pattern = uuid(v2);
  } else
    (_b2 = def.pattern) != null ? _b2 : def.pattern = uuid();
  $ZodStringFormat.init(inst, def);
});
var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = email;
  $ZodStringFormat.init(inst, def);
});
var $ZodURL = /* @__PURE__ */ $constructor("$ZodURL", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    try {
      const trimmed = payload.value.trim();
      const url2 = new URL(trimmed);
      if (def.hostname) {
        def.hostname.lastIndex = 0;
        if (!def.hostname.test(url2.hostname)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid hostname",
            pattern: def.hostname.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (def.protocol) {
        def.protocol.lastIndex = 0;
        if (!def.protocol.test(url2.protocol.endsWith(":") ? url2.protocol.slice(0, -1) : url2.protocol)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid protocol",
            pattern: def.protocol.source,
            input: payload.value,
            inst,
            continue: !def.abort
          });
        }
      }
      if (def.normalize) {
        payload.value = url2.href;
      } else {
        payload.value = trimmed;
      }
      return;
    } catch (_10) {
      payload.issues.push({
        code: "invalid_format",
        format: "url",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = emoji();
  $ZodStringFormat.init(inst, def);
});
var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = nanoid;
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = cuid;
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = cuid2;
  $ZodStringFormat.init(inst, def);
});
var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = ulid;
  $ZodStringFormat.init(inst, def);
});
var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = xid;
  $ZodStringFormat.init(inst, def);
});
var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = ksuid;
  $ZodStringFormat.init(inst, def);
});
var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = datetime(def);
  $ZodStringFormat.init(inst, def);
});
var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = date;
  $ZodStringFormat.init(inst, def);
});
var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = time(def);
  $ZodStringFormat.init(inst, def);
});
var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = duration;
  $ZodStringFormat.init(inst, def);
});
var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = ipv4;
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv4`;
});
var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = ipv6;
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv6`;
  inst._zod.check = (payload) => {
    try {
      new URL(`http://[${payload.value}]`);
    } catch (e2) {
      payload.issues.push({
        code: "invalid_format",
        format: "ipv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodMAC = /* @__PURE__ */ $constructor("$ZodMAC", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = mac(def.delimiter);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `mac`;
});
var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = cidrv4;
  $ZodStringFormat.init(inst, def);
});
var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = cidrv6;
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    const parts = payload.value.split("/");
    try {
      if (parts.length !== 2)
        throw new Error();
      const [address, prefix] = parts;
      if (!prefix)
        throw new Error();
      const prefixNum = Number(prefix);
      if (`${prefixNum}` !== prefix)
        throw new Error();
      if (prefixNum < 0 || prefixNum > 128)
        throw new Error();
      new URL(`http://[${address}]`);
    } catch (e2) {
      payload.issues.push({
        code: "invalid_format",
        format: "cidrv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
function isValidBase64(data) {
  if (data === "")
    return true;
  if (data.length % 4 !== 0)
    return false;
  try {
    atob(data);
    return true;
  } catch (e2) {
    return false;
  }
}
var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = base64;
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.contentEncoding = "base64";
  inst._zod.check = (payload) => {
    if (isValidBase64(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
function isValidBase64URL(data) {
  if (!base64url.test(data))
    return false;
  const base643 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
  const padded = base643.padEnd(Math.ceil(base643.length / 4) * 4, "=");
  return isValidBase64(padded);
}
var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = base64url;
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.contentEncoding = "base64url";
  inst._zod.check = (payload) => {
    if (isValidBase64URL(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "base64url",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodE164 = /* @__PURE__ */ $constructor("$ZodE164", (inst, def) => {
  var _a3;
  (_a3 = def.pattern) != null ? _a3 : def.pattern = e164;
  $ZodStringFormat.init(inst, def);
});
function isValidJWT2(token, algorithm = null) {
  try {
    const tokensParts = token.split(".");
    if (tokensParts.length !== 3)
      return false;
    const [header] = tokensParts;
    if (!header)
      return false;
    const parsedHeader = JSON.parse(atob(header));
    if ("typ" in parsedHeader && (parsedHeader == null ? void 0 : parsedHeader.typ) !== "JWT")
      return false;
    if (!parsedHeader.alg)
      return false;
    if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
      return false;
    return true;
  } catch (e2) {
    return false;
  }
}
var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (isValidJWT2(payload.value, def.alg))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "jwt",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodCustomStringFormat = /* @__PURE__ */ $constructor("$ZodCustomStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (def.fn(payload.value))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: def.format,
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
  var _a3;
  $ZodType.init(inst, def);
  inst._zod.pattern = (_a3 = inst._zod.bag.pattern) != null ? _a3 : number;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Number(payload.value);
      } catch (_10) {
      }
    const input = payload.value;
    if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) {
      return payload;
    }
    const received = typeof input === "number" ? Number.isNaN(input) ? "NaN" : !Number.isFinite(input) ? "Infinity" : void 0 : void 0;
    payload.issues.push({
      expected: "number",
      code: "invalid_type",
      input,
      inst,
      ...received ? { received } : {}
    });
    return payload;
  };
});
var $ZodNumberFormat = /* @__PURE__ */ $constructor("$ZodNumberFormat", (inst, def) => {
  $ZodCheckNumberFormat.init(inst, def);
  $ZodNumber.init(inst, def);
});
var $ZodBoolean = /* @__PURE__ */ $constructor("$ZodBoolean", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = boolean;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Boolean(payload.value);
      } catch (_10) {
      }
    const input = payload.value;
    if (typeof input === "boolean")
      return payload;
    payload.issues.push({
      expected: "boolean",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodBigInt = /* @__PURE__ */ $constructor("$ZodBigInt", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = bigint;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = BigInt(payload.value);
      } catch (_10) {
      }
    if (typeof payload.value === "bigint")
      return payload;
    payload.issues.push({
      expected: "bigint",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodBigIntFormat = /* @__PURE__ */ $constructor("$ZodBigIntFormat", (inst, def) => {
  $ZodCheckBigIntFormat.init(inst, def);
  $ZodBigInt.init(inst, def);
});
var $ZodSymbol = /* @__PURE__ */ $constructor("$ZodSymbol", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "symbol")
      return payload;
    payload.issues.push({
      expected: "symbol",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodUndefined = /* @__PURE__ */ $constructor("$ZodUndefined", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _undefined;
  inst._zod.values = /* @__PURE__ */ new Set([void 0]);
  inst._zod.optin = "optional";
  inst._zod.optout = "optional";
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined")
      return payload;
    payload.issues.push({
      expected: "undefined",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodNull = /* @__PURE__ */ $constructor("$ZodNull", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = _null;
  inst._zod.values = /* @__PURE__ */ new Set([null]);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input === null)
      return payload;
    payload.issues.push({
      expected: "null",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodAny = /* @__PURE__ */ $constructor("$ZodAny", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodUnknown = /* @__PURE__ */ $constructor("$ZodUnknown", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload) => payload;
});
var $ZodNever = /* @__PURE__ */ $constructor("$ZodNever", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    payload.issues.push({
      expected: "never",
      code: "invalid_type",
      input: payload.value,
      inst
    });
    return payload;
  };
});
var $ZodVoid = /* @__PURE__ */ $constructor("$ZodVoid", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (typeof input === "undefined")
      return payload;
    payload.issues.push({
      expected: "void",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodDate = /* @__PURE__ */ $constructor("$ZodDate", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce) {
      try {
        payload.value = new Date(payload.value);
      } catch (_err) {
      }
    }
    const input = payload.value;
    const isDate = input instanceof Date;
    const isValidDate = isDate && !Number.isNaN(input.getTime());
    if (isValidDate)
      return payload;
    payload.issues.push({
      expected: "date",
      code: "invalid_type",
      input,
      ...isDate ? { received: "Invalid Date" } : {},
      inst
    });
    return payload;
  };
});
function handleArrayResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
var $ZodArray = /* @__PURE__ */ $constructor("$ZodArray", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        expected: "array",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    payload.value = Array(input.length);
    const proms = [];
    for (let i2 = 0; i2 < input.length; i2++) {
      const item = input[i2];
      const result = def.element._zod.run({
        value: item,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleArrayResult(result2, payload, i2)));
      } else {
        handleArrayResult(result, payload, i2);
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
function handlePropertyResult(result, final, key, input, isOptionalOut) {
  if (result.issues.length) {
    if (isOptionalOut && !(key in input)) {
      return;
    }
    final.issues.push(...prefixIssues(key, result.issues));
  }
  if (result.value === void 0) {
    if (key in input) {
      final.value[key] = void 0;
    }
  } else {
    final.value[key] = result.value;
  }
}
function normalizeDef(def) {
  var _a3, _b2, _c, _d2;
  const keys = Object.keys(def.shape);
  for (const k10 of keys) {
    if (!((_d2 = (_c = (_b2 = (_a3 = def.shape) == null ? void 0 : _a3[k10]) == null ? void 0 : _b2._zod) == null ? void 0 : _c.traits) == null ? void 0 : _d2.has("$ZodType"))) {
      throw new Error(`Invalid element at key "${k10}": expected a Zod schema`);
    }
  }
  const okeys = optionalKeys(def.shape);
  return {
    ...def,
    keys,
    keySet: new Set(keys),
    numKeys: keys.length,
    optionalKeys: new Set(okeys)
  };
}
function handleCatchall(proms, input, payload, ctx, def, inst) {
  const unrecognized = [];
  const keySet = def.keySet;
  const _catchall = def.catchall._zod;
  const t2 = _catchall.def.type;
  const isOptionalOut = _catchall.optout === "optional";
  for (const key in input) {
    if (keySet.has(key))
      continue;
    if (t2 === "never") {
      unrecognized.push(key);
      continue;
    }
    const r2 = _catchall.run({ value: input[key], issues: [] }, ctx);
    if (r2 instanceof Promise) {
      proms.push(r2.then((r4) => handlePropertyResult(r4, payload, key, input, isOptionalOut)));
    } else {
      handlePropertyResult(r2, payload, key, input, isOptionalOut);
    }
  }
  if (unrecognized.length) {
    payload.issues.push({
      code: "unrecognized_keys",
      keys: unrecognized,
      input,
      inst
    });
  }
  if (!proms.length)
    return payload;
  return Promise.all(proms).then(() => {
    return payload;
  });
}
var $ZodObject = /* @__PURE__ */ $constructor("$ZodObject", (inst, def) => {
  $ZodType.init(inst, def);
  const desc = Object.getOwnPropertyDescriptor(def, "shape");
  if (!(desc == null ? void 0 : desc.get)) {
    const sh = def.shape;
    Object.defineProperty(def, "shape", {
      get: () => {
        const newSh = { ...sh };
        Object.defineProperty(def, "shape", {
          value: newSh
        });
        return newSh;
      }
    });
  }
  const _normalized = cached(() => normalizeDef(def));
  defineLazy(inst._zod, "propValues", () => {
    var _a3;
    const shape = def.shape;
    const propValues = {};
    for (const key in shape) {
      const field = shape[key]._zod;
      if (field.values) {
        (_a3 = propValues[key]) != null ? _a3 : propValues[key] = /* @__PURE__ */ new Set();
        for (const v2 of field.values)
          propValues[key].add(v2);
      }
    }
    return propValues;
  });
  const isObject2 = isObject;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value != null ? value : value = _normalized.value;
    const input = payload.value;
    if (!isObject2(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    payload.value = {};
    const proms = [];
    const shape = value.shape;
    for (const key of value.keys) {
      const el = shape[key];
      const isOptionalOut = el._zod.optout === "optional";
      const r2 = el._zod.run({ value: input[key], issues: [] }, ctx);
      if (r2 instanceof Promise) {
        proms.push(r2.then((r4) => handlePropertyResult(r4, payload, key, input, isOptionalOut)));
      } else {
        handlePropertyResult(r2, payload, key, input, isOptionalOut);
      }
    }
    if (!catchall) {
      return proms.length ? Promise.all(proms).then(() => payload) : payload;
    }
    return handleCatchall(proms, input, payload, ctx, _normalized.value, inst);
  };
});
var $ZodObjectJIT = /* @__PURE__ */ $constructor("$ZodObjectJIT", (inst, def) => {
  $ZodObject.init(inst, def);
  const superParse = inst._zod.parse;
  const _normalized = cached(() => normalizeDef(def));
  const generateFastpass = (shape) => {
    var _a3;
    const doc = new Doc(["shape", "payload", "ctx"]);
    const normalized = _normalized.value;
    const parseStr = (key) => {
      const k10 = esc(key);
      return `shape[${k10}]._zod.run({ value: input[${k10}], issues: [] }, ctx)`;
    };
    doc.write(`const input = payload.value;`);
    const ids = /* @__PURE__ */ Object.create(null);
    let counter = 0;
    for (const key of normalized.keys) {
      ids[key] = `key_${counter++}`;
    }
    doc.write(`const newResult = {};`);
    for (const key of normalized.keys) {
      const id = ids[key];
      const k10 = esc(key);
      const schema = shape[key];
      const isOptionalOut = ((_a3 = schema == null ? void 0 : schema._zod) == null ? void 0 : _a3.optout) === "optional";
      doc.write(`const ${id} = ${parseStr(key)};`);
      if (isOptionalOut) {
        doc.write(`
        if (${id}.issues.length) {
          if (${k10} in input) {
            payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
              ...iss,
              path: iss.path ? [${k10}, ...iss.path] : [${k10}]
            })));
          }
        }
        
        if (${id}.value === undefined) {
          if (${k10} in input) {
            newResult[${k10}] = undefined;
          }
        } else {
          newResult[${k10}] = ${id}.value;
        }
        
      `);
      } else {
        doc.write(`
        if (${id}.issues.length) {
          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${k10}, ...iss.path] : [${k10}]
          })));
        }
        
        if (${id}.value === undefined) {
          if (${k10} in input) {
            newResult[${k10}] = undefined;
          }
        } else {
          newResult[${k10}] = ${id}.value;
        }
        
      `);
      }
    }
    doc.write(`payload.value = newResult;`);
    doc.write(`return payload;`);
    const fn = doc.compile();
    return (payload, ctx) => fn(shape, payload, ctx);
  };
  let fastpass;
  const isObject2 = isObject;
  const jit = !globalConfig.jitless;
  const allowsEval2 = allowsEval;
  const fastEnabled = jit && allowsEval2.value;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    value != null ? value : value = _normalized.value;
    const input = payload.value;
    if (!isObject2(input)) {
      payload.issues.push({
        expected: "object",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    if (jit && fastEnabled && (ctx == null ? void 0 : ctx.async) === false && ctx.jitless !== true) {
      if (!fastpass)
        fastpass = generateFastpass(def.shape);
      payload = fastpass(payload, ctx);
      if (!catchall)
        return payload;
      return handleCatchall([], input, payload, ctx, value, inst);
    }
    return superParse(payload, ctx);
  };
});
function handleUnionResults(results, final, inst, ctx) {
  for (const result of results) {
    if (result.issues.length === 0) {
      final.value = result.value;
      return final;
    }
  }
  const nonaborted = results.filter((r2) => !aborted(r2));
  if (nonaborted.length === 1) {
    final.value = nonaborted[0].value;
    return nonaborted[0];
  }
  final.issues.push({
    code: "invalid_union",
    input: final.value,
    inst,
    errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
  });
  return final;
}
var $ZodUnion = /* @__PURE__ */ $constructor("$ZodUnion", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.options.some((o2) => o2._zod.optin === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "optout", () => def.options.some((o2) => o2._zod.optout === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "values", () => {
    if (def.options.every((o2) => o2._zod.values)) {
      return new Set(def.options.flatMap((option) => Array.from(option._zod.values)));
    }
    return void 0;
  });
  defineLazy(inst._zod, "pattern", () => {
    if (def.options.every((o2) => o2._zod.pattern)) {
      const patterns = def.options.map((o2) => o2._zod.pattern);
      return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
    }
    return void 0;
  });
  const single = def.options.length === 1;
  const first = def.options[0]._zod.run;
  inst._zod.parse = (payload, ctx) => {
    if (single) {
      return first(payload, ctx);
    }
    let async = false;
    const results = [];
    for (const option of def.options) {
      const result = option._zod.run({
        value: payload.value,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        if (result.issues.length === 0)
          return result;
        results.push(result);
      }
    }
    if (!async)
      return handleUnionResults(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleUnionResults(results2, payload, inst, ctx);
    });
  };
});
function handleExclusiveUnionResults(results, final, inst, ctx) {
  const successes = results.filter((r2) => r2.issues.length === 0);
  if (successes.length === 1) {
    final.value = successes[0].value;
    return final;
  }
  if (successes.length === 0) {
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config())))
    });
  } else {
    final.issues.push({
      code: "invalid_union",
      input: final.value,
      inst,
      errors: [],
      inclusive: false
    });
  }
  return final;
}
var $ZodXor = /* @__PURE__ */ $constructor("$ZodXor", (inst, def) => {
  $ZodUnion.init(inst, def);
  def.inclusive = false;
  const single = def.options.length === 1;
  const first = def.options[0]._zod.run;
  inst._zod.parse = (payload, ctx) => {
    if (single) {
      return first(payload, ctx);
    }
    let async = false;
    const results = [];
    for (const option of def.options) {
      const result = option._zod.run({
        value: payload.value,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        results.push(result);
        async = true;
      } else {
        results.push(result);
      }
    }
    if (!async)
      return handleExclusiveUnionResults(results, payload, inst, ctx);
    return Promise.all(results).then((results2) => {
      return handleExclusiveUnionResults(results2, payload, inst, ctx);
    });
  };
});
var $ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
  def.inclusive = false;
  $ZodUnion.init(inst, def);
  const _super = inst._zod.parse;
  defineLazy(inst._zod, "propValues", () => {
    const propValues = {};
    for (const option of def.options) {
      const pv = option._zod.propValues;
      if (!pv || Object.keys(pv).length === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`);
      for (const [k10, v2] of Object.entries(pv)) {
        if (!propValues[k10])
          propValues[k10] = /* @__PURE__ */ new Set();
        for (const val of v2) {
          propValues[k10].add(val);
        }
      }
    }
    return propValues;
  });
  const disc = cached(() => {
    var _a3;
    const opts = def.options;
    const map2 = /* @__PURE__ */ new Map();
    for (const o2 of opts) {
      const values = (_a3 = o2._zod.propValues) == null ? void 0 : _a3[def.discriminator];
      if (!values || values.size === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o2)}"`);
      for (const v2 of values) {
        if (map2.has(v2)) {
          throw new Error(`Duplicate discriminator value "${String(v2)}"`);
        }
        map2.set(v2, o2);
      }
    }
    return map2;
  });
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isObject(input)) {
      payload.issues.push({
        code: "invalid_type",
        expected: "object",
        input,
        inst
      });
      return payload;
    }
    const opt = disc.value.get(input == null ? void 0 : input[def.discriminator]);
    if (opt) {
      return opt._zod.run(payload, ctx);
    }
    if (def.unionFallback) {
      return _super(payload, ctx);
    }
    payload.issues.push({
      code: "invalid_union",
      errors: [],
      note: "No matching discriminator",
      discriminator: def.discriminator,
      input,
      path: [def.discriminator],
      inst
    });
    return payload;
  };
});
var $ZodIntersection = /* @__PURE__ */ $constructor("$ZodIntersection", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    const left = def.left._zod.run({ value: input, issues: [] }, ctx);
    const right = def.right._zod.run({ value: input, issues: [] }, ctx);
    const async = left instanceof Promise || right instanceof Promise;
    if (async) {
      return Promise.all([left, right]).then(([left2, right2]) => {
        return handleIntersectionResults(payload, left2, right2);
      });
    }
    return handleIntersectionResults(payload, left, right);
  };
});
function mergeValues2(a2, b10) {
  if (a2 === b10) {
    return { valid: true, data: a2 };
  }
  if (a2 instanceof Date && b10 instanceof Date && +a2 === +b10) {
    return { valid: true, data: a2 };
  }
  if (isPlainObject(a2) && isPlainObject(b10)) {
    const bKeys = Object.keys(b10);
    const sharedKeys = Object.keys(a2).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a2, ...b10 };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues2(a2[key], b10[key]);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
        };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  }
  if (Array.isArray(a2) && Array.isArray(b10)) {
    if (a2.length !== b10.length) {
      return { valid: false, mergeErrorPath: [] };
    }
    const newArray = [];
    for (let index = 0; index < a2.length; index++) {
      const itemA = a2[index];
      const itemB = b10[index];
      const sharedValue = mergeValues2(itemA, itemB);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [index, ...sharedValue.mergeErrorPath]
        };
      }
      newArray.push(sharedValue.data);
    }
    return { valid: true, data: newArray };
  }
  return { valid: false, mergeErrorPath: [] };
}
function handleIntersectionResults(result, left, right) {
  const unrecKeys = /* @__PURE__ */ new Map();
  let unrecIssue;
  for (const iss of left.issues) {
    if (iss.code === "unrecognized_keys") {
      unrecIssue != null ? unrecIssue : unrecIssue = iss;
      for (const k10 of iss.keys) {
        if (!unrecKeys.has(k10))
          unrecKeys.set(k10, {});
        unrecKeys.get(k10).l = true;
      }
    } else {
      result.issues.push(iss);
    }
  }
  for (const iss of right.issues) {
    if (iss.code === "unrecognized_keys") {
      for (const k10 of iss.keys) {
        if (!unrecKeys.has(k10))
          unrecKeys.set(k10, {});
        unrecKeys.get(k10).r = true;
      }
    } else {
      result.issues.push(iss);
    }
  }
  const bothKeys = [...unrecKeys].filter(([, f2]) => f2.l && f2.r).map(([k10]) => k10);
  if (bothKeys.length && unrecIssue) {
    result.issues.push({ ...unrecIssue, keys: bothKeys });
  }
  if (aborted(result))
    return result;
  const merged = mergeValues2(left.value, right.value);
  if (!merged.valid) {
    throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
  }
  result.value = merged.data;
  return result;
}
var $ZodTuple = /* @__PURE__ */ $constructor("$ZodTuple", (inst, def) => {
  $ZodType.init(inst, def);
  const items = def.items;
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!Array.isArray(input)) {
      payload.issues.push({
        input,
        inst,
        expected: "tuple",
        code: "invalid_type"
      });
      return payload;
    }
    payload.value = [];
    const proms = [];
    const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional");
    const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex;
    if (!def.rest) {
      const tooBig = input.length > items.length;
      const tooSmall = input.length < optStart - 1;
      if (tooBig || tooSmall) {
        payload.issues.push({
          ...tooBig ? { code: "too_big", maximum: items.length, inclusive: true } : { code: "too_small", minimum: items.length },
          input,
          inst,
          origin: "array"
        });
        return payload;
      }
    }
    let i2 = -1;
    for (const item of items) {
      i2++;
      if (i2 >= input.length) {
        if (i2 >= optStart)
          continue;
      }
      const result = item._zod.run({
        value: input[i2],
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleTupleResult(result2, payload, i2)));
      } else {
        handleTupleResult(result, payload, i2);
      }
    }
    if (def.rest) {
      const rest = input.slice(items.length);
      for (const el of rest) {
        i2++;
        const result = def.rest._zod.run({
          value: el,
          issues: []
        }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((result2) => handleTupleResult(result2, payload, i2)));
        } else {
          handleTupleResult(result, payload, i2);
        }
      }
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleTupleResult(result, final, index) {
  if (result.issues.length) {
    final.issues.push(...prefixIssues(index, result.issues));
  }
  final.value[index] = result.value;
}
var $ZodRecord = /* @__PURE__ */ $constructor("$ZodRecord", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!isPlainObject(input)) {
      payload.issues.push({
        expected: "record",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    const values = def.keyType._zod.values;
    if (values) {
      payload.value = {};
      const recordKeys = /* @__PURE__ */ new Set();
      for (const key of values) {
        if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") {
          recordKeys.add(typeof key === "number" ? key.toString() : key);
          const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
          if (result instanceof Promise) {
            proms.push(result.then((result2) => {
              if (result2.issues.length) {
                payload.issues.push(...prefixIssues(key, result2.issues));
              }
              payload.value[key] = result2.value;
            }));
          } else {
            if (result.issues.length) {
              payload.issues.push(...prefixIssues(key, result.issues));
            }
            payload.value[key] = result.value;
          }
        }
      }
      let unrecognized;
      for (const key in input) {
        if (!recordKeys.has(key)) {
          unrecognized = unrecognized != null ? unrecognized : [];
          unrecognized.push(key);
        }
      }
      if (unrecognized && unrecognized.length > 0) {
        payload.issues.push({
          code: "unrecognized_keys",
          input,
          inst,
          keys: unrecognized
        });
      }
    } else {
      payload.value = {};
      for (const key of Reflect.ownKeys(input)) {
        if (key === "__proto__")
          continue;
        let keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
        if (keyResult instanceof Promise) {
          throw new Error("Async schemas not supported in object keys currently");
        }
        const checkNumericKey = typeof key === "string" && number.test(key) && keyResult.issues.length;
        if (checkNumericKey) {
          const retryResult = def.keyType._zod.run({ value: Number(key), issues: [] }, ctx);
          if (retryResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (retryResult.issues.length === 0) {
            keyResult = retryResult;
          }
        }
        if (keyResult.issues.length) {
          if (def.mode === "loose") {
            payload.value[key] = input[key];
          } else {
            payload.issues.push({
              code: "invalid_key",
              origin: "record",
              issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
              input: key,
              path: [key],
              inst
            });
          }
          continue;
        }
        const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx);
        if (result instanceof Promise) {
          proms.push(result.then((result2) => {
            if (result2.issues.length) {
              payload.issues.push(...prefixIssues(key, result2.issues));
            }
            payload.value[keyResult.value] = result2.value;
          }));
        } else {
          if (result.issues.length) {
            payload.issues.push(...prefixIssues(key, result.issues));
          }
          payload.value[keyResult.value] = result.value;
        }
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
var $ZodMap = /* @__PURE__ */ $constructor("$ZodMap", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Map)) {
      payload.issues.push({
        expected: "map",
        code: "invalid_type",
        input,
        inst
      });
      return payload;
    }
    const proms = [];
    payload.value = /* @__PURE__ */ new Map();
    for (const [key, value] of input) {
      const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
      const valueResult = def.valueType._zod.run({ value, issues: [] }, ctx);
      if (keyResult instanceof Promise || valueResult instanceof Promise) {
        proms.push(Promise.all([keyResult, valueResult]).then(([keyResult2, valueResult2]) => {
          handleMapResult(keyResult2, valueResult2, payload, key, input, inst, ctx);
        }));
      } else {
        handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx);
      }
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) {
  if (keyResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, keyResult.issues));
    } else {
      final.issues.push({
        code: "invalid_key",
        origin: "map",
        input,
        inst,
        issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  if (valueResult.issues.length) {
    if (propertyKeyTypes.has(typeof key)) {
      final.issues.push(...prefixIssues(key, valueResult.issues));
    } else {
      final.issues.push({
        origin: "map",
        code: "invalid_element",
        input,
        inst,
        key,
        issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config()))
      });
    }
  }
  final.value.set(keyResult.value, valueResult.value);
}
var $ZodSet = /* @__PURE__ */ $constructor("$ZodSet", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    const input = payload.value;
    if (!(input instanceof Set)) {
      payload.issues.push({
        input,
        inst,
        expected: "set",
        code: "invalid_type"
      });
      return payload;
    }
    const proms = [];
    payload.value = /* @__PURE__ */ new Set();
    for (const item of input) {
      const result = def.valueType._zod.run({ value: item, issues: [] }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleSetResult(result2, payload)));
      } else
        handleSetResult(result, payload);
    }
    if (proms.length)
      return Promise.all(proms).then(() => payload);
    return payload;
  };
});
function handleSetResult(result, final) {
  if (result.issues.length) {
    final.issues.push(...result.issues);
  }
  final.value.add(result.value);
}
var $ZodEnum = /* @__PURE__ */ $constructor("$ZodEnum", (inst, def) => {
  $ZodType.init(inst, def);
  const values = getEnumValues(def.entries);
  const valuesSet = new Set(values);
  inst._zod.values = valuesSet;
  inst._zod.pattern = new RegExp(`^(${values.filter((k10) => propertyKeyTypes.has(typeof k10)).map((o2) => typeof o2 === "string" ? escapeRegex(o2) : o2.toString()).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (valuesSet.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values,
      input,
      inst
    });
    return payload;
  };
});
var $ZodLiteral = /* @__PURE__ */ $constructor("$ZodLiteral", (inst, def) => {
  $ZodType.init(inst, def);
  if (def.values.length === 0) {
    throw new Error("Cannot create literal schema with no valid values");
  }
  const values = new Set(def.values);
  inst._zod.values = values;
  inst._zod.pattern = new RegExp(`^(${def.values.map((o2) => typeof o2 === "string" ? escapeRegex(o2) : o2 ? escapeRegex(o2.toString()) : String(o2)).join("|")})$`);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (values.has(input)) {
      return payload;
    }
    payload.issues.push({
      code: "invalid_value",
      values: def.values,
      input,
      inst
    });
    return payload;
  };
});
var $ZodFile = /* @__PURE__ */ $constructor("$ZodFile", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    const input = payload.value;
    if (input instanceof File)
      return payload;
    payload.issues.push({
      expected: "file",
      code: "invalid_type",
      input,
      inst
    });
    return payload;
  };
});
var $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    const _out = def.transform(payload.value, payload);
    if (ctx.async) {
      const output = _out instanceof Promise ? _out : Promise.resolve(_out);
      return output.then((output2) => {
        payload.value = output2;
        return payload;
      });
    }
    if (_out instanceof Promise) {
      throw new $ZodAsyncError();
    }
    payload.value = _out;
    return payload;
  };
});
function handleOptionalResult(result, input) {
  if (result.issues.length && input === void 0) {
    return { issues: [], value: void 0 };
  }
  return result;
}
var $ZodOptional = /* @__PURE__ */ $constructor("$ZodOptional", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  inst._zod.optout = "optional";
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, void 0]) : void 0;
  });
  defineLazy(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    if (def.innerType._zod.optin === "optional") {
      const result = def.innerType._zod.run(payload, ctx);
      if (result instanceof Promise)
        return result.then((r2) => handleOptionalResult(r2, payload.value));
      return handleOptionalResult(result, payload.value);
    }
    if (payload.value === void 0) {
      return payload;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodExactOptional = /* @__PURE__ */ $constructor("$ZodExactOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy(inst._zod, "pattern", () => def.innerType._zod.pattern);
  inst._zod.parse = (payload, ctx) => {
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodNullable = /* @__PURE__ */ $constructor("$ZodNullable", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "pattern", () => {
    const pattern = def.innerType._zod.pattern;
    return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : void 0;
  });
  defineLazy(inst._zod, "values", () => {
    return def.innerType._zod.values ? /* @__PURE__ */ new Set([...def.innerType._zod.values, null]) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    if (payload.value === null)
      return payload;
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodDefault = /* @__PURE__ */ $constructor("$ZodDefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    if (payload.value === void 0) {
      payload.value = def.defaultValue;
      return payload;
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleDefaultResult(result2, def));
    }
    return handleDefaultResult(result, def);
  };
});
function handleDefaultResult(payload, def) {
  if (payload.value === void 0) {
    payload.value = def.defaultValue;
  }
  return payload;
}
var $ZodPrefault = /* @__PURE__ */ $constructor("$ZodPrefault", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    if (payload.value === void 0) {
      payload.value = def.defaultValue;
    }
    return def.innerType._zod.run(payload, ctx);
  };
});
var $ZodNonOptional = /* @__PURE__ */ $constructor("$ZodNonOptional", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => {
    const v2 = def.innerType._zod.values;
    return v2 ? new Set([...v2].filter((x) => x !== void 0)) : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => handleNonOptionalResult(result2, inst));
    }
    return handleNonOptionalResult(result, inst);
  };
});
function handleNonOptionalResult(payload, inst) {
  if (!payload.issues.length && payload.value === void 0) {
    payload.issues.push({
      code: "invalid_type",
      expected: "nonoptional",
      input: payload.value,
      inst
    });
  }
  return payload;
}
var $ZodSuccess = /* @__PURE__ */ $constructor("$ZodSuccess", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      throw new $ZodEncodeError("ZodSuccess");
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => {
        payload.value = result2.issues.length === 0;
        return payload;
      });
    }
    payload.value = result.issues.length === 0;
    return payload;
  };
});
var $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "optin", () => def.innerType._zod.optin);
  defineLazy(inst._zod, "optout", () => def.innerType._zod.optout);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then((result2) => {
        payload.value = result2.value;
        if (result2.issues.length) {
          payload.value = def.catchValue({
            ...payload,
            error: {
              issues: result2.issues.map((iss) => finalizeIssue(iss, ctx, config()))
            },
            input: payload.value
          });
          payload.issues = [];
        }
        return payload;
      });
    }
    payload.value = result.value;
    if (result.issues.length) {
      payload.value = def.catchValue({
        ...payload,
        error: {
          issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config()))
        },
        input: payload.value
      });
      payload.issues = [];
    }
    return payload;
  };
});
var $ZodNaN = /* @__PURE__ */ $constructor("$ZodNaN", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) {
      payload.issues.push({
        input: payload.value,
        inst,
        expected: "nan",
        code: "invalid_type"
      });
      return payload;
    }
    return payload;
  };
});
var $ZodPipe = /* @__PURE__ */ $constructor("$ZodPipe", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => def.in._zod.values);
  defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handlePipeResult(right2, def.in, ctx));
      }
      return handlePipeResult(right, def.in, ctx);
    }
    const left = def.in._zod.run(payload, ctx);
    if (left instanceof Promise) {
      return left.then((left2) => handlePipeResult(left2, def.out, ctx));
    }
    return handlePipeResult(left, def.out, ctx);
  };
});
function handlePipeResult(left, next, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return next._zod.run({ value: left.value, issues: left.issues }, ctx);
}
var $ZodCodec = /* @__PURE__ */ $constructor("$ZodCodec", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "values", () => def.in._zod.values);
  defineLazy(inst._zod, "optin", () => def.in._zod.optin);
  defineLazy(inst._zod, "optout", () => def.out._zod.optout);
  defineLazy(inst._zod, "propValues", () => def.in._zod.propValues);
  inst._zod.parse = (payload, ctx) => {
    const direction = ctx.direction || "forward";
    if (direction === "forward") {
      const left = def.in._zod.run(payload, ctx);
      if (left instanceof Promise) {
        return left.then((left2) => handleCodecAResult(left2, def, ctx));
      }
      return handleCodecAResult(left, def, ctx);
    } else {
      const right = def.out._zod.run(payload, ctx);
      if (right instanceof Promise) {
        return right.then((right2) => handleCodecAResult(right2, def, ctx));
      }
      return handleCodecAResult(right, def, ctx);
    }
  };
});
function handleCodecAResult(result, def, ctx) {
  if (result.issues.length) {
    result.aborted = true;
    return result;
  }
  const direction = ctx.direction || "forward";
  if (direction === "forward") {
    const transformed = def.transform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx));
    }
    return handleCodecTxResult(result, transformed, def.out, ctx);
  } else {
    const transformed = def.reverseTransform(result.value, result);
    if (transformed instanceof Promise) {
      return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx));
    }
    return handleCodecTxResult(result, transformed, def.in, ctx);
  }
}
function handleCodecTxResult(left, value, nextSchema, ctx) {
  if (left.issues.length) {
    left.aborted = true;
    return left;
  }
  return nextSchema._zod.run({ value, issues: left.issues }, ctx);
}
var $ZodReadonly = /* @__PURE__ */ $constructor("$ZodReadonly", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues);
  defineLazy(inst._zod, "values", () => def.innerType._zod.values);
  defineLazy(inst._zod, "optin", () => {
    var _a3, _b2;
    return (_b2 = (_a3 = def.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.optin;
  });
  defineLazy(inst._zod, "optout", () => {
    var _a3, _b2;
    return (_b2 = (_a3 = def.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.optout;
  });
  inst._zod.parse = (payload, ctx) => {
    if (ctx.direction === "backward") {
      return def.innerType._zod.run(payload, ctx);
    }
    const result = def.innerType._zod.run(payload, ctx);
    if (result instanceof Promise) {
      return result.then(handleReadonlyResult);
    }
    return handleReadonlyResult(result);
  };
});
function handleReadonlyResult(payload) {
  payload.value = Object.freeze(payload.value);
  return payload;
}
var $ZodTemplateLiteral = /* @__PURE__ */ $constructor("$ZodTemplateLiteral", (inst, def) => {
  $ZodType.init(inst, def);
  const regexParts = [];
  for (const part of def.parts) {
    if (typeof part === "object" && part !== null) {
      if (!part._zod.pattern) {
        throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`);
      }
      const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern;
      if (!source)
        throw new Error(`Invalid template literal part: ${part._zod.traits}`);
      const start = source.startsWith("^") ? 1 : 0;
      const end = source.endsWith("$") ? source.length - 1 : source.length;
      regexParts.push(source.slice(start, end));
    } else if (part === null || primitiveTypes.has(typeof part)) {
      regexParts.push(escapeRegex(`${part}`));
    } else {
      throw new Error(`Invalid template literal part: ${part}`);
    }
  }
  inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`);
  inst._zod.parse = (payload, _ctx) => {
    var _a3;
    if (typeof payload.value !== "string") {
      payload.issues.push({
        input: payload.value,
        inst,
        expected: "string",
        code: "invalid_type"
      });
      return payload;
    }
    inst._zod.pattern.lastIndex = 0;
    if (!inst._zod.pattern.test(payload.value)) {
      payload.issues.push({
        input: payload.value,
        inst,
        code: "invalid_format",
        format: (_a3 = def.format) != null ? _a3 : "template_literal",
        pattern: inst._zod.pattern.source
      });
      return payload;
    }
    return payload;
  };
});
var $ZodFunction = /* @__PURE__ */ $constructor("$ZodFunction", (inst, def) => {
  $ZodType.init(inst, def);
  inst._def = def;
  inst._zod.def = def;
  inst.implement = (func) => {
    if (typeof func !== "function") {
      throw new Error("implement() must be called with a function");
    }
    return function(...args) {
      const parsedArgs = inst._def.input ? parse(inst._def.input, args) : args;
      const result = Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return parse(inst._def.output, result);
      }
      return result;
    };
  };
  inst.implementAsync = (func) => {
    if (typeof func !== "function") {
      throw new Error("implementAsync() must be called with a function");
    }
    return async function(...args) {
      const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args;
      const result = await Reflect.apply(func, this, parsedArgs);
      if (inst._def.output) {
        return await parseAsync(inst._def.output, result);
      }
      return result;
    };
  };
  inst._zod.parse = (payload, _ctx) => {
    if (typeof payload.value !== "function") {
      payload.issues.push({
        code: "invalid_type",
        expected: "function",
        input: payload.value,
        inst
      });
      return payload;
    }
    const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise";
    if (hasPromiseOutput) {
      payload.value = inst.implementAsync(payload.value);
    } else {
      payload.value = inst.implement(payload.value);
    }
    return payload;
  };
  inst.input = (...args) => {
    const F5 = inst.constructor;
    if (Array.isArray(args[0])) {
      return new F5({
        type: "function",
        input: new $ZodTuple({
          type: "tuple",
          items: args[0],
          rest: args[1]
        }),
        output: inst._def.output
      });
    }
    return new F5({
      type: "function",
      input: args[0],
      output: inst._def.output
    });
  };
  inst.output = (output) => {
    const F5 = inst.constructor;
    return new F5({
      type: "function",
      input: inst._def.input,
      output
    });
  };
  return inst;
});
var $ZodPromise = /* @__PURE__ */ $constructor("$ZodPromise", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, ctx) => {
    return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx));
  };
});
var $ZodLazy = /* @__PURE__ */ $constructor("$ZodLazy", (inst, def) => {
  $ZodType.init(inst, def);
  defineLazy(inst._zod, "innerType", () => def.getter());
  defineLazy(inst._zod, "pattern", () => {
    var _a3, _b2;
    return (_b2 = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.pattern;
  });
  defineLazy(inst._zod, "propValues", () => {
    var _a3, _b2;
    return (_b2 = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.propValues;
  });
  defineLazy(inst._zod, "optin", () => {
    var _a3, _b2, _c;
    return (_c = (_b2 = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.optin) != null ? _c : void 0;
  });
  defineLazy(inst._zod, "optout", () => {
    var _a3, _b2, _c;
    return (_c = (_b2 = (_a3 = inst._zod.innerType) == null ? void 0 : _a3._zod) == null ? void 0 : _b2.optout) != null ? _c : void 0;
  });
  inst._zod.parse = (payload, ctx) => {
    const inner = inst._zod.innerType;
    return inner._zod.run(payload, ctx);
  };
});
var $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
  $ZodCheck.init(inst, def);
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _10) => {
    return payload;
  };
  inst._zod.check = (payload) => {
    const input = payload.value;
    const r2 = def.fn(input);
    if (r2 instanceof Promise) {
      return r2.then((r4) => handleRefineResult(r4, payload, input, inst));
    }
    handleRefineResult(r2, payload, input, inst);
    return;
  };
});
function handleRefineResult(result, payload, input, inst) {
  var _a3;
  if (!result) {
    const _iss = {
      code: "custom",
      input,
      inst,
      // incorporates params.error into issue reporting
      path: [...(_a3 = inst._zod.def.path) != null ? _a3 : []],
      // incorporates params.error into issue reporting
      continue: !inst._zod.def.abort
      // params: inst._zod.def.params,
    };
    if (inst._zod.def.params)
      _iss.params = inst._zod.def.params;
    payload.issues.push(issue(_iss));
  }
}

// node_modules/zod/v4/locales/index.js
var locales_exports = {};
__export(locales_exports, {
  ar: () => ar_default,
  az: () => az_default,
  be: () => be_default,
  bg: () => bg_default,
  ca: () => ca_default,
  cs: () => cs_default,
  da: () => da_default,
  de: () => de_default2,
  en: () => en_default3,
  eo: () => eo_default,
  es: () => es_default2,
  fa: () => fa_default,
  fi: () => fi_default,
  fr: () => fr_default2,
  frCA: () => fr_CA_default,
  he: () => he_default,
  hu: () => hu_default,
  hy: () => hy_default,
  id: () => id_default,
  is: () => is_default,
  it: () => it_default,
  ja: () => ja_default2,
  ka: () => ka_default,
  kh: () => kh_default,
  km: () => km_default,
  ko: () => ko_default2,
  lt: () => lt_default,
  mk: () => mk_default,
  ms: () => ms_default,
  nl: () => nl_default,
  no: () => no_default,
  ota: () => ota_default,
  pl: () => pl_default,
  ps: () => ps_default,
  pt: () => pt_default2,
  ru: () => ru_default2,
  sl: () => sl_default,
  sv: () => sv_default,
  ta: () => ta_default,
  th: () => th_default,
  tr: () => tr_default,
  ua: () => ua_default,
  uk: () => uk_default,
  ur: () => ur_default,
  uz: () => uz_default,
  vi: () => vi_default,
  yo: () => yo_default,
  zhCN: () => zh_CN_default2,
  zhTW: () => zh_TW_default2
});

// node_modules/zod/v4/locales/ar.js
var error = () => {
  const Sizable = {
    string: { unit: "\u062D\u0631\u0641", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
    file: { unit: "\u0628\u0627\u064A\u062A", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
    array: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" },
    set: { unit: "\u0639\u0646\u0635\u0631", verb: "\u0623\u0646 \u064A\u062D\u0648\u064A" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0645\u062F\u062E\u0644",
    email: "\u0628\u0631\u064A\u062F \u0625\u0644\u0643\u062A\u0631\u0648\u0646\u064A",
    url: "\u0631\u0627\u0628\u0637",
    emoji: "\u0625\u064A\u0645\u0648\u062C\u064A",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u062A\u0627\u0631\u064A\u062E \u0648\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    date: "\u062A\u0627\u0631\u064A\u062E \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    time: "\u0648\u0642\u062A \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    duration: "\u0645\u062F\u0629 \u0628\u0645\u0639\u064A\u0627\u0631 ISO",
    ipv4: "\u0639\u0646\u0648\u0627\u0646 IPv4",
    ipv6: "\u0639\u0646\u0648\u0627\u0646 IPv6",
    cidrv4: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv4",
    cidrv6: "\u0645\u062F\u0649 \u0639\u0646\u0627\u0648\u064A\u0646 \u0628\u0635\u064A\u063A\u0629 IPv6",
    base64: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64-encoded",
    base64url: "\u0646\u064E\u0635 \u0628\u062A\u0631\u0645\u064A\u0632 base64url-encoded",
    json_string: "\u0646\u064E\u0635 \u0639\u0644\u0649 \u0647\u064A\u0626\u0629 JSON",
    e164: "\u0631\u0642\u0645 \u0647\u0627\u062A\u0641 \u0628\u0645\u0639\u064A\u0627\u0631 E.164",
    jwt: "JWT",
    template_literal: "\u0645\u062F\u062E\u0644"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 instanceof ${issue2.expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;
        }
        return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${expected}\u060C \u0648\u0644\u0643\u0646 \u062A\u0645 \u0625\u062F\u062E\u0627\u0644 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0645\u062F\u062E\u0644\u0627\u062A \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644\u0629: \u064A\u0641\u062A\u0631\u0636 \u0625\u062F\u062E\u0627\u0644 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0627\u062E\u062A\u064A\u0627\u0631 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062A\u0648\u0642\u0639 \u0627\u0646\u062A\u0642\u0627\u0621 \u0623\u062D\u062F \u0647\u0630\u0647 \u0627\u0644\u062E\u064A\u0627\u0631\u0627\u062A: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return ` \u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${(_c = issue2.origin) != null ? _c : "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u0639\u0646\u0635\u0631"}`;
        return `\u0623\u0643\u0628\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0623\u0646 \u062A\u0643\u0648\u0646 ${(_e = issue2.origin) != null ? _e : "\u0627\u0644\u0642\u064A\u0645\u0629"} ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0623\u0635\u063A\u0631 \u0645\u0646 \u0627\u0644\u0644\u0627\u0632\u0645: \u064A\u0641\u062A\u0631\u0636 \u0644\u0640 ${issue2.origin} \u0623\u0646 \u064A\u0643\u0648\u0646 ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0628\u062F\u0623 \u0628\u0640 "${issue2.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0646\u062A\u0647\u064A \u0628\u0640 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u062A\u0636\u0645\u0651\u064E\u0646 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u0646\u064E\u0635 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0637\u0627\u0628\u0642 \u0627\u0644\u0646\u0645\u0637 ${_issue.pattern}`;
        return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644`;
      }
      case "not_multiple_of":
        return `\u0631\u0642\u0645 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644: \u064A\u062C\u0628 \u0623\u0646 \u064A\u0643\u0648\u0646 \u0645\u0646 \u0645\u0636\u0627\u0639\u0641\u0627\u062A ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u0645\u0639\u0631\u0641${issue2.keys.length > 1 ? "\u0627\u062A" : ""} \u063A\u0631\u064A\u0628${issue2.keys.length > 1 ? "\u0629" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
      case "invalid_key":
        return `\u0645\u0639\u0631\u0641 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
      case "invalid_union":
        return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
      case "invalid_element":
        return `\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644 \u0641\u064A ${issue2.origin}`;
      default:
        return "\u0645\u062F\u062E\u0644 \u063A\u064A\u0631 \u0645\u0642\u0628\u0648\u0644";
    }
  };
};
function ar_default() {
  return {
    localeError: error()
  };
}

// node_modules/zod/v4/locales/az.js
var error2 = () => {
  const Sizable = {
    string: { unit: "simvol", verb: "olmal\u0131d\u0131r" },
    file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
    array: { unit: "element", verb: "olmal\u0131d\u0131r" },
    set: { unit: "element", verb: "olmal\u0131d\u0131r" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    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"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n instanceof ${issue2.expected}, daxil olan ${received}`;
        }
        return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${expected}, daxil olan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Yanl\u0131\u015F d\u0259y\u0259r: g\xF6zl\u0259nil\u0259n ${stringifyPrimitive(issue2.values[0])}`;
        return `Yanl\u0131\u015F se\xE7im: a\u015Fa\u011F\u0131dak\u0131lardan biri olmal\u0131d\u0131r: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${(_c = issue2.origin) != null ? _c : "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "element"}`;
        return `\xC7ox b\xF6y\xFCk: g\xF6zl\u0259nil\u0259n ${(_e = issue2.origin) != null ? _e : "d\u0259y\u0259r"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        return `\xC7ox ki\xE7ik: g\xF6zl\u0259nil\u0259n ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Yanl\u0131\u015F m\u0259tn: "${_issue.prefix}" il\u0259 ba\u015Flamal\u0131d\u0131r`;
        if (_issue.format === "ends_with")
          return `Yanl\u0131\u015F m\u0259tn: "${_issue.suffix}" il\u0259 bitm\u0259lidir`;
        if (_issue.format === "includes")
          return `Yanl\u0131\u015F m\u0259tn: "${_issue.includes}" daxil olmal\u0131d\u0131r`;
        if (_issue.format === "regex")
          return `Yanl\u0131\u015F m\u0259tn: ${_issue.pattern} \u015Fablonuna uy\u011Fun olmal\u0131d\u0131r`;
        return `Yanl\u0131\u015F ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Yanl\u0131\u015F \u0259d\u0259d: ${issue2.divisor} il\u0259 b\xF6l\xFCn\u0259 bil\u0259n olmal\u0131d\u0131r`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan a\xE7ar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F a\xE7ar`;
      case "invalid_union":
        return "Yanl\u0131\u015F d\u0259y\u0259r";
      case "invalid_element":
        return `${issue2.origin} daxilind\u0259 yanl\u0131\u015F d\u0259y\u0259r`;
      default:
        return `Yanl\u0131\u015F d\u0259y\u0259r`;
    }
  };
};
function az_default() {
  return {
    localeError: error2()
  };
}

// node_modules/zod/v4/locales/be.js
function getBelarusianPlural(count, one, few, many) {
  const absCount = Math.abs(count);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many;
  }
  if (lastDigit === 1) {
    return one;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many;
}
var error3 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "\u0441\u0456\u043C\u0432\u0430\u043B",
        few: "\u0441\u0456\u043C\u0432\u0430\u043B\u044B",
        many: "\u0441\u0456\u043C\u0432\u0430\u043B\u0430\u045E"
      },
      verb: "\u043C\u0435\u0446\u044C"
    },
    array: {
      unit: {
        one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
        few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
        many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
      },
      verb: "\u043C\u0435\u0446\u044C"
    },
    set: {
      unit: {
        one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
        few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u044B",
        many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\u045E"
      },
      verb: "\u043C\u0435\u0446\u044C"
    },
    file: {
      unit: {
        one: "\u0431\u0430\u0439\u0442",
        few: "\u0431\u0430\u0439\u0442\u044B",
        many: "\u0431\u0430\u0439\u0442\u0430\u045E"
      },
      verb: "\u043C\u0435\u0446\u044C"
    }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0443\u0432\u043E\u0434",
    email: "email \u0430\u0434\u0440\u0430\u0441",
    url: "URL",
    emoji: "\u044D\u043C\u043E\u0434\u0437\u0456",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0434\u0430\u0442\u0430 \u0456 \u0447\u0430\u0441",
    date: "ISO \u0434\u0430\u0442\u0430",
    time: "ISO \u0447\u0430\u0441",
    duration: "ISO \u043F\u0440\u0430\u0446\u044F\u0433\u043B\u0430\u0441\u0446\u044C",
    ipv4: "IPv4 \u0430\u0434\u0440\u0430\u0441",
    ipv6: "IPv6 \u0430\u0434\u0440\u0430\u0441",
    cidrv4: "IPv4 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
    cidrv6: "IPv6 \u0434\u044B\u044F\u043F\u0430\u0437\u043E\u043D",
    base64: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64",
    base64url: "\u0440\u0430\u0434\u043E\u043A \u0443 \u0444\u0430\u0440\u043C\u0430\u0446\u0435 base64url",
    json_string: "JSON \u0440\u0430\u0434\u043E\u043A",
    e164: "\u043D\u0443\u043C\u0430\u0440 E.164",
    jwt: "JWT",
    template_literal: "\u0443\u0432\u043E\u0434"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u043B\u0456\u043A",
    array: "\u043C\u0430\u0441\u0456\u045E"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F instanceof ${issue2.expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;
        }
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u045E\u0441\u044F ${expected}, \u0430\u0442\u0440\u044B\u043C\u0430\u043D\u0430 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0432\u0430\u0440\u044B\u044F\u043D\u0442: \u0447\u0430\u043A\u0430\u045E\u0441\u044F \u0430\u0434\u0437\u0456\u043D \u0437 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${(_c = issue2.origin) != null ? _c : "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.maximum.toString()} ${unit}`;
        }
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u0432\u044F\u043B\u0456\u043A\u0456: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${(_d2 = issue2.origin) != null ? _d2 : "\u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435"} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 ${sizing.verb} ${adj}${issue2.minimum.toString()} ${unit}`;
        }
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u0430 \u043C\u0430\u043B\u044B: \u0447\u0430\u043A\u0430\u043B\u0430\u0441\u044F, \u0448\u0442\u043E ${issue2.origin} \u043F\u0430\u0432\u0456\u043D\u043D\u0430 \u0431\u044B\u0446\u044C ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u043F\u0430\u0447\u044B\u043D\u0430\u0446\u0446\u0430 \u0437 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u0430\u043A\u0430\u043D\u0447\u0432\u0430\u0446\u0446\u0430 \u043D\u0430 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0437\u043C\u044F\u0448\u0447\u0430\u0446\u044C "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u0440\u0430\u0434\u043E\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0430\u0434\u043F\u0430\u0432\u044F\u0434\u0430\u0446\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043B\u0456\u043A: \u043F\u0430\u0432\u0456\u043D\u0435\u043D \u0431\u044B\u0446\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u0430\u0437\u043D\u0430\u043D\u044B ${issue2.keys.length > 1 ? "\u043A\u043B\u044E\u0447\u044B" : "\u043A\u043B\u044E\u0447"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434";
      case "invalid_element":
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u0430\u0435 \u0437\u043D\u0430\u0447\u044D\u043D\u043D\u0435 \u045E ${issue2.origin}`;
      default:
        return `\u041D\u044F\u043F\u0440\u0430\u0432\u0456\u043B\u044C\u043D\u044B \u045E\u0432\u043E\u0434`;
    }
  };
};
function be_default() {
  return {
    localeError: error3()
  };
}

// node_modules/zod/v4/locales/bg.js
var error4 = () => {
  const Sizable = {
    string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
    file: { unit: "\u0431\u0430\u0439\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
    array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" },
    set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430", verb: "\u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0432\u0445\u043E\u0434",
    email: "\u0438\u043C\u0435\u0439\u043B \u0430\u0434\u0440\u0435\u0441",
    url: "URL",
    emoji: "\u0435\u043C\u043E\u0434\u0436\u0438",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0432\u0440\u0435\u043C\u0435",
    date: "ISO \u0434\u0430\u0442\u0430",
    time: "ISO \u0432\u0440\u0435\u043C\u0435",
    duration: "ISO \u043F\u0440\u043E\u0434\u044A\u043B\u0436\u0438\u0442\u0435\u043B\u043D\u043E\u0441\u0442",
    ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
    ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
    cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    base64: "base64-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",
    base64url: "base64url-\u043A\u043E\u0434\u0438\u0440\u0430\u043D \u043D\u0438\u0437",
    json_string: "JSON \u043D\u0438\u0437",
    e164: "E.164 \u043D\u043E\u043C\u0435\u0440",
    jwt: "JWT",
    template_literal: "\u0432\u0445\u043E\u0434"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0447\u0438\u0441\u043B\u043E",
    array: "\u043C\u0430\u0441\u0438\u0432"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;
        }
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434: \u043E\u0447\u0430\u043A\u0432\u0430\u043D ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u043E\u043F\u0446\u0438\u044F: \u043E\u0447\u0430\u043A\u0432\u0430\u043D\u043E \u0435\u0434\u043D\u043E \u043E\u0442 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${(_c = issue2.origin) != null ? _c : "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0430"}`;
        return `\u0422\u0432\u044A\u0440\u0434\u0435 \u0433\u043E\u043B\u044F\u043C\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${(_e = issue2.origin) != null ? _e : "\u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442"} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0441\u044A\u0434\u044A\u0440\u0436\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0422\u0432\u044A\u0440\u0434\u0435 \u043C\u0430\u043B\u043A\u043E: \u043E\u0447\u0430\u043A\u0432\u0430 \u0441\u0435 ${issue2.origin} \u0434\u0430 \u0431\u044A\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u0432\u0430 \u0441 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0437\u0430\u0432\u044A\u0440\u0448\u0432\u0430 \u0441 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0432\u043A\u043B\u044E\u0447\u0432\u0430 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043D\u0438\u0437: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0441\u044A\u0432\u043F\u0430\u0434\u0430 \u0441 ${_issue.pattern}`;
        let invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D";
        if (_issue.format === "emoji")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
        if (_issue.format === "datetime")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
        if (_issue.format === "date")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";
        if (_issue.format === "time")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E";
        if (_issue.format === "duration")
          invalid_adj = "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430";
        return `${invalid_adj} ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u043E \u0447\u0438\u0441\u043B\u043E: \u0442\u0440\u044F\u0431\u0432\u0430 \u0434\u0430 \u0431\u044A\u0434\u0435 \u043A\u0440\u0430\u0442\u043D\u043E \u043D\u0430 ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0437\u043F\u043E\u0437\u043D\u0430\u0442${issue2.keys.length > 1 ? "\u0438" : ""} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u043E\u0432\u0435" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434";
      case "invalid_element":
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u043D\u0430 \u0441\u0442\u043E\u0439\u043D\u043E\u0441\u0442 \u0432 ${issue2.origin}`;
      default:
        return `\u041D\u0435\u0432\u0430\u043B\u0438\u0434\u0435\u043D \u0432\u0445\u043E\u0434`;
    }
  };
};
function bg_default() {
  return {
    localeError: error4()
  };
}

// node_modules/zod/v4/locales/ca.js
var error5 = () => {
  const Sizable = {
    string: { unit: "car\xE0cters", verb: "contenir" },
    file: { unit: "bytes", verb: "contenir" },
    array: { unit: "elements", verb: "contenir" },
    set: { unit: "elements", verb: "contenir" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "entrada",
    email: "adre\xE7a electr\xF2nica",
    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: "data i hora ISO",
    date: "data ISO",
    time: "hora ISO",
    duration: "durada ISO",
    ipv4: "adre\xE7a IPv4",
    ipv6: "adre\xE7a IPv6",
    cidrv4: "rang IPv4",
    cidrv6: "rang IPv6",
    base64: "cadena codificada en base64",
    base64url: "cadena codificada en base64url",
    json_string: "cadena JSON",
    e164: "n\xFAmero E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Tipus inv\xE0lid: s'esperava instanceof ${issue2.expected}, s'ha rebut ${received}`;
        }
        return `Tipus inv\xE0lid: s'esperava ${expected}, s'ha rebut ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Valor inv\xE0lid: s'esperava ${stringifyPrimitive(issue2.values[0])}`;
        return `Opci\xF3 inv\xE0lida: s'esperava una de ${joinValues(issue2.values, " o ")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "com a m\xE0xim" : "menys de";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Massa gran: s'esperava que ${(_c = issue2.origin) != null ? _c : "el valor"} contingu\xE9s ${adj} ${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elements"}`;
        return `Massa gran: s'esperava que ${(_e = issue2.origin) != null ? _e : "el valor"} fos ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "com a m\xEDnim" : "m\xE9s de";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Massa petit: s'esperava que ${issue2.origin} contingu\xE9s ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Massa petit: s'esperava que ${issue2.origin} fos ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Format inv\xE0lid: ha de comen\xE7ar amb "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Format inv\xE0lid: ha d'acabar amb "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Format inv\xE0lid: ha d'incloure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Format inv\xE0lid: ha de coincidir amb el patr\xF3 ${_issue.pattern}`;
        return `Format inv\xE0lid per a ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE0lid: ha de ser m\xFAltiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Clau${issue2.keys.length > 1 ? "s" : ""} no reconeguda${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Clau inv\xE0lida a ${issue2.origin}`;
      case "invalid_union":
        return "Entrada inv\xE0lida";
      // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general
      case "invalid_element":
        return `Element inv\xE0lid a ${issue2.origin}`;
      default:
        return `Entrada inv\xE0lida`;
    }
  };
};
function ca_default() {
  return {
    localeError: error5()
  };
}

// node_modules/zod/v4/locales/cs.js
var error6 = () => {
  const Sizable = {
    string: { unit: "znak\u016F", verb: "m\xEDt" },
    file: { unit: "bajt\u016F", verb: "m\xEDt" },
    array: { unit: "prvk\u016F", verb: "m\xEDt" },
    set: { unit: "prvk\u016F", verb: "m\xEDt" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "regul\xE1rn\xED v\xFDraz",
    email: "e-mailov\xE1 adresa",
    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: "datum a \u010Das ve form\xE1tu ISO",
    date: "datum ve form\xE1tu ISO",
    time: "\u010Das ve form\xE1tu ISO",
    duration: "doba trv\xE1n\xED ISO",
    ipv4: "IPv4 adresa",
    ipv6: "IPv6 adresa",
    cidrv4: "rozsah IPv4",
    cidrv6: "rozsah IPv6",
    base64: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64",
    base64url: "\u0159et\u011Bzec zak\xF3dovan\xFD ve form\xE1tu base64url",
    json_string: "\u0159et\u011Bzec ve form\xE1tu JSON",
    e164: "\u010D\xEDslo E.164",
    jwt: "JWT",
    template_literal: "vstup"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u010D\xEDslo",
    string: "\u0159et\u011Bzec",
    function: "funkce",
    array: "pole"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no instanceof ${issue2.expected}, obdr\u017Eeno ${received}`;
        }
        return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${expected}, obdr\u017Eeno ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Neplatn\xFD vstup: o\u010Dek\xE1v\xE1no ${stringifyPrimitive(issue2.values[0])}`;
        return `Neplatn\xE1 mo\u017Enost: o\u010Dek\xE1v\xE1na jedna z hodnot ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${(_c = issue2.origin) != null ? _c : "hodnota"} mus\xED m\xEDt ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "prvk\u016F"}`;
        }
        return `Hodnota je p\u0159\xEDli\u0161 velk\xE1: ${(_e = issue2.origin) != null ? _e : "hodnota"} mus\xED b\xFDt ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${(_f = issue2.origin) != null ? _f : "hodnota"} mus\xED m\xEDt ${adj}${issue2.minimum.toString()} ${(_g = sizing.unit) != null ? _g : "prvk\u016F"}`;
        }
        return `Hodnota je p\u0159\xEDli\u0161 mal\xE1: ${(_h = issue2.origin) != null ? _h : "hodnota"} mus\xED b\xFDt ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Neplatn\xFD \u0159et\u011Bzec: mus\xED za\u010D\xEDnat na "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Neplatn\xFD \u0159et\u011Bzec: mus\xED kon\u010Dit na "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Neplatn\xFD \u0159et\u011Bzec: mus\xED obsahovat "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Neplatn\xFD \u0159et\u011Bzec: mus\xED odpov\xEDdat vzoru ${_issue.pattern}`;
        return `Neplatn\xFD form\xE1t ${(_i = FormatDictionary[_issue.format]) != null ? _i : issue2.format}`;
      }
      case "not_multiple_of":
        return `Neplatn\xE9 \u010D\xEDslo: mus\xED b\xFDt n\xE1sobkem ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Nezn\xE1m\xE9 kl\xED\u010De: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Neplatn\xFD kl\xED\u010D v ${issue2.origin}`;
      case "invalid_union":
        return "Neplatn\xFD vstup";
      case "invalid_element":
        return `Neplatn\xE1 hodnota v ${issue2.origin}`;
      default:
        return `Neplatn\xFD vstup`;
    }
  };
};
function cs_default() {
  return {
    localeError: error6()
  };
}

// node_modules/zod/v4/locales/da.js
var error7 = () => {
  const Sizable = {
    string: { unit: "tegn", verb: "havde" },
    file: { unit: "bytes", verb: "havde" },
    array: { unit: "elementer", verb: "indeholdt" },
    set: { unit: "elementer", verb: "indeholdt" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "e-mailadresse",
    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 dato- og klokkesl\xE6t",
    date: "ISO-dato",
    time: "ISO-klokkesl\xE6t",
    duration: "ISO-varighed",
    ipv4: "IPv4-omr\xE5de",
    ipv6: "IPv6-omr\xE5de",
    cidrv4: "IPv4-spektrum",
    cidrv6: "IPv6-spektrum",
    base64: "base64-kodet streng",
    base64url: "base64url-kodet streng",
    json_string: "JSON-streng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "streng",
    number: "tal",
    boolean: "boolean",
    array: "liste",
    object: "objekt",
    set: "s\xE6t",
    file: "fil"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ugyldigt input: forventede instanceof ${issue2.expected}, fik ${received}`;
        }
        return `Ugyldigt input: forventede ${expected}, fik ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ugyldig v\xE6rdi: forventede ${stringifyPrimitive(issue2.values[0])}`;
        return `Ugyldigt valg: forventede en af f\xF8lgende ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = (_c = TypeDictionary[issue2.origin]) != null ? _c : issue2.origin;
        if (sizing)
          return `For stor: forventede ${origin != null ? origin : "value"} ${sizing.verb} ${adj} ${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elementer"}`;
        return `For stor: forventede ${origin != null ? origin : "value"} havde ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = (_e = TypeDictionary[issue2.origin]) != null ? _e : issue2.origin;
        if (sizing) {
          return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `For lille: forventede ${origin} havde ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ugyldig streng: skal starte med "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Ugyldig streng: skal ende med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ugyldig streng: skal indeholde "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ugyldig streng: skal matche m\xF8nsteret ${_issue.pattern}`;
        return `Ugyldig ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Ugyldigt tal: skal v\xE6re deleligt med ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Ukendte n\xF8gler" : "Ukendt n\xF8gle"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8gle i ${issue2.origin}`;
      case "invalid_union":
        return "Ugyldigt input: matcher ingen af de tilladte typer";
      case "invalid_element":
        return `Ugyldig v\xE6rdi i ${issue2.origin}`;
      default:
        return `Ugyldigt input`;
    }
  };
};
function da_default() {
  return {
    localeError: error7()
  };
}

// node_modules/zod/v4/locales/de.js
var error8 = () => {
  const Sizable = {
    string: { unit: "Zeichen", verb: "zu haben" },
    file: { unit: "Bytes", verb: "zu haben" },
    array: { unit: "Elemente", verb: "zu haben" },
    set: { unit: "Elemente", verb: "zu haben" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "Eingabe",
    email: "E-Mail-Adresse",
    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-Datum und -Uhrzeit",
    date: "ISO-Datum",
    time: "ISO-Uhrzeit",
    duration: "ISO-Dauer",
    ipv4: "IPv4-Adresse",
    ipv6: "IPv6-Adresse",
    cidrv4: "IPv4-Bereich",
    cidrv6: "IPv6-Bereich",
    base64: "Base64-codierter String",
    base64url: "Base64-URL-codierter String",
    json_string: "JSON-String",
    e164: "E.164-Nummer",
    jwt: "JWT",
    template_literal: "Eingabe"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "Zahl",
    array: "Array"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ung\xFCltige Eingabe: erwartet instanceof ${issue2.expected}, erhalten ${received}`;
        }
        return `Ung\xFCltige Eingabe: erwartet ${expected}, erhalten ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ung\xFCltige Eingabe: erwartet ${stringifyPrimitive(issue2.values[0])}`;
        return `Ung\xFCltige Option: erwartet eine von ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Zu gro\xDF: erwartet, dass ${(_c = issue2.origin) != null ? _c : "Wert"} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "Elemente"} hat`;
        return `Zu gro\xDF: erwartet, dass ${(_e = issue2.origin) != null ? _e : "Wert"} ${adj}${issue2.maximum.toString()} ist`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} hat`;
        }
        return `Zu klein: erwartet, dass ${issue2.origin} ${adj}${issue2.minimum.toString()} ist`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ung\xFCltiger String: muss mit "${_issue.prefix}" beginnen`;
        if (_issue.format === "ends_with")
          return `Ung\xFCltiger String: muss mit "${_issue.suffix}" enden`;
        if (_issue.format === "includes")
          return `Ung\xFCltiger String: muss "${_issue.includes}" enthalten`;
        if (_issue.format === "regex")
          return `Ung\xFCltiger String: muss dem Muster ${_issue.pattern} entsprechen`;
        return `Ung\xFCltig: ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Ung\xFCltige Zahl: muss ein Vielfaches von ${issue2.divisor} sein`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Unbekannte Schl\xFCssel" : "Unbekannter Schl\xFCssel"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ung\xFCltiger Schl\xFCssel in ${issue2.origin}`;
      case "invalid_union":
        return "Ung\xFCltige Eingabe";
      case "invalid_element":
        return `Ung\xFCltiger Wert in ${issue2.origin}`;
      default:
        return `Ung\xFCltige Eingabe`;
    }
  };
};
function de_default2() {
  return {
    localeError: error8()
  };
}

// node_modules/zod/v4/locales/en.js
var error9 = () => {
  const Sizable = {
    string: { unit: "characters", verb: "to have" },
    file: { unit: "bytes", verb: "to have" },
    array: { unit: "items", verb: "to have" },
    set: { unit: "items", verb: "to have" },
    map: { unit: "entries", verb: "to have" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    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",
    mac: "MAC 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"
  };
  const TypeDictionary = {
    // Compatibility: "nan" -> "NaN" for display
    nan: "NaN"
    // All other type names omitted - they fall back to raw values via ?? operator
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        return `Invalid input: expected ${expected}, received ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
        return `Invalid option: expected one of ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Too big: expected ${(_c = issue2.origin) != null ? _c : "value"} to have ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elements"}`;
        return `Too big: expected ${(_e = issue2.origin) != null ? _e : "value"} to be ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Too small: expected ${issue2.origin} to have ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Too small: expected ${issue2.origin} to be ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Invalid string: must start with "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Invalid string: must end with "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Invalid string: must include "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Invalid string: must match pattern ${_issue.pattern}`;
        return `Invalid ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Invalid number: must be a multiple of ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Unrecognized key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Invalid key in ${issue2.origin}`;
      case "invalid_union":
        return "Invalid input";
      case "invalid_element":
        return `Invalid value in ${issue2.origin}`;
      default:
        return `Invalid input`;
    }
  };
};
function en_default3() {
  return {
    localeError: error9()
  };
}

// node_modules/zod/v4/locales/eo.js
var error10 = () => {
  const Sizable = {
    string: { unit: "karaktrojn", verb: "havi" },
    file: { unit: "bajtojn", verb: "havi" },
    array: { unit: "elementojn", verb: "havi" },
    set: { unit: "elementojn", verb: "havi" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "enigo",
    email: "retadreso",
    url: "URL",
    emoji: "emo\u011Dio",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-datotempo",
    date: "ISO-dato",
    time: "ISO-tempo",
    duration: "ISO-da\u016Dro",
    ipv4: "IPv4-adreso",
    ipv6: "IPv6-adreso",
    cidrv4: "IPv4-rango",
    cidrv6: "IPv6-rango",
    base64: "64-ume kodita karaktraro",
    base64url: "URL-64-ume kodita karaktraro",
    json_string: "JSON-karaktraro",
    e164: "E.164-nombro",
    jwt: "JWT",
    template_literal: "enigo"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nombro",
    array: "tabelo",
    null: "senvalora"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Nevalida enigo: atendi\u011Dis instanceof ${issue2.expected}, ricevi\u011Dis ${received}`;
        }
        return `Nevalida enigo: atendi\u011Dis ${expected}, ricevi\u011Dis ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Nevalida enigo: atendi\u011Dis ${stringifyPrimitive(issue2.values[0])}`;
        return `Nevalida opcio: atendi\u011Dis unu el ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Tro granda: atendi\u011Dis ke ${(_c = issue2.origin) != null ? _c : "valoro"} havu ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elementojn"}`;
        return `Tro granda: atendi\u011Dis ke ${(_e = issue2.origin) != null ? _e : "valoro"} havu ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} havu ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Tro malgranda: atendi\u011Dis ke ${issue2.origin} estu ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Nevalida karaktraro: devas komenci\u011Di per "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Nevalida karaktraro: devas fini\u011Di per "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`;
        return `Nevalida ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Nevalida nombro: devas esti oblo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Nekonata${issue2.keys.length > 1 ? "j" : ""} \u015Dlosilo${issue2.keys.length > 1 ? "j" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Nevalida \u015Dlosilo en ${issue2.origin}`;
      case "invalid_union":
        return "Nevalida enigo";
      case "invalid_element":
        return `Nevalida valoro en ${issue2.origin}`;
      default:
        return `Nevalida enigo`;
    }
  };
};
function eo_default() {
  return {
    localeError: error10()
  };
}

// node_modules/zod/v4/locales/es.js
var error11 = () => {
  const Sizable = {
    string: { unit: "caracteres", verb: "tener" },
    file: { unit: "bytes", verb: "tener" },
    array: { unit: "elementos", verb: "tener" },
    set: { unit: "elementos", verb: "tener" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "entrada",
    email: "direcci\xF3n de correo electr\xF3nico",
    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: "fecha y hora ISO",
    date: "fecha ISO",
    time: "hora ISO",
    duration: "duraci\xF3n ISO",
    ipv4: "direcci\xF3n IPv4",
    ipv6: "direcci\xF3n IPv6",
    cidrv4: "rango IPv4",
    cidrv6: "rango IPv6",
    base64: "cadena codificada en base64",
    base64url: "URL codificada en base64",
    json_string: "cadena JSON",
    e164: "n\xFAmero E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN",
    string: "texto",
    number: "n\xFAmero",
    boolean: "booleano",
    array: "arreglo",
    object: "objeto",
    set: "conjunto",
    file: "archivo",
    date: "fecha",
    bigint: "n\xFAmero grande",
    symbol: "s\xEDmbolo",
    undefined: "indefinido",
    null: "nulo",
    function: "funci\xF3n",
    map: "mapa",
    record: "registro",
    tuple: "tupla",
    enum: "enumeraci\xF3n",
    union: "uni\xF3n",
    literal: "literal",
    promise: "promesa",
    void: "vac\xEDo",
    never: "nunca",
    unknown: "desconocido",
    any: "cualquiera"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entrada inv\xE1lida: se esperaba instanceof ${issue2.expected}, recibido ${received}`;
        }
        return `Entrada inv\xE1lida: se esperaba ${expected}, recibido ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entrada inv\xE1lida: se esperaba ${stringifyPrimitive(issue2.values[0])}`;
        return `Opci\xF3n inv\xE1lida: se esperaba una de ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const origin = (_c = TypeDictionary[issue2.origin]) != null ? _c : issue2.origin;
        if (sizing)
          return `Demasiado grande: se esperaba que ${origin != null ? origin : "valor"} tuviera ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elementos"}`;
        return `Demasiado grande: se esperaba que ${origin != null ? origin : "valor"} fuera ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const origin = (_e = TypeDictionary[issue2.origin]) != null ? _e : issue2.origin;
        if (sizing) {
          return `Demasiado peque\xF1o: se esperaba que ${origin} tuviera ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Demasiado peque\xF1o: se esperaba que ${origin} fuera ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Cadena inv\xE1lida: debe comenzar con "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Cadena inv\xE1lida: debe terminar en "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Cadena inv\xE1lida: debe incluir "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Cadena inv\xE1lida: debe coincidir con el patr\xF3n ${_issue.pattern}`;
        return `Inv\xE1lido ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: debe ser m\xFAltiplo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Llave${issue2.keys.length > 1 ? "s" : ""} desconocida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Llave inv\xE1lida en ${(_g = TypeDictionary[issue2.origin]) != null ? _g : issue2.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido en ${(_h = TypeDictionary[issue2.origin]) != null ? _h : issue2.origin}`;
      default:
        return `Entrada inv\xE1lida`;
    }
  };
};
function es_default2() {
  return {
    localeError: error11()
  };
}

// node_modules/zod/v4/locales/fa.js
var error12 = () => {
  const Sizable = {
    string: { unit: "\u06A9\u0627\u0631\u0627\u06A9\u062A\u0631", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
    file: { unit: "\u0628\u0627\u06CC\u062A", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
    array: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" },
    set: { unit: "\u0622\u06CC\u062A\u0645", verb: "\u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0648\u0631\u0648\u062F\u06CC",
    email: "\u0622\u062F\u0631\u0633 \u0627\u06CC\u0645\u06CC\u0644",
    url: "URL",
    emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u062A\u0627\u0631\u06CC\u062E \u0648 \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
    date: "\u062A\u0627\u0631\u06CC\u062E \u0627\u06CC\u0632\u0648",
    time: "\u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
    duration: "\u0645\u062F\u062A \u0632\u0645\u0627\u0646 \u0627\u06CC\u0632\u0648",
    ipv4: "IPv4 \u0622\u062F\u0631\u0633",
    ipv6: "IPv6 \u0622\u062F\u0631\u0633",
    cidrv4: "IPv4 \u062F\u0627\u0645\u0646\u0647",
    cidrv6: "IPv6 \u062F\u0627\u0645\u0646\u0647",
    base64: "base64-encoded \u0631\u0634\u062A\u0647",
    base64url: "base64url-encoded \u0631\u0634\u062A\u0647",
    json_string: "JSON \u0631\u0634\u062A\u0647",
    e164: "E.164 \u0639\u062F\u062F",
    jwt: "JWT",
    template_literal: "\u0648\u0631\u0648\u062F\u06CC"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0639\u062F\u062F",
    array: "\u0622\u0631\u0627\u06CC\u0647"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A instanceof ${issue2.expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
        }
        return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${expected} \u0645\u06CC\u200C\u0628\u0648\u062F\u060C ${received} \u062F\u0631\u06CC\u0627\u0641\u062A \u0634\u062F`;
      }
      case "invalid_value":
        if (issue2.values.length === 1) {
          return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A ${stringifyPrimitive(issue2.values[0])} \u0645\u06CC\u200C\u0628\u0648\u062F`;
        }
        return `\u06AF\u0632\u06CC\u0646\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0645\u06CC\u200C\u0628\u0627\u06CC\u0633\u062A \u06CC\u06A9\u06CC \u0627\u0632 ${joinValues(issue2.values, "|")} \u0645\u06CC\u200C\u0628\u0648\u062F`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${(_c = issue2.origin) != null ? _c : "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u0639\u0646\u0635\u0631"} \u0628\u0627\u0634\u062F`;
        }
        return `\u062E\u06CC\u0644\u06CC \u0628\u0632\u0631\u06AF: ${(_e = issue2.origin) != null ? _e : "\u0645\u0642\u062F\u0627\u0631"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0628\u0627\u0634\u062F`;
        }
        return `\u062E\u06CC\u0644\u06CC \u06A9\u0648\u0686\u06A9: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0628\u0627\u0634\u062F`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.prefix}" \u0634\u0631\u0648\u0639 \u0634\u0648\u062F`;
        }
        if (_issue.format === "ends_with") {
          return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 "${_issue.suffix}" \u062A\u0645\u0627\u0645 \u0634\u0648\u062F`;
        }
        if (_issue.format === "includes") {
          return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0634\u0627\u0645\u0644 "${_issue.includes}" \u0628\u0627\u0634\u062F`;
        }
        if (_issue.format === "regex") {
          return `\u0631\u0634\u062A\u0647 \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0628\u0627 \u0627\u0644\u06AF\u0648\u06CC ${_issue.pattern} \u0645\u0637\u0627\u0628\u0642\u062A \u062F\u0627\u0634\u062A\u0647 \u0628\u0627\u0634\u062F`;
        }
        return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
      }
      case "not_multiple_of":
        return `\u0639\u062F\u062F \u0646\u0627\u0645\u0639\u062A\u0628\u0631: \u0628\u0627\u06CC\u062F \u0645\u0636\u0631\u0628 ${issue2.divisor} \u0628\u0627\u0634\u062F`;
      case "unrecognized_keys":
        return `\u06A9\u0644\u06CC\u062F${issue2.keys.length > 1 ? "\u0647\u0627\u06CC" : ""} \u0646\u0627\u0634\u0646\u0627\u0633: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u06A9\u0644\u06CC\u062F \u0646\u0627\u0634\u0646\u0627\u0633 \u062F\u0631 ${issue2.origin}`;
      case "invalid_union":
        return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
      case "invalid_element":
        return `\u0645\u0642\u062F\u0627\u0631 \u0646\u0627\u0645\u0639\u062A\u0628\u0631 \u062F\u0631 ${issue2.origin}`;
      default:
        return `\u0648\u0631\u0648\u062F\u06CC \u0646\u0627\u0645\u0639\u062A\u0628\u0631`;
    }
  };
};
function fa_default() {
  return {
    localeError: error12()
  };
}

// node_modules/zod/v4/locales/fi.js
var error13 = () => {
  const Sizable = {
    string: { unit: "merkki\xE4", subject: "merkkijonon" },
    file: { unit: "tavua", subject: "tiedoston" },
    array: { unit: "alkiota", subject: "listan" },
    set: { unit: "alkiota", subject: "joukon" },
    number: { unit: "", subject: "luvun" },
    bigint: { unit: "", subject: "suuren kokonaisluvun" },
    int: { unit: "", subject: "kokonaisluvun" },
    date: { unit: "", subject: "p\xE4iv\xE4m\xE4\xE4r\xE4n" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "s\xE4\xE4nn\xF6llinen lauseke",
    email: "s\xE4hk\xF6postiosoite",
    url: "URL-osoite",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO-aikaleima",
    date: "ISO-p\xE4iv\xE4m\xE4\xE4r\xE4",
    time: "ISO-aika",
    duration: "ISO-kesto",
    ipv4: "IPv4-osoite",
    ipv6: "IPv6-osoite",
    cidrv4: "IPv4-alue",
    cidrv6: "IPv6-alue",
    base64: "base64-koodattu merkkijono",
    base64url: "base64url-koodattu merkkijono",
    json_string: "JSON-merkkijono",
    e164: "E.164-luku",
    jwt: "JWT",
    template_literal: "templaattimerkkijono"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Virheellinen tyyppi: odotettiin instanceof ${issue2.expected}, oli ${received}`;
        }
        return `Virheellinen tyyppi: odotettiin ${expected}, oli ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Virheellinen sy\xF6te: t\xE4ytyy olla ${stringifyPrimitive(issue2.values[0])}`;
        return `Virheellinen valinta: t\xE4ytyy olla yksi seuraavista: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Liian suuri: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.maximum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian suuri: arvon t\xE4ytyy olla ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Liian pieni: ${sizing.subject} t\xE4ytyy olla ${adj}${issue2.minimum.toString()} ${sizing.unit}`.trim();
        }
        return `Liian pieni: arvon t\xE4ytyy olla ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Virheellinen sy\xF6te: t\xE4ytyy alkaa "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Virheellinen sy\xF6te: t\xE4ytyy loppua "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Virheellinen sy\xF6te: t\xE4ytyy sis\xE4lt\xE4\xE4 "${_issue.includes}"`;
        if (_issue.format === "regex") {
          return `Virheellinen sy\xF6te: t\xE4ytyy vastata s\xE4\xE4nn\xF6llist\xE4 lauseketta ${_issue.pattern}`;
        }
        return `Virheellinen ${(_c = FormatDictionary[_issue.format]) != null ? _c : issue2.format}`;
      }
      case "not_multiple_of":
        return `Virheellinen luku: t\xE4ytyy olla luvun ${issue2.divisor} monikerta`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return "Virheellinen avain tietueessa";
      case "invalid_union":
        return "Virheellinen unioni";
      case "invalid_element":
        return "Virheellinen arvo joukossa";
      default:
        return `Virheellinen sy\xF6te`;
    }
  };
};
function fi_default() {
  return {
    localeError: error13()
  };
}

// node_modules/zod/v4/locales/fr.js
var error14 = () => {
  const Sizable = {
    string: { unit: "caract\xE8res", verb: "avoir" },
    file: { unit: "octets", verb: "avoir" },
    array: { unit: "\xE9l\xE9ments", verb: "avoir" },
    set: { unit: "\xE9l\xE9ments", verb: "avoir" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "entr\xE9e",
    email: "adresse e-mail",
    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: "date et heure ISO",
    date: "date ISO",
    time: "heure ISO",
    duration: "dur\xE9e ISO",
    ipv4: "adresse IPv4",
    ipv6: "adresse IPv6",
    cidrv4: "plage IPv4",
    cidrv6: "plage IPv6",
    base64: "cha\xEEne encod\xE9e en base64",
    base64url: "cha\xEEne encod\xE9e en base64url",
    json_string: "cha\xEEne JSON",
    e164: "num\xE9ro E.164",
    jwt: "JWT",
    template_literal: "entr\xE9e"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nombre",
    array: "tableau"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entr\xE9e invalide : instanceof ${issue2.expected} attendu, ${received} re\xE7u`;
        }
        return `Entr\xE9e invalide : ${expected} attendu, ${received} re\xE7u`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entr\xE9e invalide : ${stringifyPrimitive(issue2.values[0])} attendu`;
        return `Option invalide : une valeur parmi ${joinValues(issue2.values, "|")} attendue`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Trop grand : ${(_c = issue2.origin) != null ? _c : "valeur"} doit ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\xE9l\xE9ment(s)"}`;
        return `Trop grand : ${(_e = issue2.origin) != null ? _e : "valeur"} doit \xEAtre ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Trop petit : ${issue2.origin} doit ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Trop petit : ${issue2.origin} doit \xEAtre ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Cha\xEEne invalide : doit correspondre au mod\xE8le ${_issue.pattern}`;
        return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${issue2.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue2.origin}`;
      default:
        return `Entr\xE9e invalide`;
    }
  };
};
function fr_default2() {
  return {
    localeError: error14()
  };
}

// node_modules/zod/v4/locales/fr-CA.js
var error15 = () => {
  const Sizable = {
    string: { unit: "caract\xE8res", verb: "avoir" },
    file: { unit: "octets", verb: "avoir" },
    array: { unit: "\xE9l\xE9ments", verb: "avoir" },
    set: { unit: "\xE9l\xE9ments", verb: "avoir" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "entr\xE9e",
    email: "adresse courriel",
    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: "date-heure ISO",
    date: "date ISO",
    time: "heure ISO",
    duration: "dur\xE9e ISO",
    ipv4: "adresse IPv4",
    ipv6: "adresse IPv6",
    cidrv4: "plage IPv4",
    cidrv6: "plage IPv6",
    base64: "cha\xEEne encod\xE9e en base64",
    base64url: "cha\xEEne encod\xE9e en base64url",
    json_string: "cha\xEEne JSON",
    e164: "num\xE9ro E.164",
    jwt: "JWT",
    template_literal: "entr\xE9e"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Entr\xE9e invalide : attendu instanceof ${issue2.expected}, re\xE7u ${received}`;
        }
        return `Entr\xE9e invalide : attendu ${expected}, re\xE7u ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entr\xE9e invalide : attendu ${stringifyPrimitive(issue2.values[0])}`;
        return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "\u2264" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Trop grand : attendu que ${(_c = issue2.origin) != null ? _c : "la valeur"} ait ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        return `Trop grand : attendu que ${(_d2 = issue2.origin) != null ? _d2 : "la valeur"} soit ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "\u2265" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Trop petit : attendu que ${issue2.origin} ait ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Trop petit : attendu que ${issue2.origin} soit ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Cha\xEEne invalide : doit commencer par "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Cha\xEEne invalide : doit se terminer par "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Cha\xEEne invalide : doit inclure "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Cha\xEEne invalide : doit correspondre au motif ${_issue.pattern}`;
        return `${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format} invalide`;
      }
      case "not_multiple_of":
        return `Nombre invalide : doit \xEAtre un multiple de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Cl\xE9${issue2.keys.length > 1 ? "s" : ""} non reconnue${issue2.keys.length > 1 ? "s" : ""} : ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Cl\xE9 invalide dans ${issue2.origin}`;
      case "invalid_union":
        return "Entr\xE9e invalide";
      case "invalid_element":
        return `Valeur invalide dans ${issue2.origin}`;
      default:
        return `Entr\xE9e invalide`;
    }
  };
};
function fr_CA_default() {
  return {
    localeError: error15()
  };
}

// node_modules/zod/v4/locales/he.js
var error16 = () => {
  const TypeNames = {
    string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA", gender: "f" },
    number: { label: "\u05DE\u05E1\u05E4\u05E8", gender: "m" },
    boolean: { label: "\u05E2\u05E8\u05DA \u05D1\u05D5\u05DC\u05D9\u05D0\u05E0\u05D9", gender: "m" },
    bigint: { label: "BigInt", gender: "m" },
    date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA", gender: "m" },
    array: { label: "\u05DE\u05E2\u05E8\u05DA", gender: "m" },
    object: { label: "\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8", gender: "m" },
    null: { label: "\u05E2\u05E8\u05DA \u05E8\u05D9\u05E7 (null)", gender: "m" },
    undefined: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05DE\u05D5\u05D2\u05D3\u05E8 (undefined)", gender: "m" },
    symbol: { label: "\u05E1\u05D9\u05DE\u05D1\u05D5\u05DC (Symbol)", gender: "m" },
    function: { label: "\u05E4\u05D5\u05E0\u05E7\u05E6\u05D9\u05D4", gender: "f" },
    map: { label: "\u05DE\u05E4\u05D4 (Map)", gender: "f" },
    set: { label: "\u05E7\u05D1\u05D5\u05E6\u05D4 (Set)", gender: "f" },
    file: { label: "\u05E7\u05D5\u05D1\u05E5", gender: "m" },
    promise: { label: "Promise", gender: "m" },
    NaN: { label: "NaN", gender: "m" },
    unknown: { label: "\u05E2\u05E8\u05DA \u05DC\u05D0 \u05D9\u05D3\u05D5\u05E2", gender: "m" },
    value: { label: "\u05E2\u05E8\u05DA", gender: "m" }
  };
  const Sizable = {
    string: { unit: "\u05EA\u05D5\u05D5\u05D9\u05DD", shortLabel: "\u05E7\u05E6\u05E8", longLabel: "\u05D0\u05E8\u05D5\u05DA" },
    file: { unit: "\u05D1\u05D9\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
    array: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
    set: { unit: "\u05E4\u05E8\u05D9\u05D8\u05D9\u05DD", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" },
    number: { unit: "", shortLabel: "\u05E7\u05D8\u05DF", longLabel: "\u05D2\u05D3\u05D5\u05DC" }
    // no unit
  };
  const typeEntry = (t2) => t2 ? TypeNames[t2] : void 0;
  const typeLabel = (t2) => {
    const e2 = typeEntry(t2);
    if (e2)
      return e2.label;
    return t2 != null ? t2 : TypeNames.unknown.label;
  };
  const withDefinite = (t2) => `\u05D4${typeLabel(t2)}`;
  const verbFor = (t2) => {
    var _a3;
    const e2 = typeEntry(t2);
    const gender = (_a3 = e2 == null ? void 0 : e2.gender) != null ? _a3 : "m";
    return gender === "f" ? "\u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05D9\u05D5\u05EA" : "\u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA";
  };
  const getSizing = (origin) => {
    var _a3;
    if (!origin)
      return null;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  };
  const FormatDictionary = {
    regex: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    email: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05D0\u05D9\u05DE\u05D9\u05D9\u05DC", gender: "f" },
    url: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA \u05E8\u05E9\u05EA", gender: "f" },
    emoji: { label: "\u05D0\u05D9\u05DE\u05D5\u05D2'\u05D9", gender: "m" },
    uuid: { label: "UUID", gender: "m" },
    nanoid: { label: "nanoid", gender: "m" },
    guid: { label: "GUID", gender: "m" },
    cuid: { label: "cuid", gender: "m" },
    cuid2: { label: "cuid2", gender: "m" },
    ulid: { label: "ULID", gender: "m" },
    xid: { label: "XID", gender: "m" },
    ksuid: { label: "KSUID", gender: "m" },
    datetime: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA \u05D5\u05D6\u05DE\u05DF ISO", gender: "m" },
    date: { label: "\u05EA\u05D0\u05E8\u05D9\u05DA ISO", gender: "m" },
    time: { label: "\u05D6\u05DE\u05DF ISO", gender: "m" },
    duration: { label: "\u05DE\u05E9\u05DA \u05D6\u05DE\u05DF ISO", gender: "m" },
    ipv4: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv4", gender: "f" },
    ipv6: { label: "\u05DB\u05EA\u05D5\u05D1\u05EA IPv6", gender: "f" },
    cidrv4: { label: "\u05D8\u05D5\u05D5\u05D7 IPv4", gender: "m" },
    cidrv6: { label: "\u05D8\u05D5\u05D5\u05D7 IPv6", gender: "m" },
    base64: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64", gender: "f" },
    base64url: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D1\u05D1\u05E1\u05D9\u05E1 64 \u05DC\u05DB\u05EA\u05D5\u05D1\u05D5\u05EA \u05E8\u05E9\u05EA", gender: "f" },
    json_string: { label: "\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA JSON", gender: "f" },
    e164: { label: "\u05DE\u05E1\u05E4\u05E8 E.164", gender: "m" },
    jwt: { label: "JWT", gender: "m" },
    ends_with: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    includes: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    lowercase: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    starts_with: { label: "\u05E7\u05DC\u05D8", gender: "m" },
    uppercase: { label: "\u05E7\u05DC\u05D8", gender: "m" }
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l, _m, _n, _o, _p2, _q, _r, _s, _t, _u;
    switch (issue2.code) {
      case "invalid_type": {
        const expectedKey = issue2.expected;
        const expected = (_a3 = TypeDictionary[expectedKey != null ? expectedKey : ""]) != null ? _a3 : typeLabel(expectedKey);
        const receivedType = parsedType(issue2.input);
        const received = (_d2 = (_c = TypeDictionary[receivedType]) != null ? _c : (_b2 = TypeNames[receivedType]) == null ? void 0 : _b2.label) != null ? _d2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA instanceof ${issue2.expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;
        }
        return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${expected}, \u05D4\u05EA\u05E7\u05D1\u05DC ${received}`;
      }
      case "invalid_value": {
        if (issue2.values.length === 1) {
          return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05E2\u05E8\u05DA \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA ${stringifyPrimitive(issue2.values[0])}`;
        }
        const stringified = issue2.values.map((v2) => stringifyPrimitive(v2));
        if (issue2.values.length === 2) {
          return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${stringified[0]} \u05D0\u05D5 ${stringified[1]}`;
        }
        const lastValue = stringified[stringified.length - 1];
        const restValues = stringified.slice(0, -1).join(", ");
        return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D4\u05D0\u05E4\u05E9\u05E8\u05D5\u05D9\u05D5\u05EA \u05D4\u05DE\u05EA\u05D0\u05D9\u05DE\u05D5\u05EA \u05D4\u05DF ${restValues} \u05D0\u05D5 ${lastValue}`;
      }
      case "too_big": {
        const sizing = getSizing(issue2.origin);
        const subject = withDefinite((_e = issue2.origin) != null ? _e : "value");
        if (issue2.origin === "string") {
          return `${(_f = sizing == null ? void 0 : sizing.longLabel) != null ? _f : "\u05D0\u05E8\u05D5\u05DA"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.maximum.toString()} ${(_g = sizing == null ? void 0 : sizing.unit) != null ? _g : ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA" : "\u05DC\u05DB\u05DC \u05D4\u05D9\u05D5\u05EA\u05E8"}`.trim();
        }
        if (issue2.origin === "number") {
          const comparison = issue2.inclusive ? `\u05E7\u05D8\u05DF \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.maximum}` : `\u05E7\u05D8\u05DF \u05DE-${issue2.maximum}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue2.origin === "array" || issue2.origin === "set") {
          const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          const comparison = issue2.inclusive ? `${issue2.maximum} ${(_h = sizing == null ? void 0 : sizing.unit) != null ? _h : ""} \u05D0\u05D5 \u05E4\u05D7\u05D5\u05EA` : `\u05E4\u05D7\u05D5\u05EA \u05DE-${issue2.maximum} ${(_i = sizing == null ? void 0 : sizing.unit) != null ? _i : ""}`;
          return `\u05D2\u05D3\u05D5\u05DC \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue2.inclusive ? "<=" : "<";
        const be = verbFor((_j2 = issue2.origin) != null ? _j2 : "value");
        if (sizing == null ? void 0 : sizing.unit) {
          return `${sizing.longLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        }
        return `${(_k = sizing == null ? void 0 : sizing.longLabel) != null ? _k : "\u05D2\u05D3\u05D5\u05DC"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const sizing = getSizing(issue2.origin);
        const subject = withDefinite((_l = issue2.origin) != null ? _l : "value");
        if (issue2.origin === "string") {
          return `${(_m = sizing == null ? void 0 : sizing.shortLabel) != null ? _m : "\u05E7\u05E6\u05E8"} \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DB\u05D4 \u05DC\u05D4\u05DB\u05D9\u05DC ${issue2.minimum.toString()} ${(_n = sizing == null ? void 0 : sizing.unit) != null ? _n : ""} ${issue2.inclusive ? "\u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8" : "\u05DC\u05E4\u05D7\u05D5\u05EA"}`.trim();
        }
        if (issue2.origin === "number") {
          const comparison = issue2.inclusive ? `\u05D2\u05D3\u05D5\u05DC \u05D0\u05D5 \u05E9\u05D5\u05D5\u05D4 \u05DC-${issue2.minimum}` : `\u05D2\u05D3\u05D5\u05DC \u05DE-${issue2.minimum}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} \u05E6\u05E8\u05D9\u05DA \u05DC\u05D4\u05D9\u05D5\u05EA ${comparison}`;
        }
        if (issue2.origin === "array" || issue2.origin === "set") {
          const verb = issue2.origin === "set" ? "\u05E6\u05E8\u05D9\u05DB\u05D4" : "\u05E6\u05E8\u05D9\u05DA";
          if (issue2.minimum === 1 && issue2.inclusive) {
            const singularPhrase = issue2.origin === "set" ? "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3" : "\u05DC\u05E4\u05D7\u05D5\u05EA \u05E4\u05E8\u05D9\u05D8 \u05D0\u05D7\u05D3";
            return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${singularPhrase}`;
          }
          const comparison = issue2.inclusive ? `${issue2.minimum} ${(_o = sizing == null ? void 0 : sizing.unit) != null ? _o : ""} \u05D0\u05D5 \u05D9\u05D5\u05EA\u05E8` : `\u05D9\u05D5\u05EA\u05E8 \u05DE-${issue2.minimum} ${(_p2 = sizing == null ? void 0 : sizing.unit) != null ? _p2 : ""}`;
          return `\u05E7\u05D8\u05DF \u05DE\u05D3\u05D9: ${subject} ${verb} \u05DC\u05D4\u05DB\u05D9\u05DC ${comparison}`.trim();
        }
        const adj = issue2.inclusive ? ">=" : ">";
        const be = verbFor((_q = issue2.origin) != null ? _q : "value");
        if (sizing == null ? void 0 : sizing.unit) {
          return `${sizing.shortLabel} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `${(_r = sizing == null ? void 0 : sizing.shortLabel) != null ? _r : "\u05E7\u05D8\u05DF"} \u05DE\u05D3\u05D9: ${subject} ${be} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D7\u05D9\u05DC \u05D1 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05E1\u05EA\u05D9\u05D9\u05DD \u05D1 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05DB\u05DC\u05D5\u05DC "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u05D4\u05DE\u05D7\u05E8\u05D5\u05D6\u05EA \u05D7\u05D9\u05D9\u05D1\u05EA \u05DC\u05D4\u05EA\u05D0\u05D9\u05DD \u05DC\u05EA\u05D1\u05E0\u05D9\u05EA ${_issue.pattern}`;
        const nounEntry = FormatDictionary[_issue.format];
        const noun = (_s = nounEntry == null ? void 0 : nounEntry.label) != null ? _s : _issue.format;
        const gender = (_t = nounEntry == null ? void 0 : nounEntry.gender) != null ? _t : "m";
        const adjective = gender === "f" ? "\u05EA\u05E7\u05D9\u05E0\u05D4" : "\u05EA\u05E7\u05D9\u05DF";
        return `${noun} \u05DC\u05D0 ${adjective}`;
      }
      case "not_multiple_of":
        return `\u05DE\u05E1\u05E4\u05E8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF: \u05D7\u05D9\u05D9\u05D1 \u05DC\u05D4\u05D9\u05D5\u05EA \u05DE\u05DB\u05E4\u05DC\u05D4 \u05E9\u05DC ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u05DE\u05E4\u05EA\u05D7${issue2.keys.length > 1 ? "\u05D5\u05EA" : ""} \u05DC\u05D0 \u05DE\u05D6\u05D5\u05D4${issue2.keys.length > 1 ? "\u05D9\u05DD" : "\u05D4"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key": {
        return `\u05E9\u05D3\u05D4 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1\u05D0\u05D5\u05D1\u05D9\u05D9\u05E7\u05D8`;
      }
      case "invalid_union":
        return "\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF";
      case "invalid_element": {
        const place = withDefinite((_u = issue2.origin) != null ? _u : "array");
        return `\u05E2\u05E8\u05DA \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF \u05D1${place}`;
      }
      default:
        return `\u05E7\u05DC\u05D8 \u05DC\u05D0 \u05EA\u05E7\u05D9\u05DF`;
    }
  };
};
function he_default() {
  return {
    localeError: error16()
  };
}

// node_modules/zod/v4/locales/hu.js
var error17 = () => {
  const Sizable = {
    string: { unit: "karakter", verb: "legyen" },
    file: { unit: "byte", verb: "legyen" },
    array: { unit: "elem", verb: "legyen" },
    set: { unit: "elem", verb: "legyen" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "bemenet",
    email: "email c\xEDm",
    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 id\u0151b\xE9lyeg",
    date: "ISO d\xE1tum",
    time: "ISO id\u0151",
    duration: "ISO id\u0151intervallum",
    ipv4: "IPv4 c\xEDm",
    ipv6: "IPv6 c\xEDm",
    cidrv4: "IPv4 tartom\xE1ny",
    cidrv6: "IPv6 tartom\xE1ny",
    base64: "base64-k\xF3dolt string",
    base64url: "base64url-k\xF3dolt string",
    json_string: "JSON string",
    e164: "E.164 sz\xE1m",
    jwt: "JWT",
    template_literal: "bemenet"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "sz\xE1m",
    array: "t\xF6mb"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k instanceof ${issue2.expected}, a kapott \xE9rt\xE9k ${received}`;
        }
        return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${expected}, a kapott \xE9rt\xE9k ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\xC9rv\xE9nytelen bemenet: a v\xE1rt \xE9rt\xE9k ${stringifyPrimitive(issue2.values[0])}`;
        return `\xC9rv\xE9nytelen opci\xF3: valamelyik \xE9rt\xE9k v\xE1rt ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `T\xFAl nagy: ${(_c = issue2.origin) != null ? _c : "\xE9rt\xE9k"} m\xE9rete t\xFAl nagy ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elem"}`;
        return `T\xFAl nagy: a bemeneti \xE9rt\xE9k ${(_e = issue2.origin) != null ? _e : "\xE9rt\xE9k"} t\xFAl nagy: ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} m\xE9rete t\xFAl kicsi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `T\xFAl kicsi: a bemeneti \xE9rt\xE9k ${issue2.origin} t\xFAl kicsi ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\xC9rv\xE9nytelen string: "${_issue.prefix}" \xE9rt\xE9kkel kell kezd\u0151dnie`;
        if (_issue.format === "ends_with")
          return `\xC9rv\xE9nytelen string: "${_issue.suffix}" \xE9rt\xE9kkel kell v\xE9gz\u0151dnie`;
        if (_issue.format === "includes")
          return `\xC9rv\xE9nytelen string: "${_issue.includes}" \xE9rt\xE9ket kell tartalmaznia`;
        if (_issue.format === "regex")
          return `\xC9rv\xE9nytelen string: ${_issue.pattern} mint\xE1nak kell megfelelnie`;
        return `\xC9rv\xE9nytelen ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\xC9rv\xE9nytelen sz\xE1m: ${issue2.divisor} t\xF6bbsz\xF6r\xF6s\xE9nek kell lennie`;
      case "unrecognized_keys":
        return `Ismeretlen kulcs${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\xC9rv\xE9nytelen kulcs ${issue2.origin}`;
      case "invalid_union":
        return "\xC9rv\xE9nytelen bemenet";
      case "invalid_element":
        return `\xC9rv\xE9nytelen \xE9rt\xE9k: ${issue2.origin}`;
      default:
        return `\xC9rv\xE9nytelen bemenet`;
    }
  };
};
function hu_default() {
  return {
    localeError: error17()
  };
}

// node_modules/zod/v4/locales/hy.js
function getArmenianPlural(count, one, many) {
  return Math.abs(count) === 1 ? one : many;
}
function withDefiniteArticle(word) {
  if (!word)
    return "";
  const vowels = ["\u0561", "\u0565", "\u0568", "\u056B", "\u0578", "\u0578\u0582", "\u0585"];
  const lastChar = word[word.length - 1];
  return word + (vowels.includes(lastChar) ? "\u0576" : "\u0568");
}
var error18 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "\u0576\u0577\u0561\u0576",
        many: "\u0576\u0577\u0561\u0576\u0576\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    },
    file: {
      unit: {
        one: "\u0562\u0561\u0575\u0569",
        many: "\u0562\u0561\u0575\u0569\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    },
    array: {
      unit: {
        one: "\u057F\u0561\u0580\u0580",
        many: "\u057F\u0561\u0580\u0580\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    },
    set: {
      unit: {
        one: "\u057F\u0561\u0580\u0580",
        many: "\u057F\u0561\u0580\u0580\u0565\u0580"
      },
      verb: "\u0578\u0582\u0576\u0565\u0576\u0561\u056C"
    }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0574\u0578\u0582\u057F\u0584",
    email: "\u0567\u056C. \u0570\u0561\u057D\u0581\u0565",
    url: "URL",
    emoji: "\u0567\u0574\u0578\u057B\u056B",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E \u0587 \u056A\u0561\u0574",
    date: "ISO \u0561\u0574\u057D\u0561\u0569\u056B\u057E",
    time: "ISO \u056A\u0561\u0574",
    duration: "ISO \u057F\u0587\u0578\u0572\u0578\u0582\u0569\u0575\u0578\u0582\u0576",
    ipv4: "IPv4 \u0570\u0561\u057D\u0581\u0565",
    ipv6: "IPv6 \u0570\u0561\u057D\u0581\u0565",
    cidrv4: "IPv4 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",
    cidrv6: "IPv6 \u0574\u056B\u057B\u0561\u056F\u0561\u0575\u0584",
    base64: "base64 \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",
    base64url: "base64url \u0571\u0587\u0561\u0579\u0561\u0583\u0578\u057E \u057F\u0578\u0572",
    json_string: "JSON \u057F\u0578\u0572",
    e164: "E.164 \u0570\u0561\u0574\u0561\u0580",
    jwt: "JWT",
    template_literal: "\u0574\u0578\u0582\u057F\u0584"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0569\u056B\u057E",
    array: "\u0566\u0561\u0576\u0563\u057E\u0561\u056E"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 instanceof ${issue2.expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;
        }
        return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${expected}, \u057D\u057F\u0561\u0581\u057E\u0565\u056C \u0567 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 ${stringifyPrimitive(issue2.values[1])}`;
        return `\u054D\u056D\u0561\u056C \u057F\u0561\u0580\u0562\u0565\u0580\u0561\u056F\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567\u0580 \u0570\u0565\u057F\u0587\u0575\u0561\u056C\u0576\u0565\u0580\u056B\u0581 \u0574\u0565\u056F\u0568\u055D ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit = getArmenianPlural(maxValue, sizing.unit.one, sizing.unit.many);
          return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle((_c = issue2.origin) != null ? _c : "\u0561\u0580\u056A\u0565\u0584")} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.maximum.toString()} ${unit}`;
        }
        return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0574\u0565\u056E \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle((_d2 = issue2.origin) != null ? _d2 : "\u0561\u0580\u056A\u0565\u0584")} \u056C\u056B\u0576\u056B ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit = getArmenianPlural(minValue, sizing.unit.one, sizing.unit.many);
          return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056F\u0578\u0582\u0576\u0565\u0576\u0561 ${adj}${issue2.minimum.toString()} ${unit}`;
        }
        return `\u0549\u0561\u0583\u0561\u0566\u0561\u0576\u0581 \u0583\u0578\u0584\u0580 \u0561\u0580\u056A\u0565\u0584\u2024 \u057D\u057A\u0561\u057D\u057E\u0578\u0582\u0574 \u0567, \u0578\u0580 ${withDefiniteArticle(issue2.origin)} \u056C\u056B\u0576\u056B ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057D\u056F\u057D\u057E\u056B "${_issue.prefix}"-\u0578\u057E`;
        if (_issue.format === "ends_with")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0561\u057E\u0561\u0580\u057F\u057E\u056B "${_issue.suffix}"-\u0578\u057E`;
        if (_issue.format === "includes")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u057A\u0561\u0580\u0578\u0582\u0576\u0561\u056F\u056B "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u054D\u056D\u0561\u056C \u057F\u0578\u0572\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0570\u0561\u0574\u0561\u057A\u0561\u057F\u0561\u057D\u056D\u0561\u0576\u056B ${_issue.pattern} \u0571\u0587\u0561\u0579\u0561\u0583\u056B\u0576`;
        return `\u054D\u056D\u0561\u056C ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u054D\u056D\u0561\u056C \u0569\u056B\u057E\u2024 \u057A\u0565\u057F\u0584 \u0567 \u0562\u0561\u0566\u0574\u0561\u057A\u0561\u057F\u056B\u056F \u056C\u056B\u0576\u056B ${issue2.divisor}-\u056B`;
      case "unrecognized_keys":
        return `\u0549\u0573\u0561\u0576\u0561\u0579\u057E\u0561\u056E \u0562\u0561\u0576\u0561\u056C\u056B${issue2.keys.length > 1 ? "\u0576\u0565\u0580" : ""}. ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u054D\u056D\u0561\u056C \u0562\u0561\u0576\u0561\u056C\u056B ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;
      case "invalid_union":
        return "\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574";
      case "invalid_element":
        return `\u054D\u056D\u0561\u056C \u0561\u0580\u056A\u0565\u0584 ${withDefiniteArticle(issue2.origin)}-\u0578\u0582\u0574`;
      default:
        return `\u054D\u056D\u0561\u056C \u0574\u0578\u0582\u057F\u0584\u0561\u0563\u0580\u0578\u0582\u0574`;
    }
  };
};
function hy_default() {
  return {
    localeError: error18()
  };
}

// node_modules/zod/v4/locales/id.js
var error19 = () => {
  const Sizable = {
    string: { unit: "karakter", verb: "memiliki" },
    file: { unit: "byte", verb: "memiliki" },
    array: { unit: "item", verb: "memiliki" },
    set: { unit: "item", verb: "memiliki" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "alamat email",
    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: "tanggal dan waktu format ISO",
    date: "tanggal format ISO",
    time: "jam format ISO",
    duration: "durasi format ISO",
    ipv4: "alamat IPv4",
    ipv6: "alamat IPv6",
    cidrv4: "rentang alamat IPv4",
    cidrv6: "rentang alamat IPv6",
    base64: "string dengan enkode base64",
    base64url: "string dengan enkode base64url",
    json_string: "string JSON",
    e164: "angka E.164",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Input tidak valid: diharapkan instanceof ${issue2.expected}, diterima ${received}`;
        }
        return `Input tidak valid: diharapkan ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Input tidak valid: diharapkan ${stringifyPrimitive(issue2.values[0])}`;
        return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Terlalu besar: diharapkan ${(_c = issue2.origin) != null ? _c : "value"} memiliki ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elemen"}`;
        return `Terlalu besar: diharapkan ${(_e = issue2.origin) != null ? _e : "value"} menjadi ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Terlalu kecil: diharapkan ${issue2.origin} memiliki ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: diharapkan ${issue2.origin} menjadi ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `String tidak valid: harus menyertakan "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `String tidak valid: harus sesuai pola ${_issue.pattern}`;
        return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} tidak valid`;
      }
      case "not_multiple_of":
        return `Angka tidak valid: harus kelipatan dari ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak valid di ${issue2.origin}`;
      case "invalid_union":
        return "Input tidak valid";
      case "invalid_element":
        return `Nilai tidak valid di ${issue2.origin}`;
      default:
        return `Input tidak valid`;
    }
  };
};
function id_default() {
  return {
    localeError: error19()
  };
}

// node_modules/zod/v4/locales/is.js
var error20 = () => {
  const Sizable = {
    string: { unit: "stafi", verb: "a\xF0 hafa" },
    file: { unit: "b\xE6ti", verb: "a\xF0 hafa" },
    array: { unit: "hluti", verb: "a\xF0 hafa" },
    set: { unit: "hluti", verb: "a\xF0 hafa" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "gildi",
    email: "netfang",
    url: "vefsl\xF3\xF0",
    emoji: "emoji",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO dagsetning og t\xEDmi",
    date: "ISO dagsetning",
    time: "ISO t\xEDmi",
    duration: "ISO t\xEDmalengd",
    ipv4: "IPv4 address",
    ipv6: "IPv6 address",
    cidrv4: "IPv4 range",
    cidrv6: "IPv6 range",
    base64: "base64-encoded strengur",
    base64url: "base64url-encoded strengur",
    json_string: "JSON strengur",
    e164: "E.164 t\xF6lugildi",
    jwt: "JWT",
    template_literal: "gildi"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "n\xFAmer",
    array: "fylki"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera instanceof ${issue2.expected}`;
        }
        return `Rangt gildi: \xDE\xFA sl\xF3st inn ${received} \xFEar sem \xE1 a\xF0 vera ${expected}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Rangt gildi: gert r\xE1\xF0 fyrir ${stringifyPrimitive(issue2.values[0])}`;
        return `\xD3gilt val: m\xE1 vera eitt af eftirfarandi ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${(_c = issue2.origin) != null ? _c : "gildi"} hafi ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "hluti"}`;
        return `Of st\xF3rt: gert er r\xE1\xF0 fyrir a\xF0 ${(_e = issue2.origin) != null ? _e : "gildi"} s\xE9 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} hafi ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Of l\xEDti\xF0: gert er r\xE1\xF0 fyrir a\xF0 ${issue2.origin} s\xE9 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\xD3gildur strengur: ver\xF0ur a\xF0 byrja \xE1 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\xD3gildur strengur: ver\xF0ur a\xF0 enda \xE1 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\xD3gildur strengur: ver\xF0ur a\xF0 innihalda "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\xD3gildur strengur: ver\xF0ur a\xF0 fylgja mynstri ${_issue.pattern}`;
        return `Rangt ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `R\xF6ng tala: ver\xF0ur a\xF0 vera margfeldi af ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\xD3\xFEekkt ${issue2.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Rangur lykill \xED ${issue2.origin}`;
      case "invalid_union":
        return "Rangt gildi";
      case "invalid_element":
        return `Rangt gildi \xED ${issue2.origin}`;
      default:
        return `Rangt gildi`;
    }
  };
};
function is_default() {
  return {
    localeError: error20()
  };
}

// node_modules/zod/v4/locales/it.js
var error21 = () => {
  const Sizable = {
    string: { unit: "caratteri", verb: "avere" },
    file: { unit: "byte", verb: "avere" },
    array: { unit: "elementi", verb: "avere" },
    set: { unit: "elementi", verb: "avere" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "indirizzo email",
    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: "data e ora ISO",
    date: "data ISO",
    time: "ora ISO",
    duration: "durata ISO",
    ipv4: "indirizzo IPv4",
    ipv6: "indirizzo IPv6",
    cidrv4: "intervallo IPv4",
    cidrv6: "intervallo IPv6",
    base64: "stringa codificata in base64",
    base64url: "URL codificata in base64",
    json_string: "stringa JSON",
    e164: "numero E.164",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "numero",
    array: "vettore"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Input non valido: atteso instanceof ${issue2.expected}, ricevuto ${received}`;
        }
        return `Input non valido: atteso ${expected}, ricevuto ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Input non valido: atteso ${stringifyPrimitive(issue2.values[0])}`;
        return `Opzione non valida: atteso uno tra ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Troppo grande: ${(_c = issue2.origin) != null ? _c : "valore"} deve avere ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elementi"}`;
        return `Troppo grande: ${(_e = issue2.origin) != null ? _e : "valore"} deve essere ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Troppo piccolo: ${issue2.origin} deve avere ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Troppo piccolo: ${issue2.origin} deve essere ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Stringa non valida: deve iniziare con "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Stringa non valida: deve terminare con "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Stringa non valida: deve includere "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`;
        return `Invalid ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Numero non valido: deve essere un multiplo di ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Chiav${issue2.keys.length > 1 ? "i" : "e"} non riconosciut${issue2.keys.length > 1 ? "e" : "a"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Chiave non valida in ${issue2.origin}`;
      case "invalid_union":
        return "Input non valido";
      case "invalid_element":
        return `Valore non valido in ${issue2.origin}`;
      default:
        return `Input non valido`;
    }
  };
};
function it_default() {
  return {
    localeError: error21()
  };
}

// node_modules/zod/v4/locales/ja.js
var error22 = () => {
  const Sizable = {
    string: { unit: "\u6587\u5B57", verb: "\u3067\u3042\u308B" },
    file: { unit: "\u30D0\u30A4\u30C8", verb: "\u3067\u3042\u308B" },
    array: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" },
    set: { unit: "\u8981\u7D20", verb: "\u3067\u3042\u308B" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u5165\u529B\u5024",
    email: "\u30E1\u30FC\u30EB\u30A2\u30C9\u30EC\u30B9",
    url: "URL",
    emoji: "\u7D75\u6587\u5B57",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO\u65E5\u6642",
    date: "ISO\u65E5\u4ED8",
    time: "ISO\u6642\u523B",
    duration: "ISO\u671F\u9593",
    ipv4: "IPv4\u30A2\u30C9\u30EC\u30B9",
    ipv6: "IPv6\u30A2\u30C9\u30EC\u30B9",
    cidrv4: "IPv4\u7BC4\u56F2",
    cidrv6: "IPv6\u7BC4\u56F2",
    base64: "base64\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
    base64url: "base64url\u30A8\u30F3\u30B3\u30FC\u30C9\u6587\u5B57\u5217",
    json_string: "JSON\u6587\u5B57\u5217",
    e164: "E.164\u756A\u53F7",
    jwt: "JWT",
    template_literal: "\u5165\u529B\u5024"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u6570\u5024",
    array: "\u914D\u5217"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u7121\u52B9\u306A\u5165\u529B: instanceof ${issue2.expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
        }
        return `\u7121\u52B9\u306A\u5165\u529B: ${expected}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F\u304C\u3001${received}\u304C\u5165\u529B\u3055\u308C\u307E\u3057\u305F`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u7121\u52B9\u306A\u5165\u529B: ${stringifyPrimitive(issue2.values[0])}\u304C\u671F\u5F85\u3055\u308C\u307E\u3057\u305F`;
        return `\u7121\u52B9\u306A\u9078\u629E: ${joinValues(issue2.values, "\u3001")}\u306E\u3044\u305A\u308C\u304B\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      case "too_big": {
        const adj = issue2.inclusive ? "\u4EE5\u4E0B\u3067\u3042\u308B" : "\u3088\u308A\u5C0F\u3055\u3044";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u5927\u304D\u3059\u304E\u308B\u5024: ${(_c = issue2.origin) != null ? _c : "\u5024"}\u306F${issue2.maximum.toString()}${(_d2 = sizing.unit) != null ? _d2 : "\u8981\u7D20"}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5927\u304D\u3059\u304E\u308B\u5024: ${(_e = issue2.origin) != null ? _e : "\u5024"}\u306F${issue2.maximum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "\u4EE5\u4E0A\u3067\u3042\u308B" : "\u3088\u308A\u5927\u304D\u3044";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${sizing.unit}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u5C0F\u3055\u3059\u304E\u308B\u5024: ${issue2.origin}\u306F${issue2.minimum.toString()}${adj}\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.prefix}"\u3067\u59CB\u307E\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        if (_issue.format === "ends_with")
          return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.suffix}"\u3067\u7D42\u308F\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        if (_issue.format === "includes")
          return `\u7121\u52B9\u306A\u6587\u5B57\u5217: "${_issue.includes}"\u3092\u542B\u3080\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        if (_issue.format === "regex")
          return `\u7121\u52B9\u306A\u6587\u5B57\u5217: \u30D1\u30BF\u30FC\u30F3${_issue.pattern}\u306B\u4E00\u81F4\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
        return `\u7121\u52B9\u306A${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u52B9\u306A\u6570\u5024: ${issue2.divisor}\u306E\u500D\u6570\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059`;
      case "unrecognized_keys":
        return `\u8A8D\u8B58\u3055\u308C\u3066\u3044\u306A\u3044\u30AD\u30FC${issue2.keys.length > 1 ? "\u7FA4" : ""}: ${joinValues(issue2.keys, "\u3001")}`;
      case "invalid_key":
        return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u30AD\u30FC`;
      case "invalid_union":
        return "\u7121\u52B9\u306A\u5165\u529B";
      case "invalid_element":
        return `${issue2.origin}\u5185\u306E\u7121\u52B9\u306A\u5024`;
      default:
        return `\u7121\u52B9\u306A\u5165\u529B`;
    }
  };
};
function ja_default2() {
  return {
    localeError: error22()
  };
}

// node_modules/zod/v4/locales/ka.js
var error23 = () => {
  const Sizable = {
    string: { unit: "\u10E1\u10D8\u10DB\u10D1\u10DD\u10DA\u10DD", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
    file: { unit: "\u10D1\u10D0\u10D8\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
    array: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" },
    set: { unit: "\u10D4\u10DA\u10D4\u10DB\u10D4\u10DC\u10E2\u10D8", verb: "\u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0",
    email: "\u10D4\u10DA-\u10E4\u10DD\u10E1\u10E2\u10D8\u10E1 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
    url: "URL",
    emoji: "\u10D4\u10DB\u10DD\u10EF\u10D8",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8-\u10D3\u10E0\u10DD",
    date: "\u10D7\u10D0\u10E0\u10D8\u10E6\u10D8",
    time: "\u10D3\u10E0\u10DD",
    duration: "\u10EE\u10D0\u10DC\u10D2\u10E0\u10EB\u10DA\u10D8\u10D5\u10DD\u10D1\u10D0",
    ipv4: "IPv4 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
    ipv6: "IPv6 \u10DB\u10D8\u10E1\u10D0\u10DB\u10D0\u10E0\u10D7\u10D8",
    cidrv4: "IPv4 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",
    cidrv6: "IPv6 \u10D3\u10D8\u10D0\u10DE\u10D0\u10D6\u10DD\u10DC\u10D8",
    base64: "base64-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",
    base64url: "base64url-\u10D9\u10DD\u10D3\u10D8\u10E0\u10D4\u10D1\u10E3\u10DA\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",
    json_string: "JSON \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",
    e164: "E.164 \u10DC\u10DD\u10DB\u10D4\u10E0\u10D8",
    jwt: "JWT",
    template_literal: "\u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u10E0\u10D8\u10EA\u10EE\u10D5\u10D8",
    string: "\u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8",
    boolean: "\u10D1\u10E3\u10DA\u10D4\u10D0\u10DC\u10D8",
    function: "\u10E4\u10E3\u10DC\u10E5\u10EA\u10D8\u10D0",
    array: "\u10DB\u10D0\u10E1\u10D8\u10D5\u10D8"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 instanceof ${issue2.expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;
        }
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${expected}, \u10DB\u10D8\u10E6\u10D4\u10D1\u10E3\u10DA\u10D8 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D5\u10D0\u10E0\u10D8\u10D0\u10DC\u10E2\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8\u10D0 \u10D4\u10E0\u10D7-\u10D4\u10E0\u10D7\u10D8 ${joinValues(issue2.values, "|")}-\u10D3\u10D0\u10DC`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${(_c = issue2.origin) != null ? _c : "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${sizing.unit}`;
        return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10D3\u10D8\u10D3\u10D8: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${(_d2 = issue2.origin) != null ? _d2 : "\u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0"} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u10D6\u10D4\u10D3\u10DB\u10D4\u10E2\u10D0\u10D3 \u10DE\u10D0\u10E2\u10D0\u10E0\u10D0: \u10DB\u10DD\u10E1\u10D0\u10DA\u10DD\u10D3\u10DC\u10D4\u10DA\u10D8 ${issue2.origin} \u10D8\u10E7\u10DD\u10E1 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10EC\u10E7\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.prefix}"-\u10D8\u10D7`;
        }
        if (_issue.format === "ends_with")
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10DB\u10D7\u10D0\u10D5\u10E0\u10D3\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 "${_issue.suffix}"-\u10D8\u10D7`;
        if (_issue.format === "includes")
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D8\u10EA\u10D0\u10D5\u10D3\u10D4\u10E1 "${_issue.includes}"-\u10E1`;
        if (_issue.format === "regex")
          return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E1\u10E2\u10E0\u10D8\u10DC\u10D2\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10E8\u10D4\u10D4\u10E1\u10D0\u10D1\u10D0\u10DB\u10D4\u10D1\u10DD\u10D3\u10D4\u10E1 \u10E8\u10D0\u10D1\u10DA\u10DD\u10DC\u10E1 ${_issue.pattern}`;
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E0\u10D8\u10EA\u10EE\u10D5\u10D8: \u10E3\u10DC\u10D3\u10D0 \u10D8\u10E7\u10DD\u10E1 ${issue2.divisor}-\u10D8\u10E1 \u10EF\u10D4\u10E0\u10D0\u10D3\u10D8`;
      case "unrecognized_keys":
        return `\u10E3\u10EA\u10DC\u10DD\u10D1\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1${issue2.keys.length > 1 ? "\u10D4\u10D1\u10D8" : "\u10D8"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10D2\u10D0\u10E1\u10D0\u10E6\u10D4\u10D1\u10D8 ${issue2.origin}-\u10E8\u10D8`;
      case "invalid_union":
        return "\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0";
      case "invalid_element":
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10DB\u10DC\u10D8\u10E8\u10D5\u10DC\u10D4\u10DA\u10DD\u10D1\u10D0 ${issue2.origin}-\u10E8\u10D8`;
      default:
        return `\u10D0\u10E0\u10D0\u10E1\u10EC\u10DD\u10E0\u10D8 \u10E8\u10D4\u10E7\u10D5\u10D0\u10DC\u10D0`;
    }
  };
};
function ka_default() {
  return {
    localeError: error23()
  };
}

// node_modules/zod/v4/locales/km.js
var error24 = () => {
  const Sizable = {
    string: { unit: "\u178F\u17BD\u17A2\u1780\u17D2\u179F\u179A", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
    file: { unit: "\u1794\u17C3", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
    array: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" },
    set: { unit: "\u1792\u17B6\u178F\u17BB", verb: "\u1782\u17BD\u179A\u1798\u17B6\u1793" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B",
    email: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793\u17A2\u17CA\u17B8\u1798\u17C2\u179B",
    url: "URL",
    emoji: "\u179F\u1789\u17D2\u1789\u17B6\u17A2\u17B6\u179A\u1798\u17D2\u1798\u178E\u17CD",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 \u1793\u17B7\u1784\u1798\u17C9\u17C4\u1784 ISO",
    date: "\u1780\u17B6\u179B\u1794\u179A\u17B7\u1785\u17D2\u1786\u17C1\u1791 ISO",
    time: "\u1798\u17C9\u17C4\u1784 ISO",
    duration: "\u179A\u1799\u17C8\u1796\u17C1\u179B ISO",
    ipv4: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
    ipv6: "\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
    cidrv4: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv4",
    cidrv6: "\u178A\u17C2\u1793\u17A2\u17B6\u179F\u1799\u178A\u17D2\u178B\u17B6\u1793 IPv6",
    base64: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64",
    base64url: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u17A2\u17CA\u17B7\u1780\u17BC\u178A base64url",
    json_string: "\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A JSON",
    e164: "\u179B\u17C1\u1781 E.164",
    jwt: "JWT",
    template_literal: "\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u179B\u17C1\u1781",
    array: "\u17A2\u17B6\u179A\u17C1 (Array)",
    null: "\u1782\u17D2\u1798\u17B6\u1793\u178F\u1798\u17D2\u179B\u17C3 (null)"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A instanceof ${issue2.expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;
        }
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${expected} \u1794\u17C9\u17BB\u1793\u17D2\u178F\u17C2\u1791\u1791\u17BD\u179B\u1794\u17B6\u1793 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1794\u1789\u17D2\u1785\u17BC\u179B\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${stringifyPrimitive(issue2.values[0])}`;
        return `\u1787\u1798\u17D2\u179A\u17BE\u179F\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1787\u17B6\u1798\u17BD\u1799\u1780\u17D2\u1793\u17BB\u1784\u1785\u17C6\u178E\u17C4\u1798 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${(_c = issue2.origin) != null ? _c : "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u1792\u17B6\u178F\u17BB"}`;
        return `\u1792\u17C6\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${(_e = issue2.origin) != null ? _e : "\u178F\u1798\u17D2\u179B\u17C3"} ${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u178F\u17BC\u1785\u1796\u17C1\u1780\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1780\u17B6\u179A ${issue2.origin} ${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1785\u17B6\u1794\u17CB\u1795\u17D2\u178F\u17BE\u1798\u178A\u17C4\u1799 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1794\u1789\u17D2\u1785\u1794\u17CB\u178A\u17C4\u1799 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u1798\u17B6\u1793 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u1781\u17D2\u179F\u17C2\u17A2\u1780\u17D2\u179F\u179A\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1795\u17D2\u1782\u17BC\u1795\u17D2\u1782\u1784\u1793\u17B9\u1784\u1791\u1798\u17D2\u179A\u1784\u17CB\u178A\u17C2\u179B\u1794\u17B6\u1793\u1780\u17C6\u178E\u178F\u17CB ${_issue.pattern}`;
        return `\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u179B\u17C1\u1781\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u17D6 \u178F\u17D2\u179A\u17BC\u179C\u178F\u17C2\u1787\u17B6\u1796\u17A0\u17BB\u1782\u17BB\u178E\u1793\u17C3 ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u179A\u1780\u1783\u17BE\u1789\u179F\u17C4\u1798\u17B7\u1793\u179F\u17D2\u1782\u17B6\u179B\u17CB\u17D6 ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u179F\u17C4\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
      case "invalid_union":
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
      case "invalid_element":
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C\u1793\u17C5\u1780\u17D2\u1793\u17BB\u1784 ${issue2.origin}`;
      default:
        return `\u1791\u17B7\u1793\u17D2\u1793\u1793\u17D0\u1799\u1798\u17B7\u1793\u178F\u17D2\u179A\u17B9\u1798\u178F\u17D2\u179A\u17BC\u179C`;
    }
  };
};
function km_default() {
  return {
    localeError: error24()
  };
}

// node_modules/zod/v4/locales/kh.js
function kh_default() {
  return km_default();
}

// node_modules/zod/v4/locales/ko.js
var error25 = () => {
  const Sizable = {
    string: { unit: "\uBB38\uC790", verb: "to have" },
    file: { unit: "\uBC14\uC774\uD2B8", verb: "to have" },
    array: { unit: "\uAC1C", verb: "to have" },
    set: { unit: "\uAC1C", verb: "to have" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\uC785\uB825",
    email: "\uC774\uBA54\uC77C \uC8FC\uC18C",
    url: "URL",
    emoji: "\uC774\uBAA8\uC9C0",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \uB0A0\uC9DC\uC2DC\uAC04",
    date: "ISO \uB0A0\uC9DC",
    time: "ISO \uC2DC\uAC04",
    duration: "ISO \uAE30\uAC04",
    ipv4: "IPv4 \uC8FC\uC18C",
    ipv6: "IPv6 \uC8FC\uC18C",
    cidrv4: "IPv4 \uBC94\uC704",
    cidrv6: "IPv6 \uBC94\uC704",
    base64: "base64 \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
    base64url: "base64url \uC778\uCF54\uB529 \uBB38\uC790\uC5F4",
    json_string: "JSON \uBB38\uC790\uC5F4",
    e164: "E.164 \uBC88\uD638",
    jwt: "JWT",
    template_literal: "\uC785\uB825"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 instanceof ${issue2.expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;
        }
        return `\uC798\uBABB\uB41C \uC785\uB825: \uC608\uC0C1 \uD0C0\uC785\uC740 ${expected}, \uBC1B\uC740 \uD0C0\uC785\uC740 ${received}\uC785\uB2C8\uB2E4`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\uC798\uBABB\uB41C \uC785\uB825: \uAC12\uC740 ${stringifyPrimitive(issue2.values[0])} \uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4`;
        return `\uC798\uBABB\uB41C \uC635\uC158: ${joinValues(issue2.values, "\uB610\uB294 ")} \uC911 \uD558\uB098\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "too_big": {
        const adj = issue2.inclusive ? "\uC774\uD558" : "\uBBF8\uB9CC";
        const suffix = adj === "\uBBF8\uB9CC" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
        const sizing = getSizing(issue2.origin);
        const unit = (_c = sizing == null ? void 0 : sizing.unit) != null ? _c : "\uC694\uC18C";
        if (sizing)
          return `${(_d2 = issue2.origin) != null ? _d2 : "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()}${unit} ${adj}${suffix}`;
        return `${(_e = issue2.origin) != null ? _e : "\uAC12"}\uC774 \uB108\uBB34 \uD07D\uB2C8\uB2E4: ${issue2.maximum.toString()} ${adj}${suffix}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "\uC774\uC0C1" : "\uCD08\uACFC";
        const suffix = adj === "\uC774\uC0C1" ? "\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4" : "\uC5EC\uC57C \uD569\uB2C8\uB2E4";
        const sizing = getSizing(issue2.origin);
        const unit = (_f = sizing == null ? void 0 : sizing.unit) != null ? _f : "\uC694\uC18C";
        if (sizing) {
          return `${(_g = issue2.origin) != null ? _g : "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()}${unit} ${adj}${suffix}`;
        }
        return `${(_h = issue2.origin) != null ? _h : "\uAC12"}\uC774 \uB108\uBB34 \uC791\uC2B5\uB2C8\uB2E4: ${issue2.minimum.toString()} ${adj}${suffix}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.prefix}"(\uC73C)\uB85C \uC2DC\uC791\uD574\uC57C \uD569\uB2C8\uB2E4`;
        }
        if (_issue.format === "ends_with")
          return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.suffix}"(\uC73C)\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4`;
        if (_issue.format === "includes")
          return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: "${_issue.includes}"\uC744(\uB97C) \uD3EC\uD568\uD574\uC57C \uD569\uB2C8\uB2E4`;
        if (_issue.format === "regex")
          return `\uC798\uBABB\uB41C \uBB38\uC790\uC5F4: \uC815\uADDC\uC2DD ${_issue.pattern} \uD328\uD134\uACFC \uC77C\uCE58\uD574\uC57C \uD569\uB2C8\uB2E4`;
        return `\uC798\uBABB\uB41C ${(_i = FormatDictionary[_issue.format]) != null ? _i : issue2.format}`;
      }
      case "not_multiple_of":
        return `\uC798\uBABB\uB41C \uC22B\uC790: ${issue2.divisor}\uC758 \uBC30\uC218\uC5EC\uC57C \uD569\uB2C8\uB2E4`;
      case "unrecognized_keys":
        return `\uC778\uC2DD\uD560 \uC218 \uC5C6\uB294 \uD0A4: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\uC798\uBABB\uB41C \uD0A4: ${issue2.origin}`;
      case "invalid_union":
        return `\uC798\uBABB\uB41C \uC785\uB825`;
      case "invalid_element":
        return `\uC798\uBABB\uB41C \uAC12: ${issue2.origin}`;
      default:
        return `\uC798\uBABB\uB41C \uC785\uB825`;
    }
  };
};
function ko_default2() {
  return {
    localeError: error25()
  };
}

// node_modules/zod/v4/locales/lt.js
var capitalizeFirstCharacter = (text) => {
  return text.charAt(0).toUpperCase() + text.slice(1);
};
function getUnitTypeFromNumber(number5) {
  const abs = Math.abs(number5);
  const last = abs % 10;
  const last2 = abs % 100;
  if (last2 >= 11 && last2 <= 19 || last === 0)
    return "many";
  if (last === 1)
    return "one";
  return "few";
}
var error26 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "simbolis",
        few: "simboliai",
        many: "simboli\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi b\u016Bti ne ilgesn\u0117 kaip",
          notInclusive: "turi b\u016Bti trumpesn\u0117 kaip"
        },
        bigger: {
          inclusive: "turi b\u016Bti ne trumpesn\u0117 kaip",
          notInclusive: "turi b\u016Bti ilgesn\u0117 kaip"
        }
      }
    },
    file: {
      unit: {
        one: "baitas",
        few: "baitai",
        many: "bait\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi b\u016Bti ne didesnis kaip",
          notInclusive: "turi b\u016Bti ma\u017Eesnis kaip"
        },
        bigger: {
          inclusive: "turi b\u016Bti ne ma\u017Eesnis kaip",
          notInclusive: "turi b\u016Bti didesnis kaip"
        }
      }
    },
    array: {
      unit: {
        one: "element\u0105",
        few: "elementus",
        many: "element\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi tur\u0117ti ne daugiau kaip",
          notInclusive: "turi tur\u0117ti ma\u017Eiau kaip"
        },
        bigger: {
          inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip",
          notInclusive: "turi tur\u0117ti daugiau kaip"
        }
      }
    },
    set: {
      unit: {
        one: "element\u0105",
        few: "elementus",
        many: "element\u0173"
      },
      verb: {
        smaller: {
          inclusive: "turi tur\u0117ti ne daugiau kaip",
          notInclusive: "turi tur\u0117ti ma\u017Eiau kaip"
        },
        bigger: {
          inclusive: "turi tur\u0117ti ne ma\u017Eiau kaip",
          notInclusive: "turi tur\u0117ti daugiau kaip"
        }
      }
    }
  };
  function getSizing(origin, unitType, inclusive, targetShouldBe) {
    var _a3;
    const result = (_a3 = Sizable[origin]) != null ? _a3 : null;
    if (result === null)
      return result;
    return {
      unit: result.unit[unitType],
      verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"]
    };
  }
  const FormatDictionary = {
    regex: "\u012Fvestis",
    email: "el. pa\u0161to adresas",
    url: "URL",
    emoji: "jaustukas",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO data ir laikas",
    date: "ISO data",
    time: "ISO laikas",
    duration: "ISO trukm\u0117",
    ipv4: "IPv4 adresas",
    ipv6: "IPv6 adresas",
    cidrv4: "IPv4 tinklo prefiksas (CIDR)",
    cidrv6: "IPv6 tinklo prefiksas (CIDR)",
    base64: "base64 u\u017Ekoduota eilut\u0117",
    base64url: "base64url u\u017Ekoduota eilut\u0117",
    json_string: "JSON eilut\u0117",
    e164: "E.164 numeris",
    jwt: "JWT",
    template_literal: "\u012Fvestis"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "skai\u010Dius",
    bigint: "sveikasis skai\u010Dius",
    string: "eilut\u0117",
    boolean: "login\u0117 reik\u0161m\u0117",
    undefined: "neapibr\u0117\u017Eta reik\u0161m\u0117",
    function: "funkcija",
    symbol: "simbolis",
    array: "masyvas",
    object: "objektas",
    null: "nulin\u0117 reik\u0161m\u0117"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l, _m, _n, _o;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Gautas tipas ${received}, o tik\u0117tasi - instanceof ${issue2.expected}`;
        }
        return `Gautas tipas ${received}, o tik\u0117tasi - ${expected}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Privalo b\u016Bti ${stringifyPrimitive(issue2.values[0])}`;
        return `Privalo b\u016Bti vienas i\u0161 ${joinValues(issue2.values, "|")} pasirinkim\u0173`;
      case "too_big": {
        const origin = (_c = TypeDictionary[issue2.origin]) != null ? _c : issue2.origin;
        const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.maximum)), (_d2 = issue2.inclusive) != null ? _d2 : false, "smaller");
        if (sizing == null ? void 0 : sizing.verb)
          return `${capitalizeFirstCharacter((_e = origin != null ? origin : issue2.origin) != null ? _e : "reik\u0161m\u0117")} ${sizing.verb} ${issue2.maximum.toString()} ${(_f = sizing.unit) != null ? _f : "element\u0173"}`;
        const adj = issue2.inclusive ? "ne didesnis kaip" : "ma\u017Eesnis kaip";
        return `${capitalizeFirstCharacter((_g = origin != null ? origin : issue2.origin) != null ? _g : "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.maximum.toString()} ${sizing == null ? void 0 : sizing.unit}`;
      }
      case "too_small": {
        const origin = (_h = TypeDictionary[issue2.origin]) != null ? _h : issue2.origin;
        const sizing = getSizing(issue2.origin, getUnitTypeFromNumber(Number(issue2.minimum)), (_i = issue2.inclusive) != null ? _i : false, "bigger");
        if (sizing == null ? void 0 : sizing.verb)
          return `${capitalizeFirstCharacter((_j2 = origin != null ? origin : issue2.origin) != null ? _j2 : "reik\u0161m\u0117")} ${sizing.verb} ${issue2.minimum.toString()} ${(_k = sizing.unit) != null ? _k : "element\u0173"}`;
        const adj = issue2.inclusive ? "ne ma\u017Eesnis kaip" : "didesnis kaip";
        return `${capitalizeFirstCharacter((_l = origin != null ? origin : issue2.origin) != null ? _l : "reik\u0161m\u0117")} turi b\u016Bti ${adj} ${issue2.minimum.toString()} ${sizing == null ? void 0 : sizing.unit}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Eilut\u0117 privalo prasid\u0117ti "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Eilut\u0117 privalo pasibaigti "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Eilut\u0117 privalo \u012Ftraukti "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Eilut\u0117 privalo atitikti ${_issue.pattern}`;
        return `Neteisingas ${(_m = FormatDictionary[_issue.format]) != null ? _m : issue2.format}`;
      }
      case "not_multiple_of":
        return `Skai\u010Dius privalo b\u016Bti ${issue2.divisor} kartotinis.`;
      case "unrecognized_keys":
        return `Neatpa\u017Eint${issue2.keys.length > 1 ? "i" : "as"} rakt${issue2.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return "Rastas klaidingas raktas";
      case "invalid_union":
        return "Klaidinga \u012Fvestis";
      case "invalid_element": {
        const origin = (_n = TypeDictionary[issue2.origin]) != null ? _n : issue2.origin;
        return `${capitalizeFirstCharacter((_o = origin != null ? origin : issue2.origin) != null ? _o : "reik\u0161m\u0117")} turi klaiding\u0105 \u012Fvest\u012F`;
      }
      default:
        return "Klaidinga \u012Fvestis";
    }
  };
};
function lt_default() {
  return {
    localeError: error26()
  };
}

// node_modules/zod/v4/locales/mk.js
var error27 = () => {
  const Sizable = {
    string: { unit: "\u0437\u043D\u0430\u0446\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
    file: { unit: "\u0431\u0430\u0458\u0442\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
    array: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" },
    set: { unit: "\u0441\u0442\u0430\u0432\u043A\u0438", verb: "\u0434\u0430 \u0438\u043C\u0430\u0430\u0442" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0432\u043D\u0435\u0441",
    email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u043D\u0430 \u0435-\u043F\u043E\u0448\u0442\u0430",
    url: "URL",
    emoji: "\u0435\u043C\u043E\u045F\u0438",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0434\u0430\u0442\u0443\u043C \u0438 \u0432\u0440\u0435\u043C\u0435",
    date: "ISO \u0434\u0430\u0442\u0443\u043C",
    time: "ISO \u0432\u0440\u0435\u043C\u0435",
    duration: "ISO \u0432\u0440\u0435\u043C\u0435\u0442\u0440\u0430\u0435\u045A\u0435",
    ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441\u0430",
    ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441\u0430",
    cidrv4: "IPv4 \u043E\u043F\u0441\u0435\u0433",
    cidrv6: "IPv6 \u043E\u043F\u0441\u0435\u0433",
    base64: "base64-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
    base64url: "base64url-\u0435\u043D\u043A\u043E\u0434\u0438\u0440\u0430\u043D\u0430 \u043D\u0438\u0437\u0430",
    json_string: "JSON \u043D\u0438\u0437\u0430",
    e164: "E.164 \u0431\u0440\u043E\u0458",
    jwt: "JWT",
    template_literal: "\u0432\u043D\u0435\u0441"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0431\u0440\u043E\u0458",
    array: "\u043D\u0438\u0437\u0430"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 instanceof ${issue2.expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;
        }
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${expected}, \u043F\u0440\u0438\u043C\u0435\u043D\u043E ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Invalid input: expected ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0413\u0440\u0435\u0448\u0430\u043D\u0430 \u043E\u043F\u0446\u0438\u0458\u0430: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 \u0435\u0434\u043D\u0430 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${(_c = issue2.origin) != null ? _c : "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0438"}`;
        return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u0433\u043E\u043B\u0435\u043C: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${(_e = issue2.origin) != null ? _e : "\u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442\u0430"} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0438\u043C\u0430 ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u041F\u0440\u0435\u043C\u043D\u043E\u0433\u0443 \u043C\u0430\u043B: \u0441\u0435 \u043E\u0447\u0435\u043A\u0443\u0432\u0430 ${issue2.origin} \u0434\u0430 \u0431\u0438\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u043F\u043E\u0447\u043D\u0443\u0432\u0430 \u0441\u043E "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0437\u0430\u0432\u0440\u0448\u0443\u0432\u0430 \u0441\u043E "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0432\u043A\u043B\u0443\u0447\u0443\u0432\u0430 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u0432\u0430\u0436\u0435\u0447\u043A\u0430 \u043D\u0438\u0437\u0430: \u043C\u043E\u0440\u0430 \u0434\u0430 \u043E\u0434\u0433\u043E\u0430\u0440\u0430 \u043D\u0430 \u043F\u0430\u0442\u0435\u0440\u043D\u043E\u0442 ${_issue.pattern}`;
        return `Invalid ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0431\u0440\u043E\u0458: \u043C\u043E\u0440\u0430 \u0434\u0430 \u0431\u0438\u0434\u0435 \u0434\u0435\u043B\u0438\u0432 \u0441\u043E ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D\u0438 \u043A\u043B\u0443\u0447\u0435\u0432\u0438" : "\u041D\u0435\u043F\u0440\u0435\u043F\u043E\u0437\u043D\u0430\u0435\u043D \u043A\u043B\u0443\u0447"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u043A\u043B\u0443\u0447 \u0432\u043E ${issue2.origin}`;
      case "invalid_union":
        return "\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441";
      case "invalid_element":
        return `\u0413\u0440\u0435\u0448\u043D\u0430 \u0432\u0440\u0435\u0434\u043D\u043E\u0441\u0442 \u0432\u043E ${issue2.origin}`;
      default:
        return `\u0413\u0440\u0435\u0448\u0435\u043D \u0432\u043D\u0435\u0441`;
    }
  };
};
function mk_default() {
  return {
    localeError: error27()
  };
}

// node_modules/zod/v4/locales/ms.js
var error28 = () => {
  const Sizable = {
    string: { unit: "aksara", verb: "mempunyai" },
    file: { unit: "bait", verb: "mempunyai" },
    array: { unit: "elemen", verb: "mempunyai" },
    set: { unit: "elemen", verb: "mempunyai" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "alamat e-mel",
    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: "tarikh masa ISO",
    date: "tarikh ISO",
    time: "masa ISO",
    duration: "tempoh ISO",
    ipv4: "alamat IPv4",
    ipv6: "alamat IPv6",
    cidrv4: "julat IPv4",
    cidrv6: "julat IPv6",
    base64: "string dikodkan base64",
    base64url: "string dikodkan base64url",
    json_string: "string JSON",
    e164: "nombor E.164",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "nombor"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Input tidak sah: dijangka instanceof ${issue2.expected}, diterima ${received}`;
        }
        return `Input tidak sah: dijangka ${expected}, diterima ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Input tidak sah: dijangka ${stringifyPrimitive(issue2.values[0])}`;
        return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Terlalu besar: dijangka ${(_c = issue2.origin) != null ? _c : "nilai"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elemen"}`;
        return `Terlalu besar: dijangka ${(_e = issue2.origin) != null ? _e : "nilai"} adalah ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Terlalu kecil: dijangka ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Terlalu kecil: dijangka ${issue2.origin} adalah ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `String tidak sah: mesti mengandungi "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`;
        return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} tidak sah`;
      }
      case "not_multiple_of":
        return `Nombor tidak sah: perlu gandaan ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Kunci tidak dikenali: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Kunci tidak sah dalam ${issue2.origin}`;
      case "invalid_union":
        return "Input tidak sah";
      case "invalid_element":
        return `Nilai tidak sah dalam ${issue2.origin}`;
      default:
        return `Input tidak sah`;
    }
  };
};
function ms_default() {
  return {
    localeError: error28()
  };
}

// node_modules/zod/v4/locales/nl.js
var error29 = () => {
  const Sizable = {
    string: { unit: "tekens", verb: "heeft" },
    file: { unit: "bytes", verb: "heeft" },
    array: { unit: "elementen", verb: "heeft" },
    set: { unit: "elementen", verb: "heeft" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "invoer",
    email: "emailadres",
    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 datum en tijd",
    date: "ISO datum",
    time: "ISO tijd",
    duration: "ISO duur",
    ipv4: "IPv4-adres",
    ipv6: "IPv6-adres",
    cidrv4: "IPv4-bereik",
    cidrv6: "IPv6-bereik",
    base64: "base64-gecodeerde tekst",
    base64url: "base64 URL-gecodeerde tekst",
    json_string: "JSON string",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "invoer"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "getal"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ongeldige invoer: verwacht instanceof ${issue2.expected}, ontving ${received}`;
        }
        return `Ongeldige invoer: verwacht ${expected}, ontving ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue2.values[0])}`;
        return `Ongeldige optie: verwacht \xE9\xE9n van ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        const longName = issue2.origin === "date" ? "laat" : issue2.origin === "string" ? "lang" : "groot";
        if (sizing)
          return `Te ${longName}: verwacht dat ${(_c = issue2.origin) != null ? _c : "waarde"} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elementen"} ${sizing.verb}`;
        return `Te ${longName}: verwacht dat ${(_e = issue2.origin) != null ? _e : "waarde"} ${adj}${issue2.maximum.toString()} is`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        const shortName = issue2.origin === "date" ? "vroeg" : issue2.origin === "string" ? "kort" : "klein";
        if (sizing) {
          return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Te ${shortName}: verwacht dat ${issue2.origin} ${adj}${issue2.minimum.toString()} is`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`;
        }
        if (_issue.format === "ends_with")
          return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`;
        if (_issue.format === "includes")
          return `Ongeldige tekst: moet "${_issue.includes}" bevatten`;
        if (_issue.format === "regex")
          return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`;
        return `Ongeldig: ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Ongeldig getal: moet een veelvoud van ${issue2.divisor} zijn`;
      case "unrecognized_keys":
        return `Onbekende key${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ongeldige key in ${issue2.origin}`;
      case "invalid_union":
        return "Ongeldige invoer";
      case "invalid_element":
        return `Ongeldige waarde in ${issue2.origin}`;
      default:
        return `Ongeldige invoer`;
    }
  };
};
function nl_default() {
  return {
    localeError: error29()
  };
}

// node_modules/zod/v4/locales/no.js
var error30 = () => {
  const Sizable = {
    string: { unit: "tegn", verb: "\xE5 ha" },
    file: { unit: "bytes", verb: "\xE5 ha" },
    array: { unit: "elementer", verb: "\xE5 inneholde" },
    set: { unit: "elementer", verb: "\xE5 inneholde" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "input",
    email: "e-postadresse",
    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 dato- og klokkeslett",
    date: "ISO-dato",
    time: "ISO-klokkeslett",
    duration: "ISO-varighet",
    ipv4: "IPv4-omr\xE5de",
    ipv6: "IPv6-omr\xE5de",
    cidrv4: "IPv4-spekter",
    cidrv6: "IPv6-spekter",
    base64: "base64-enkodet streng",
    base64url: "base64url-enkodet streng",
    json_string: "JSON-streng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "tall",
    array: "liste"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ugyldig input: forventet instanceof ${issue2.expected}, fikk ${received}`;
        }
        return `Ugyldig input: forventet ${expected}, fikk ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ugyldig verdi: forventet ${stringifyPrimitive(issue2.values[0])}`;
        return `Ugyldig valg: forventet en av ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `For stor(t): forventet ${(_c = issue2.origin) != null ? _c : "value"} til \xE5 ha ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elementer"}`;
        return `For stor(t): forventet ${(_e = issue2.origin) != null ? _e : "value"} til \xE5 ha ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `For lite(n): forventet ${issue2.origin} til \xE5 ha ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ugyldig streng: m\xE5 starte med "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Ugyldig streng: m\xE5 ende med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ugyldig streng: m\xE5 inneholde "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ugyldig streng: m\xE5 matche m\xF8nsteret ${_issue.pattern}`;
        return `Ugyldig ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Ugyldig tall: m\xE5 v\xE6re et multiplum av ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Ukjente n\xF8kler" : "Ukjent n\xF8kkel"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ugyldig n\xF8kkel i ${issue2.origin}`;
      case "invalid_union":
        return "Ugyldig input";
      case "invalid_element":
        return `Ugyldig verdi i ${issue2.origin}`;
      default:
        return `Ugyldig input`;
    }
  };
};
function no_default() {
  return {
    localeError: error30()
  };
}

// node_modules/zod/v4/locales/ota.js
var error31 = () => {
  const Sizable = {
    string: { unit: "harf", verb: "olmal\u0131d\u0131r" },
    file: { unit: "bayt", verb: "olmal\u0131d\u0131r" },
    array: { unit: "unsur", verb: "olmal\u0131d\u0131r" },
    set: { unit: "unsur", verb: "olmal\u0131d\u0131r" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "giren",
    email: "epostag\xE2h",
    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 heng\xE2m\u0131",
    date: "ISO tarihi",
    time: "ISO zaman\u0131",
    duration: "ISO m\xFCddeti",
    ipv4: "IPv4 ni\u015F\xE2n\u0131",
    ipv6: "IPv6 ni\u015F\xE2n\u0131",
    cidrv4: "IPv4 menzili",
    cidrv6: "IPv6 menzili",
    base64: "base64-\u015Fifreli metin",
    base64url: "base64url-\u015Fifreli metin",
    json_string: "JSON metin",
    e164: "E.164 say\u0131s\u0131",
    jwt: "JWT",
    template_literal: "giren"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "numara",
    array: "saf",
    null: "gayb"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `F\xE2sit giren: umulan instanceof ${issue2.expected}, al\u0131nan ${received}`;
        }
        return `F\xE2sit giren: umulan ${expected}, al\u0131nan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `F\xE2sit giren: umulan ${stringifyPrimitive(issue2.values[0])}`;
        return `F\xE2sit tercih: m\xFBteberler ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Fazla b\xFCy\xFCk: ${(_c = issue2.origin) != null ? _c : "value"}, ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elements"} sahip olmal\u0131yd\u0131.`;
        return `Fazla b\xFCy\xFCk: ${(_e = issue2.origin) != null ? _e : "value"}, ${adj}${issue2.maximum.toString()} olmal\u0131yd\u0131.`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} ${sizing.unit} sahip olmal\u0131yd\u0131.`;
        }
        return `Fazla k\xFC\xE7\xFCk: ${issue2.origin}, ${adj}${issue2.minimum.toString()} olmal\u0131yd\u0131.`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `F\xE2sit metin: "${_issue.prefix}" ile ba\u015Flamal\u0131.`;
        if (_issue.format === "ends_with")
          return `F\xE2sit metin: "${_issue.suffix}" ile bitmeli.`;
        if (_issue.format === "includes")
          return `F\xE2sit metin: "${_issue.includes}" ihtiv\xE2 etmeli.`;
        if (_issue.format === "regex")
          return `F\xE2sit metin: ${_issue.pattern} nak\u015F\u0131na uymal\u0131.`;
        return `F\xE2sit ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `F\xE2sit say\u0131: ${issue2.divisor} kat\u0131 olmal\u0131yd\u0131.`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar ${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} i\xE7in tan\u0131nmayan anahtar var.`;
      case "invalid_union":
        return "Giren tan\u0131namad\u0131.";
      case "invalid_element":
        return `${issue2.origin} i\xE7in tan\u0131nmayan k\u0131ymet var.`;
      default:
        return `K\u0131ymet tan\u0131namad\u0131.`;
    }
  };
};
function ota_default() {
  return {
    localeError: error31()
  };
}

// node_modules/zod/v4/locales/ps.js
var error32 = () => {
  const Sizable = {
    string: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
    file: { unit: "\u0628\u0627\u06CC\u067C\u0633", verb: "\u0648\u0644\u0631\u064A" },
    array: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" },
    set: { unit: "\u062A\u0648\u06A9\u064A", verb: "\u0648\u0644\u0631\u064A" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0648\u0631\u0648\u062F\u064A",
    email: "\u0628\u0631\u06CC\u069A\u0646\u0627\u0644\u06CC\u06A9",
    url: "\u06CC\u0648 \u0622\u0631 \u0627\u0644",
    emoji: "\u0627\u06CC\u0645\u0648\u062C\u064A",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u0646\u06CC\u067C\u0647 \u0627\u0648 \u0648\u062E\u062A",
    date: "\u0646\u06D0\u067C\u0647",
    time: "\u0648\u062E\u062A",
    duration: "\u0645\u0648\u062F\u0647",
    ipv4: "\u062F IPv4 \u067E\u062A\u0647",
    ipv6: "\u062F IPv6 \u067E\u062A\u0647",
    cidrv4: "\u062F IPv4 \u0633\u0627\u062D\u0647",
    cidrv6: "\u062F IPv6 \u0633\u0627\u062D\u0647",
    base64: "base64-encoded \u0645\u062A\u0646",
    base64url: "base64url-encoded \u0645\u062A\u0646",
    json_string: "JSON \u0645\u062A\u0646",
    e164: "\u062F E.164 \u0634\u0645\u06D0\u0631\u0647",
    jwt: "JWT",
    template_literal: "\u0648\u0631\u0648\u062F\u064A"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0639\u062F\u062F",
    array: "\u0627\u0631\u06D0"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F instanceof ${issue2.expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
        }
        return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${expected} \u0648\u0627\u06CC, \u0645\u06AB\u0631 ${received} \u062A\u0631\u0644\u0627\u0633\u0647 \u0634\u0648`;
      }
      case "invalid_value":
        if (issue2.values.length === 1) {
          return `\u0646\u0627\u0633\u0645 \u0648\u0631\u0648\u062F\u064A: \u0628\u0627\u06CC\u062F ${stringifyPrimitive(issue2.values[0])} \u0648\u0627\u06CC`;
        }
        return `\u0646\u0627\u0633\u0645 \u0627\u0646\u062A\u062E\u0627\u0628: \u0628\u0627\u06CC\u062F \u06CC\u0648 \u0644\u0647 ${joinValues(issue2.values, "|")} \u0685\u062E\u0647 \u0648\u0627\u06CC`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${(_c = issue2.origin) != null ? _c : "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u0639\u0646\u0635\u0631\u0648\u0646\u0647"} \u0648\u0644\u0631\u064A`;
        }
        return `\u0689\u06CC\u0631 \u0644\u0648\u06CC: ${(_e = issue2.origin) != null ? _e : "\u0627\u0631\u0632\u069A\u062A"} \u0628\u0627\u06CC\u062F ${adj}${issue2.maximum.toString()} \u0648\u064A`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0648\u0644\u0631\u064A`;
        }
        return `\u0689\u06CC\u0631 \u06A9\u0648\u0686\u0646\u06CC: ${issue2.origin} \u0628\u0627\u06CC\u062F ${adj}${issue2.minimum.toString()} \u0648\u064A`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.prefix}" \u0633\u0631\u0647 \u067E\u06CC\u0644 \u0634\u064A`;
        }
        if (_issue.format === "ends_with") {
          return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F "${_issue.suffix}" \u0633\u0631\u0647 \u067E\u0627\u06CC \u062A\u0647 \u0648\u0631\u0633\u064A\u0696\u064A`;
        }
        if (_issue.format === "includes") {
          return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F "${_issue.includes}" \u0648\u0644\u0631\u064A`;
        }
        if (_issue.format === "regex") {
          return `\u0646\u0627\u0633\u0645 \u0645\u062A\u0646: \u0628\u0627\u06CC\u062F \u062F ${_issue.pattern} \u0633\u0631\u0647 \u0645\u0637\u0627\u0628\u0642\u062A \u0648\u0644\u0631\u064A`;
        }
        return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} \u0646\u0627\u0633\u0645 \u062F\u06CC`;
      }
      case "not_multiple_of":
        return `\u0646\u0627\u0633\u0645 \u0639\u062F\u062F: \u0628\u0627\u06CC\u062F \u062F ${issue2.divisor} \u0645\u0636\u0631\u0628 \u0648\u064A`;
      case "unrecognized_keys":
        return `\u0646\u0627\u0633\u0645 ${issue2.keys.length > 1 ? "\u06A9\u0644\u06CC\u0689\u0648\u0646\u0647" : "\u06A9\u0644\u06CC\u0689"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u0646\u0627\u0633\u0645 \u06A9\u0644\u06CC\u0689 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
      case "invalid_union":
        return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
      case "invalid_element":
        return `\u0646\u0627\u0633\u0645 \u0639\u0646\u0635\u0631 \u067E\u0647 ${issue2.origin} \u06A9\u06D0`;
      default:
        return `\u0646\u0627\u0633\u0645\u0647 \u0648\u0631\u0648\u062F\u064A`;
    }
  };
};
function ps_default() {
  return {
    localeError: error32()
  };
}

// node_modules/zod/v4/locales/pl.js
var error33 = () => {
  const Sizable = {
    string: { unit: "znak\xF3w", verb: "mie\u0107" },
    file: { unit: "bajt\xF3w", verb: "mie\u0107" },
    array: { unit: "element\xF3w", verb: "mie\u0107" },
    set: { unit: "element\xF3w", verb: "mie\u0107" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "wyra\u017Cenie",
    email: "adres email",
    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: "data i godzina w formacie ISO",
    date: "data w formacie ISO",
    time: "godzina w formacie ISO",
    duration: "czas trwania ISO",
    ipv4: "adres IPv4",
    ipv6: "adres IPv6",
    cidrv4: "zakres IPv4",
    cidrv6: "zakres IPv6",
    base64: "ci\u0105g znak\xF3w zakodowany w formacie base64",
    base64url: "ci\u0105g znak\xF3w zakodowany w formacie base64url",
    json_string: "ci\u0105g znak\xF3w w formacie JSON",
    e164: "liczba E.164",
    jwt: "JWT",
    template_literal: "wej\u015Bcie"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "liczba",
    array: "tablica"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano instanceof ${issue2.expected}, otrzymano ${received}`;
        }
        return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${expected}, otrzymano ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Nieprawid\u0142owe dane wej\u015Bciowe: oczekiwano ${stringifyPrimitive(issue2.values[0])}`;
        return `Nieprawid\u0142owa opcja: oczekiwano jednej z warto\u015Bci ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Za du\u017Ca warto\u015B\u0107: oczekiwano, \u017Ce ${(_c = issue2.origin) != null ? _c : "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "element\xF3w"}`;
        }
        return `Zbyt du\u017C(y/a/e): oczekiwano, \u017Ce ${(_e = issue2.origin) != null ? _e : "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Za ma\u0142a warto\u015B\u0107: oczekiwano, \u017Ce ${(_f = issue2.origin) != null ? _f : "warto\u015B\u0107"} b\u0119dzie mie\u0107 ${adj}${issue2.minimum.toString()} ${(_g = sizing.unit) != null ? _g : "element\xF3w"}`;
        }
        return `Zbyt ma\u0142(y/a/e): oczekiwano, \u017Ce ${(_h = issue2.origin) != null ? _h : "warto\u015B\u0107"} b\u0119dzie wynosi\u0107 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zaczyna\u0107 si\u0119 od "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi ko\u0144czy\u0107 si\u0119 na "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi zawiera\u0107 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Nieprawid\u0142owy ci\u0105g znak\xF3w: musi odpowiada\u0107 wzorcowi ${_issue.pattern}`;
        return `Nieprawid\u0142ow(y/a/e) ${(_i = FormatDictionary[_issue.format]) != null ? _i : issue2.format}`;
      }
      case "not_multiple_of":
        return `Nieprawid\u0142owa liczba: musi by\u0107 wielokrotno\u015Bci\u0105 ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Nierozpoznane klucze${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Nieprawid\u0142owy klucz w ${issue2.origin}`;
      case "invalid_union":
        return "Nieprawid\u0142owe dane wej\u015Bciowe";
      case "invalid_element":
        return `Nieprawid\u0142owa warto\u015B\u0107 w ${issue2.origin}`;
      default:
        return `Nieprawid\u0142owe dane wej\u015Bciowe`;
    }
  };
};
function pl_default() {
  return {
    localeError: error33()
  };
}

// node_modules/zod/v4/locales/pt.js
var error34 = () => {
  const Sizable = {
    string: { unit: "caracteres", verb: "ter" },
    file: { unit: "bytes", verb: "ter" },
    array: { unit: "itens", verb: "ter" },
    set: { unit: "itens", verb: "ter" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "padr\xE3o",
    email: "endere\xE7o de e-mail",
    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: "data e hora ISO",
    date: "data ISO",
    time: "hora ISO",
    duration: "dura\xE7\xE3o ISO",
    ipv4: "endere\xE7o IPv4",
    ipv6: "endere\xE7o IPv6",
    cidrv4: "faixa de IPv4",
    cidrv6: "faixa de IPv6",
    base64: "texto codificado em base64",
    base64url: "URL codificada em base64",
    json_string: "texto JSON",
    e164: "n\xFAmero E.164",
    jwt: "JWT",
    template_literal: "entrada"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "n\xFAmero",
    null: "nulo"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Tipo inv\xE1lido: esperado instanceof ${issue2.expected}, recebido ${received}`;
        }
        return `Tipo inv\xE1lido: esperado ${expected}, recebido ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Entrada inv\xE1lida: esperado ${stringifyPrimitive(issue2.values[0])}`;
        return `Op\xE7\xE3o inv\xE1lida: esperada uma das ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Muito grande: esperado que ${(_c = issue2.origin) != null ? _c : "valor"} tivesse ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elementos"}`;
        return `Muito grande: esperado que ${(_e = issue2.origin) != null ? _e : "valor"} fosse ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Muito pequeno: esperado que ${issue2.origin} tivesse ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Muito pequeno: esperado que ${issue2.origin} fosse ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Texto inv\xE1lido: deve come\xE7ar com "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Texto inv\xE1lido: deve terminar com "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Texto inv\xE1lido: deve incluir "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Texto inv\xE1lido: deve corresponder ao padr\xE3o ${_issue.pattern}`;
        return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} inv\xE1lido`;
      }
      case "not_multiple_of":
        return `N\xFAmero inv\xE1lido: deve ser m\xFAltiplo de ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Chave${issue2.keys.length > 1 ? "s" : ""} desconhecida${issue2.keys.length > 1 ? "s" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Chave inv\xE1lida em ${issue2.origin}`;
      case "invalid_union":
        return "Entrada inv\xE1lida";
      case "invalid_element":
        return `Valor inv\xE1lido em ${issue2.origin}`;
      default:
        return `Campo inv\xE1lido`;
    }
  };
};
function pt_default2() {
  return {
    localeError: error34()
  };
}

// node_modules/zod/v4/locales/ru.js
function getRussianPlural(count, one, few, many) {
  const absCount = Math.abs(count);
  const lastDigit = absCount % 10;
  const lastTwoDigits = absCount % 100;
  if (lastTwoDigits >= 11 && lastTwoDigits <= 19) {
    return many;
  }
  if (lastDigit === 1) {
    return one;
  }
  if (lastDigit >= 2 && lastDigit <= 4) {
    return few;
  }
  return many;
}
var error35 = () => {
  const Sizable = {
    string: {
      unit: {
        one: "\u0441\u0438\u043C\u0432\u043E\u043B",
        few: "\u0441\u0438\u043C\u0432\u043E\u043B\u0430",
        many: "\u0441\u0438\u043C\u0432\u043E\u043B\u043E\u0432"
      },
      verb: "\u0438\u043C\u0435\u0442\u044C"
    },
    file: {
      unit: {
        one: "\u0431\u0430\u0439\u0442",
        few: "\u0431\u0430\u0439\u0442\u0430",
        many: "\u0431\u0430\u0439\u0442"
      },
      verb: "\u0438\u043C\u0435\u0442\u044C"
    },
    array: {
      unit: {
        one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
        few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
        many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
      },
      verb: "\u0438\u043C\u0435\u0442\u044C"
    },
    set: {
      unit: {
        one: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442",
        few: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430",
        many: "\u044D\u043B\u0435\u043C\u0435\u043D\u0442\u043E\u0432"
      },
      verb: "\u0438\u043C\u0435\u0442\u044C"
    }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0432\u0432\u043E\u0434",
    email: "email \u0430\u0434\u0440\u0435\u0441",
    url: "URL",
    emoji: "\u044D\u043C\u043E\u0434\u0437\u0438",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO \u0434\u0430\u0442\u0430 \u0438 \u0432\u0440\u0435\u043C\u044F",
    date: "ISO \u0434\u0430\u0442\u0430",
    time: "ISO \u0432\u0440\u0435\u043C\u044F",
    duration: "ISO \u0434\u043B\u0438\u0442\u0435\u043B\u044C\u043D\u043E\u0441\u0442\u044C",
    ipv4: "IPv4 \u0430\u0434\u0440\u0435\u0441",
    ipv6: "IPv6 \u0430\u0434\u0440\u0435\u0441",
    cidrv4: "IPv4 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    cidrv6: "IPv6 \u0434\u0438\u0430\u043F\u0430\u0437\u043E\u043D",
    base64: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64",
    base64url: "\u0441\u0442\u0440\u043E\u043A\u0430 \u0432 \u0444\u043E\u0440\u043C\u0430\u0442\u0435 base64url",
    json_string: "JSON \u0441\u0442\u0440\u043E\u043A\u0430",
    e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
    jwt: "JWT",
    template_literal: "\u0432\u0432\u043E\u0434"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0447\u0438\u0441\u043B\u043E",
    array: "\u043C\u0430\u0441\u0441\u0438\u0432"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C instanceof ${issue2.expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;
        }
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${expected}, \u043F\u043E\u043B\u0443\u0447\u0435\u043D\u043E ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0432\u043E\u0434: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u0432\u0430\u0440\u0438\u0430\u043D\u0442: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C \u043E\u0434\u043D\u043E \u0438\u0437 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const maxValue = Number(issue2.maximum);
          const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${(_c = issue2.origin) != null ? _c : "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.maximum.toString()} ${unit}`;
        }
        return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u0431\u043E\u043B\u044C\u0448\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${(_d2 = issue2.origin) != null ? _d2 : "\u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435"} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          const minValue = Number(issue2.minimum);
          const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many);
          return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 \u0438\u043C\u0435\u0442\u044C ${adj}${issue2.minimum.toString()} ${unit}`;
        }
        return `\u0421\u043B\u0438\u0448\u043A\u043E\u043C \u043C\u0430\u043B\u0435\u043D\u044C\u043A\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435: \u043E\u0436\u0438\u0434\u0430\u043B\u043E\u0441\u044C, \u0447\u0442\u043E ${issue2.origin} \u0431\u0443\u0434\u0435\u0442 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u043D\u0430\u0447\u0438\u043D\u0430\u0442\u044C\u0441\u044F \u0441 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0437\u0430\u043A\u0430\u043D\u0447\u0438\u0432\u0430\u0442\u044C\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u0434\u0435\u0440\u0436\u0430\u0442\u044C "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u0432\u0435\u0440\u043D\u0430\u044F \u0441\u0442\u0440\u043E\u043A\u0430: \u0434\u043E\u043B\u0436\u043D\u0430 \u0441\u043E\u043E\u0442\u0432\u0435\u0442\u0441\u0442\u0432\u043E\u0432\u0430\u0442\u044C \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0447\u0438\u0441\u043B\u043E: \u0434\u043E\u043B\u0436\u043D\u043E \u0431\u044B\u0442\u044C \u043A\u0440\u0430\u0442\u043D\u044B\u043C ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u0430\u0441\u043F\u043E\u0437\u043D\u0430\u043D\u043D${issue2.keys.length > 1 ? "\u044B\u0435" : "\u044B\u0439"} \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0438" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0439 \u043A\u043B\u044E\u0447 \u0432 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435";
      case "invalid_element":
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u043E\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435 \u0432 ${issue2.origin}`;
      default:
        return `\u041D\u0435\u0432\u0435\u0440\u043D\u044B\u0435 \u0432\u0445\u043E\u0434\u043D\u044B\u0435 \u0434\u0430\u043D\u043D\u044B\u0435`;
    }
  };
};
function ru_default2() {
  return {
    localeError: error35()
  };
}

// node_modules/zod/v4/locales/sl.js
var error36 = () => {
  const Sizable = {
    string: { unit: "znakov", verb: "imeti" },
    file: { unit: "bajtov", verb: "imeti" },
    array: { unit: "elementov", verb: "imeti" },
    set: { unit: "elementov", verb: "imeti" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "vnos",
    email: "e-po\u0161tni naslov",
    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 datum in \u010Das",
    date: "ISO datum",
    time: "ISO \u010Das",
    duration: "ISO trajanje",
    ipv4: "IPv4 naslov",
    ipv6: "IPv6 naslov",
    cidrv4: "obseg IPv4",
    cidrv6: "obseg IPv6",
    base64: "base64 kodiran niz",
    base64url: "base64url kodiran niz",
    json_string: "JSON niz",
    e164: "E.164 \u0161tevilka",
    jwt: "JWT",
    template_literal: "vnos"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0161tevilo",
    array: "tabela"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Neveljaven vnos: pri\u010Dakovano instanceof ${issue2.expected}, prejeto ${received}`;
        }
        return `Neveljaven vnos: pri\u010Dakovano ${expected}, prejeto ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Neveljaven vnos: pri\u010Dakovano ${stringifyPrimitive(issue2.values[0])}`;
        return `Neveljavna mo\u017Enost: pri\u010Dakovano eno izmed ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Preveliko: pri\u010Dakovano, da bo ${(_c = issue2.origin) != null ? _c : "vrednost"} imelo ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "elementov"}`;
        return `Preveliko: pri\u010Dakovano, da bo ${(_e = issue2.origin) != null ? _e : "vrednost"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} imelo ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Premajhno: pri\u010Dakovano, da bo ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Neveljaven niz: mora se za\u010Deti z "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Neveljaven niz: mora se kon\u010Dati z "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Neveljaven niz: mora vsebovati "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`;
        return `Neveljaven ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Neveljavno \u0161tevilo: mora biti ve\u010Dkratnik ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Neprepoznan${issue2.keys.length > 1 ? "i klju\u010Di" : " klju\u010D"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Neveljaven klju\u010D v ${issue2.origin}`;
      case "invalid_union":
        return "Neveljaven vnos";
      case "invalid_element":
        return `Neveljavna vrednost v ${issue2.origin}`;
      default:
        return "Neveljaven vnos";
    }
  };
};
function sl_default() {
  return {
    localeError: error36()
  };
}

// node_modules/zod/v4/locales/sv.js
var error37 = () => {
  const Sizable = {
    string: { unit: "tecken", verb: "att ha" },
    file: { unit: "bytes", verb: "att ha" },
    array: { unit: "objekt", verb: "att inneh\xE5lla" },
    set: { unit: "objekt", verb: "att inneh\xE5lla" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "regulj\xE4rt uttryck",
    email: "e-postadress",
    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-datum och tid",
    date: "ISO-datum",
    time: "ISO-tid",
    duration: "ISO-varaktighet",
    ipv4: "IPv4-intervall",
    ipv6: "IPv6-intervall",
    cidrv4: "IPv4-spektrum",
    cidrv6: "IPv6-spektrum",
    base64: "base64-kodad str\xE4ng",
    base64url: "base64url-kodad str\xE4ng",
    json_string: "JSON-str\xE4ng",
    e164: "E.164-nummer",
    jwt: "JWT",
    template_literal: "mall-literal"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "antal",
    array: "lista"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ogiltig inmatning: f\xF6rv\xE4ntat instanceof ${issue2.expected}, fick ${received}`;
        }
        return `Ogiltig inmatning: f\xF6rv\xE4ntat ${expected}, fick ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ogiltig inmatning: f\xF6rv\xE4ntat ${stringifyPrimitive(issue2.values[0])}`;
        return `Ogiltigt val: f\xF6rv\xE4ntade en av ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `F\xF6r stor(t): f\xF6rv\xE4ntade ${(_c = issue2.origin) != null ? _c : "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "element"}`;
        }
        return `F\xF6r stor(t): f\xF6rv\xE4ntat ${(_e = issue2.origin) != null ? _e : "v\xE4rdet"} att ha ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `F\xF6r lite(t): f\xF6rv\xE4ntade ${(_f = issue2.origin) != null ? _f : "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `F\xF6r lite(t): f\xF6rv\xE4ntade ${(_g = issue2.origin) != null ? _g : "v\xE4rdet"} att ha ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `Ogiltig str\xE4ng: m\xE5ste b\xF6rja med "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `Ogiltig str\xE4ng: m\xE5ste sluta med "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Ogiltig str\xE4ng: m\xE5ste inneh\xE5lla "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Ogiltig str\xE4ng: m\xE5ste matcha m\xF6nstret "${_issue.pattern}"`;
        return `Ogiltig(t) ${(_h = FormatDictionary[_issue.format]) != null ? _h : issue2.format}`;
      }
      case "not_multiple_of":
        return `Ogiltigt tal: m\xE5ste vara en multipel av ${issue2.divisor}`;
      case "unrecognized_keys":
        return `${issue2.keys.length > 1 ? "Ok\xE4nda nycklar" : "Ok\xE4nd nyckel"}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Ogiltig nyckel i ${(_i = issue2.origin) != null ? _i : "v\xE4rdet"}`;
      case "invalid_union":
        return "Ogiltig input";
      case "invalid_element":
        return `Ogiltigt v\xE4rde i ${(_j2 = issue2.origin) != null ? _j2 : "v\xE4rdet"}`;
      default:
        return `Ogiltig input`;
    }
  };
};
function sv_default() {
  return {
    localeError: error37()
  };
}

// node_modules/zod/v4/locales/ta.js
var error38 = () => {
  const Sizable = {
    string: { unit: "\u0B8E\u0BB4\u0BC1\u0BA4\u0BCD\u0BA4\u0BC1\u0B95\u0BCD\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
    file: { unit: "\u0BAA\u0BC8\u0B9F\u0BCD\u0B9F\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
    array: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" },
    set: { unit: "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD", verb: "\u0B95\u0BCA\u0BA3\u0BCD\u0B9F\u0BBF\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1",
    email: "\u0BAE\u0BBF\u0BA9\u0BCD\u0BA9\u0B9E\u0BCD\u0B9A\u0BB2\u0BCD \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
    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 \u0BA4\u0BC7\u0BA4\u0BBF \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
    date: "ISO \u0BA4\u0BC7\u0BA4\u0BBF",
    time: "ISO \u0BA8\u0BC7\u0BB0\u0BAE\u0BCD",
    duration: "ISO \u0B95\u0BBE\u0BB2 \u0B85\u0BB3\u0BB5\u0BC1",
    ipv4: "IPv4 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
    ipv6: "IPv6 \u0BAE\u0BC1\u0B95\u0BB5\u0BB0\u0BBF",
    cidrv4: "IPv4 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
    cidrv6: "IPv6 \u0BB5\u0BB0\u0BAE\u0BCD\u0BAA\u0BC1",
    base64: "base64-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
    base64url: "base64url-encoded \u0B9A\u0BB0\u0BAE\u0BCD",
    json_string: "JSON \u0B9A\u0BB0\u0BAE\u0BCD",
    e164: "E.164 \u0B8E\u0BA3\u0BCD",
    jwt: "JWT",
    template_literal: "input"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0B8E\u0BA3\u0BCD",
    array: "\u0B85\u0BA3\u0BBF",
    null: "\u0BB5\u0BC6\u0BB1\u0BC1\u0BAE\u0BC8"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 instanceof ${issue2.expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;
        }
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${expected}, \u0BAA\u0BC6\u0BB1\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0BB0\u0BC1\u0BAA\u0BCD\u0BAA\u0BAE\u0BCD: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${joinValues(issue2.values, "|")} \u0B87\u0BB2\u0BCD \u0B92\u0BA9\u0BCD\u0BB1\u0BC1`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${(_c = issue2.origin) != null ? _c : "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u0B89\u0BB1\u0BC1\u0BAA\u0BCD\u0BAA\u0BC1\u0B95\u0BB3\u0BCD"} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        }
        return `\u0BAE\u0BBF\u0B95 \u0BAA\u0BC6\u0BB0\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${(_e = issue2.origin) != null ? _e : "\u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1"} ${adj}${issue2.maximum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        }
        return `\u0BAE\u0BBF\u0B95\u0B9A\u0BCD \u0B9A\u0BBF\u0BB1\u0BBF\u0BAF\u0BA4\u0BC1: \u0B8E\u0BA4\u0BBF\u0BB0\u0BCD\u0BAA\u0BBE\u0BB0\u0BCD\u0B95\u0BCD\u0B95\u0BAA\u0BCD\u0BAA\u0B9F\u0BCD\u0B9F\u0BA4\u0BC1 ${issue2.origin} ${adj}${issue2.minimum.toString()} \u0B86\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.prefix}" \u0B87\u0BB2\u0BCD \u0BA4\u0BCA\u0B9F\u0B99\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (_issue.format === "ends_with")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.suffix}" \u0B87\u0BB2\u0BCD \u0BAE\u0BC1\u0B9F\u0BBF\u0BB5\u0B9F\u0BC8\u0BAF \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (_issue.format === "includes")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: "${_issue.includes}" \u0B90 \u0B89\u0BB3\u0BCD\u0BB3\u0B9F\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        if (_issue.format === "regex")
          return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B9A\u0BB0\u0BAE\u0BCD: ${_issue.pattern} \u0BAE\u0BC1\u0BB1\u0BC8\u0BAA\u0BBE\u0B9F\u0BCD\u0B9F\u0BC1\u0B9F\u0BA9\u0BCD \u0BAA\u0BCA\u0BB0\u0BC1\u0BA8\u0BCD\u0BA4 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B8E\u0BA3\u0BCD: ${issue2.divisor} \u0B87\u0BA9\u0BCD \u0BAA\u0BB2\u0BAE\u0BBE\u0B95 \u0B87\u0BB0\u0BC1\u0B95\u0BCD\u0B95 \u0BB5\u0BC7\u0BA3\u0BCD\u0B9F\u0BC1\u0BAE\u0BCD`;
      case "unrecognized_keys":
        return `\u0B85\u0B9F\u0BC8\u0BAF\u0BBE\u0BB3\u0BAE\u0BCD \u0BA4\u0BC6\u0BB0\u0BBF\u0BAF\u0BBE\u0BA4 \u0BB5\u0BBF\u0B9A\u0BC8${issue2.keys.length > 1 ? "\u0B95\u0BB3\u0BCD" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BB5\u0BBF\u0B9A\u0BC8`;
      case "invalid_union":
        return "\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1";
      case "invalid_element":
        return `${issue2.origin} \u0B87\u0BB2\u0BCD \u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0BAE\u0BA4\u0BBF\u0BAA\u0BCD\u0BAA\u0BC1`;
      default:
        return `\u0BA4\u0BB5\u0BB1\u0BBE\u0BA9 \u0B89\u0BB3\u0BCD\u0BB3\u0BC0\u0B9F\u0BC1`;
    }
  };
};
function ta_default() {
  return {
    localeError: error38()
  };
}

// node_modules/zod/v4/locales/th.js
var error39 = () => {
  const Sizable = {
    string: { unit: "\u0E15\u0E31\u0E27\u0E2D\u0E31\u0E01\u0E29\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
    file: { unit: "\u0E44\u0E1A\u0E15\u0E4C", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
    array: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" },
    set: { unit: "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23", verb: "\u0E04\u0E27\u0E23\u0E21\u0E35" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19",
    email: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48\u0E2D\u0E35\u0E40\u0E21\u0E25",
    url: "URL",
    emoji: "\u0E2D\u0E34\u0E42\u0E21\u0E08\u0E34",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
    date: "\u0E27\u0E31\u0E19\u0E17\u0E35\u0E48\u0E41\u0E1A\u0E1A ISO",
    time: "\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
    duration: "\u0E0A\u0E48\u0E27\u0E07\u0E40\u0E27\u0E25\u0E32\u0E41\u0E1A\u0E1A ISO",
    ipv4: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv4",
    ipv6: "\u0E17\u0E35\u0E48\u0E2D\u0E22\u0E39\u0E48 IPv6",
    cidrv4: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv4",
    cidrv6: "\u0E0A\u0E48\u0E27\u0E07 IP \u0E41\u0E1A\u0E1A IPv6",
    base64: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64",
    base64url: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A Base64 \u0E2A\u0E33\u0E2B\u0E23\u0E31\u0E1A URL",
    json_string: "\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E41\u0E1A\u0E1A JSON",
    e164: "\u0E40\u0E1A\u0E2D\u0E23\u0E4C\u0E42\u0E17\u0E23\u0E28\u0E31\u0E1E\u0E17\u0E4C\u0E23\u0E30\u0E2B\u0E27\u0E48\u0E32\u0E07\u0E1B\u0E23\u0E30\u0E40\u0E17\u0E28 (E.164)",
    jwt: "\u0E42\u0E17\u0E40\u0E04\u0E19 JWT",
    template_literal: "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E17\u0E35\u0E48\u0E1B\u0E49\u0E2D\u0E19"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02",
    array: "\u0E2D\u0E32\u0E23\u0E4C\u0E40\u0E23\u0E22\u0E4C (Array)",
    null: "\u0E44\u0E21\u0E48\u0E21\u0E35\u0E04\u0E48\u0E32 (null)"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 instanceof ${issue2.expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;
        }
        return `\u0E1B\u0E23\u0E30\u0E40\u0E20\u0E17\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${expected} \u0E41\u0E15\u0E48\u0E44\u0E14\u0E49\u0E23\u0E31\u0E1A ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0E04\u0E48\u0E32\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19 ${stringifyPrimitive(issue2.values[0])}`;
        return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E37\u0E2D\u0E01\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E04\u0E27\u0E23\u0E40\u0E1B\u0E47\u0E19\u0E2B\u0E19\u0E36\u0E48\u0E07\u0E43\u0E19 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "\u0E44\u0E21\u0E48\u0E40\u0E01\u0E34\u0E19" : "\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${(_c = issue2.origin) != null ? _c : "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u0E23\u0E32\u0E22\u0E01\u0E32\u0E23"}`;
        return `\u0E40\u0E01\u0E34\u0E19\u0E01\u0E33\u0E2B\u0E19\u0E14: ${(_e = issue2.origin) != null ? _e : "\u0E04\u0E48\u0E32"} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? "\u0E2D\u0E22\u0E48\u0E32\u0E07\u0E19\u0E49\u0E2D\u0E22" : "\u0E21\u0E32\u0E01\u0E01\u0E27\u0E48\u0E32";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0E19\u0E49\u0E2D\u0E22\u0E01\u0E27\u0E48\u0E32\u0E01\u0E33\u0E2B\u0E19\u0E14: ${issue2.origin} \u0E04\u0E27\u0E23\u0E21\u0E35${adj} ${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E02\u0E36\u0E49\u0E19\u0E15\u0E49\u0E19\u0E14\u0E49\u0E27\u0E22 "${_issue.prefix}"`;
        }
        if (_issue.format === "ends_with")
          return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E25\u0E07\u0E17\u0E49\u0E32\u0E22\u0E14\u0E49\u0E27\u0E22 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21\u0E15\u0E49\u0E2D\u0E07\u0E21\u0E35 "${_issue.includes}" \u0E2D\u0E22\u0E39\u0E48\u0E43\u0E19\u0E02\u0E49\u0E2D\u0E04\u0E27\u0E32\u0E21`;
        if (_issue.format === "regex")
          return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14 ${_issue.pattern}`;
        return `\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u0E15\u0E31\u0E27\u0E40\u0E25\u0E02\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E15\u0E49\u0E2D\u0E07\u0E40\u0E1B\u0E47\u0E19\u0E08\u0E33\u0E19\u0E27\u0E19\u0E17\u0E35\u0E48\u0E2B\u0E32\u0E23\u0E14\u0E49\u0E27\u0E22 ${issue2.divisor} \u0E44\u0E14\u0E49\u0E25\u0E07\u0E15\u0E31\u0E27`;
      case "unrecognized_keys":
        return `\u0E1E\u0E1A\u0E04\u0E35\u0E22\u0E4C\u0E17\u0E35\u0E48\u0E44\u0E21\u0E48\u0E23\u0E39\u0E49\u0E08\u0E31\u0E01: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u0E04\u0E35\u0E22\u0E4C\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
      case "invalid_union":
        return "\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07: \u0E44\u0E21\u0E48\u0E15\u0E23\u0E07\u0E01\u0E31\u0E1A\u0E23\u0E39\u0E1B\u0E41\u0E1A\u0E1A\u0E22\u0E39\u0E40\u0E19\u0E35\u0E22\u0E19\u0E17\u0E35\u0E48\u0E01\u0E33\u0E2B\u0E19\u0E14\u0E44\u0E27\u0E49";
      case "invalid_element":
        return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07\u0E43\u0E19 ${issue2.origin}`;
      default:
        return `\u0E02\u0E49\u0E2D\u0E21\u0E39\u0E25\u0E44\u0E21\u0E48\u0E16\u0E39\u0E01\u0E15\u0E49\u0E2D\u0E07`;
    }
  };
};
function th_default() {
  return {
    localeError: error39()
  };
}

// node_modules/zod/v4/locales/tr.js
var error40 = () => {
  const Sizable = {
    string: { unit: "karakter", verb: "olmal\u0131" },
    file: { unit: "bayt", verb: "olmal\u0131" },
    array: { unit: "\xF6\u011Fe", verb: "olmal\u0131" },
    set: { unit: "\xF6\u011Fe", verb: "olmal\u0131" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "girdi",
    email: "e-posta adresi",
    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 tarih ve saat",
    date: "ISO tarih",
    time: "ISO saat",
    duration: "ISO s\xFCre",
    ipv4: "IPv4 adresi",
    ipv6: "IPv6 adresi",
    cidrv4: "IPv4 aral\u0131\u011F\u0131",
    cidrv6: "IPv6 aral\u0131\u011F\u0131",
    base64: "base64 ile \u015Fifrelenmi\u015F metin",
    base64url: "base64url ile \u015Fifrelenmi\u015F metin",
    json_string: "JSON dizesi",
    e164: "E.164 say\u0131s\u0131",
    jwt: "JWT",
    template_literal: "\u015Eablon dizesi"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Ge\xE7ersiz de\u011Fer: beklenen instanceof ${issue2.expected}, al\u0131nan ${received}`;
        }
        return `Ge\xE7ersiz de\u011Fer: beklenen ${expected}, al\u0131nan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Ge\xE7ersiz de\u011Fer: beklenen ${stringifyPrimitive(issue2.values[0])}`;
        return `Ge\xE7ersiz se\xE7enek: a\u015Fa\u011F\u0131dakilerden biri olmal\u0131: ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ok b\xFCy\xFCk: beklenen ${(_c = issue2.origin) != null ? _c : "de\u011Fer"} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\xF6\u011Fe"}`;
        return `\xC7ok b\xFCy\xFCk: beklenen ${(_e = issue2.origin) != null ? _e : "de\u011Fer"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        return `\xC7ok k\xFC\xE7\xFCk: beklenen ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Ge\xE7ersiz metin: "${_issue.prefix}" ile ba\u015Flamal\u0131`;
        if (_issue.format === "ends_with")
          return `Ge\xE7ersiz metin: "${_issue.suffix}" ile bitmeli`;
        if (_issue.format === "includes")
          return `Ge\xE7ersiz metin: "${_issue.includes}" i\xE7ermeli`;
        if (_issue.format === "regex")
          return `Ge\xE7ersiz metin: ${_issue.pattern} desenine uymal\u0131`;
        return `Ge\xE7ersiz ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `Ge\xE7ersiz say\u0131: ${issue2.divisor} ile tam b\xF6l\xFCnebilmeli`;
      case "unrecognized_keys":
        return `Tan\u0131nmayan anahtar${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} i\xE7inde ge\xE7ersiz anahtar`;
      case "invalid_union":
        return "Ge\xE7ersiz de\u011Fer";
      case "invalid_element":
        return `${issue2.origin} i\xE7inde ge\xE7ersiz de\u011Fer`;
      default:
        return `Ge\xE7ersiz de\u011Fer`;
    }
  };
};
function tr_default() {
  return {
    localeError: error40()
  };
}

// node_modules/zod/v4/locales/uk.js
var error41 = () => {
  const Sizable = {
    string: { unit: "\u0441\u0438\u043C\u0432\u043E\u043B\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
    file: { unit: "\u0431\u0430\u0439\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
    array: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" },
    set: { unit: "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432", verb: "\u043C\u0430\u0442\u0438\u043C\u0435" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456",
    email: "\u0430\u0434\u0440\u0435\u0441\u0430 \u0435\u043B\u0435\u043A\u0442\u0440\u043E\u043D\u043D\u043E\u0457 \u043F\u043E\u0448\u0442\u0438",
    url: "URL",
    emoji: "\u0435\u043C\u043E\u0434\u0437\u0456",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "\u0434\u0430\u0442\u0430 \u0442\u0430 \u0447\u0430\u0441 ISO",
    date: "\u0434\u0430\u0442\u0430 ISO",
    time: "\u0447\u0430\u0441 ISO",
    duration: "\u0442\u0440\u0438\u0432\u0430\u043B\u0456\u0441\u0442\u044C ISO",
    ipv4: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv4",
    ipv6: "\u0430\u0434\u0440\u0435\u0441\u0430 IPv6",
    cidrv4: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv4",
    cidrv6: "\u0434\u0456\u0430\u043F\u0430\u0437\u043E\u043D IPv6",
    base64: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64",
    base64url: "\u0440\u044F\u0434\u043E\u043A \u0443 \u043A\u043E\u0434\u0443\u0432\u0430\u043D\u043D\u0456 base64url",
    json_string: "\u0440\u044F\u0434\u043E\u043A JSON",
    e164: "\u043D\u043E\u043C\u0435\u0440 E.164",
    jwt: "JWT",
    template_literal: "\u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0447\u0438\u0441\u043B\u043E",
    array: "\u043C\u0430\u0441\u0438\u0432"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F instanceof ${issue2.expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;
        }
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${expected}, \u043E\u0442\u0440\u0438\u043C\u0430\u043D\u043E ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F ${stringifyPrimitive(issue2.values[0])}`;
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0430 \u043E\u043F\u0446\u0456\u044F: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F \u043E\u0434\u043D\u0435 \u0437 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${(_c = issue2.origin) != null ? _c : "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u0435\u043B\u0435\u043C\u0435\u043D\u0442\u0456\u0432"}`;
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u0432\u0435\u043B\u0438\u043A\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${(_e = issue2.origin) != null ? _e : "\u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F"} \u0431\u0443\u0434\u0435 ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u0417\u0430\u043D\u0430\u0434\u0442\u043E \u043C\u0430\u043B\u0435: \u043E\u0447\u0456\u043A\u0443\u0454\u0442\u044C\u0441\u044F, \u0449\u043E ${issue2.origin} \u0431\u0443\u0434\u0435 ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043F\u043E\u0447\u0438\u043D\u0430\u0442\u0438\u0441\u044F \u0437 "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0437\u0430\u043A\u0456\u043D\u0447\u0443\u0432\u0430\u0442\u0438\u0441\u044F \u043D\u0430 "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u043C\u0456\u0441\u0442\u0438\u0442\u0438 "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u0440\u044F\u0434\u043E\u043A: \u043F\u043E\u0432\u0438\u043D\u0435\u043D \u0432\u0456\u0434\u043F\u043E\u0432\u0456\u0434\u0430\u0442\u0438 \u0448\u0430\u0431\u043B\u043E\u043D\u0443 ${_issue.pattern}`;
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0447\u0438\u0441\u043B\u043E: \u043F\u043E\u0432\u0438\u043D\u043D\u043E \u0431\u0443\u0442\u0438 \u043A\u0440\u0430\u0442\u043D\u0438\u043C ${issue2.divisor}`;
      case "unrecognized_keys":
        return `\u041D\u0435\u0440\u043E\u0437\u043F\u0456\u0437\u043D\u0430\u043D\u0438\u0439 \u043A\u043B\u044E\u0447${issue2.keys.length > 1 ? "\u0456" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0438\u0439 \u043A\u043B\u044E\u0447 \u0443 ${issue2.origin}`;
      case "invalid_union":
        return "\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456";
      case "invalid_element":
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0435 \u0437\u043D\u0430\u0447\u0435\u043D\u043D\u044F \u0443 ${issue2.origin}`;
      default:
        return `\u041D\u0435\u043F\u0440\u0430\u0432\u0438\u043B\u044C\u043D\u0456 \u0432\u0445\u0456\u0434\u043D\u0456 \u0434\u0430\u043D\u0456`;
    }
  };
};
function uk_default() {
  return {
    localeError: error41()
  };
}

// node_modules/zod/v4/locales/ua.js
function ua_default() {
  return uk_default();
}

// node_modules/zod/v4/locales/ur.js
var error42 = () => {
  const Sizable = {
    string: { unit: "\u062D\u0631\u0648\u0641", verb: "\u06C1\u0648\u0646\u0627" },
    file: { unit: "\u0628\u0627\u0626\u0679\u0633", verb: "\u06C1\u0648\u0646\u0627" },
    array: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" },
    set: { unit: "\u0622\u0626\u0679\u0645\u0632", verb: "\u06C1\u0648\u0646\u0627" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0627\u0646 \u067E\u0679",
    email: "\u0627\u06CC \u0645\u06CC\u0644 \u0627\u06CC\u0688\u0631\u06CC\u0633",
    url: "\u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644",
    emoji: "\u0627\u06CC\u0645\u0648\u062C\u06CC",
    uuid: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    uuidv4: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 4",
    uuidv6: "\u06CC\u0648 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC \u0648\u06CC 6",
    nanoid: "\u0646\u06CC\u0646\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    guid: "\u062C\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    cuid: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    cuid2: "\u0633\u06CC \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC 2",
    ulid: "\u06CC\u0648 \u0627\u06CC\u0644 \u0622\u0626\u06CC \u0688\u06CC",
    xid: "\u0627\u06CC\u06A9\u0633 \u0622\u0626\u06CC \u0688\u06CC",
    ksuid: "\u06A9\u06D2 \u0627\u06CC\u0633 \u06CC\u0648 \u0622\u0626\u06CC \u0688\u06CC",
    datetime: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0688\u06CC\u0679 \u0679\u0627\u0626\u0645",
    date: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u062A\u0627\u0631\u06CC\u062E",
    time: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0648\u0642\u062A",
    duration: "\u0622\u0626\u06CC \u0627\u06CC\u0633 \u0627\u0648 \u0645\u062F\u062A",
    ipv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0627\u06CC\u0688\u0631\u06CC\u0633",
    ipv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0627\u06CC\u0688\u0631\u06CC\u0633",
    cidrv4: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 4 \u0631\u06CC\u0646\u062C",
    cidrv6: "\u0622\u0626\u06CC \u067E\u06CC \u0648\u06CC 6 \u0631\u06CC\u0646\u062C",
    base64: "\u0628\u06CC\u0633 64 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
    base64url: "\u0628\u06CC\u0633 64 \u06CC\u0648 \u0622\u0631 \u0627\u06CC\u0644 \u0627\u0646 \u06A9\u0648\u0688\u0688 \u0633\u0679\u0631\u0646\u06AF",
    json_string: "\u062C\u06D2 \u0627\u06CC\u0633 \u0627\u0648 \u0627\u06CC\u0646 \u0633\u0679\u0631\u0646\u06AF",
    e164: "\u0627\u06CC 164 \u0646\u0645\u0628\u0631",
    jwt: "\u062C\u06D2 \u0688\u0628\u0644\u06CC\u0648 \u0679\u06CC",
    template_literal: "\u0627\u0646 \u067E\u0679"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u0646\u0645\u0628\u0631",
    array: "\u0622\u0631\u06D2",
    null: "\u0646\u0644"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: instanceof ${issue2.expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
        }
        return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${expected} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627\u060C ${received} \u0645\u0648\u0635\u0648\u0644 \u06C1\u0648\u0627`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679: ${stringifyPrimitive(issue2.values[0])} \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
        return `\u063A\u0644\u0637 \u0622\u067E\u0634\u0646: ${joinValues(issue2.values, "|")} \u0645\u06CC\u06BA \u0633\u06D2 \u0627\u06CC\u06A9 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${(_c = issue2.origin) != null ? _c : "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u06D2 ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u0639\u0646\u0627\u0635\u0631"} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
        return `\u0628\u06C1\u062A \u0628\u0691\u0627: ${(_e = issue2.origin) != null ? _e : "\u0648\u06CC\u0644\u06CC\u0648"} \u06A9\u0627 ${adj}${issue2.maximum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u06D2 ${adj}${issue2.minimum.toString()} ${sizing.unit} \u06C1\u0648\u0646\u06D2 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u06D2`;
        }
        return `\u0628\u06C1\u062A \u0686\u06BE\u0648\u0679\u0627: ${issue2.origin} \u06A9\u0627 ${adj}${issue2.minimum.toString()} \u06C1\u0648\u0646\u0627 \u0645\u062A\u0648\u0642\u0639 \u062A\u06BE\u0627`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.prefix}" \u0633\u06D2 \u0634\u0631\u0648\u0639 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        }
        if (_issue.format === "ends_with")
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.suffix}" \u067E\u0631 \u062E\u062A\u0645 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        if (_issue.format === "includes")
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: "${_issue.includes}" \u0634\u0627\u0645\u0644 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        if (_issue.format === "regex")
          return `\u063A\u0644\u0637 \u0633\u0679\u0631\u0646\u06AF: \u067E\u06CC\u0679\u0631\u0646 ${_issue.pattern} \u0633\u06D2 \u0645\u06CC\u0686 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
        return `\u063A\u0644\u0637 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u063A\u0644\u0637 \u0646\u0645\u0628\u0631: ${issue2.divisor} \u06A9\u0627 \u0645\u0636\u0627\u0639\u0641 \u06C1\u0648\u0646\u0627 \u0686\u0627\u06C1\u06CC\u06D2`;
      case "unrecognized_keys":
        return `\u063A\u06CC\u0631 \u062A\u0633\u0644\u06CC\u0645 \u0634\u062F\u06C1 \u06A9\u06CC${issue2.keys.length > 1 ? "\u0632" : ""}: ${joinValues(issue2.keys, "\u060C ")}`;
      case "invalid_key":
        return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u06A9\u06CC`;
      case "invalid_union":
        return "\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679";
      case "invalid_element":
        return `${issue2.origin} \u0645\u06CC\u06BA \u063A\u0644\u0637 \u0648\u06CC\u0644\u06CC\u0648`;
      default:
        return `\u063A\u0644\u0637 \u0627\u0646 \u067E\u0679`;
    }
  };
};
function ur_default() {
  return {
    localeError: error42()
  };
}

// node_modules/zod/v4/locales/uz.js
var error43 = () => {
  const Sizable = {
    string: { unit: "belgi", verb: "bo\u2018lishi kerak" },
    file: { unit: "bayt", verb: "bo\u2018lishi kerak" },
    array: { unit: "element", verb: "bo\u2018lishi kerak" },
    set: { unit: "element", verb: "bo\u2018lishi kerak" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "kirish",
    email: "elektron pochta manzili",
    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 sana va vaqti",
    date: "ISO sana",
    time: "ISO vaqt",
    duration: "ISO davomiylik",
    ipv4: "IPv4 manzil",
    ipv6: "IPv6 manzil",
    mac: "MAC manzil",
    cidrv4: "IPv4 diapazon",
    cidrv6: "IPv6 diapazon",
    base64: "base64 kodlangan satr",
    base64url: "base64url kodlangan satr",
    json_string: "JSON satr",
    e164: "E.164 raqam",
    jwt: "JWT",
    template_literal: "kirish"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "raqam",
    array: "massiv"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `Noto\u2018g\u2018ri kirish: kutilgan instanceof ${issue2.expected}, qabul qilingan ${received}`;
        }
        return `Noto\u2018g\u2018ri kirish: kutilgan ${expected}, qabul qilingan ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `Noto\u2018g\u2018ri kirish: kutilgan ${stringifyPrimitive(issue2.values[0])}`;
        return `Noto\u2018g\u2018ri variant: quyidagilardan biri kutilgan ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Juda katta: kutilgan ${(_c = issue2.origin) != null ? _c : "qiymat"} ${adj}${issue2.maximum.toString()} ${sizing.unit} ${sizing.verb}`;
        return `Juda katta: kutilgan ${(_d2 = issue2.origin) != null ? _d2 : "qiymat"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit} ${sizing.verb}`;
        }
        return `Juda kichik: kutilgan ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Noto\u2018g\u2018ri satr: "${_issue.prefix}" bilan boshlanishi kerak`;
        if (_issue.format === "ends_with")
          return `Noto\u2018g\u2018ri satr: "${_issue.suffix}" bilan tugashi kerak`;
        if (_issue.format === "includes")
          return `Noto\u2018g\u2018ri satr: "${_issue.includes}" ni o\u2018z ichiga olishi kerak`;
        if (_issue.format === "regex")
          return `Noto\u2018g\u2018ri satr: ${_issue.pattern} shabloniga mos kelishi kerak`;
        return `Noto\u2018g\u2018ri ${(_e = FormatDictionary[_issue.format]) != null ? _e : issue2.format}`;
      }
      case "not_multiple_of":
        return `Noto\u2018g\u2018ri raqam: ${issue2.divisor} ning karralisi bo\u2018lishi kerak`;
      case "unrecognized_keys":
        return `Noma\u2019lum kalit${issue2.keys.length > 1 ? "lar" : ""}: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} dagi kalit noto\u2018g\u2018ri`;
      case "invalid_union":
        return "Noto\u2018g\u2018ri kirish";
      case "invalid_element":
        return `${issue2.origin} da noto\u2018g\u2018ri qiymat`;
      default:
        return `Noto\u2018g\u2018ri kirish`;
    }
  };
};
function uz_default() {
  return {
    localeError: error43()
  };
}

// node_modules/zod/v4/locales/vi.js
var error44 = () => {
  const Sizable = {
    string: { unit: "k\xFD t\u1EF1", verb: "c\xF3" },
    file: { unit: "byte", verb: "c\xF3" },
    array: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" },
    set: { unit: "ph\u1EA7n t\u1EED", verb: "c\xF3" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u0111\u1EA7u v\xE0o",
    email: "\u0111\u1ECBa ch\u1EC9 email",
    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: "ng\xE0y gi\u1EDD ISO",
    date: "ng\xE0y ISO",
    time: "gi\u1EDD ISO",
    duration: "kho\u1EA3ng th\u1EDDi gian ISO",
    ipv4: "\u0111\u1ECBa ch\u1EC9 IPv4",
    ipv6: "\u0111\u1ECBa ch\u1EC9 IPv6",
    cidrv4: "d\u1EA3i IPv4",
    cidrv6: "d\u1EA3i IPv6",
    base64: "chu\u1ED7i m\xE3 h\xF3a base64",
    base64url: "chu\u1ED7i m\xE3 h\xF3a base64url",
    json_string: "chu\u1ED7i JSON",
    e164: "s\u1ED1 E.164",
    jwt: "JWT",
    template_literal: "\u0111\u1EA7u v\xE0o"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "s\u1ED1",
    array: "m\u1EA3ng"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i instanceof ${issue2.expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;
        }
        return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${expected}, nh\u1EADn \u0111\u01B0\u1EE3c ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i ${stringifyPrimitive(issue2.values[0])}`;
        return `T\xF9y ch\u1ECDn kh\xF4ng h\u1EE3p l\u1EC7: mong \u0111\u1EE3i m\u1ED9t trong c\xE1c gi\xE1 tr\u1ECB ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${(_c = issue2.origin) != null ? _c : "gi\xE1 tr\u1ECB"} ${sizing.verb} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "ph\u1EA7n t\u1EED"}`;
        return `Qu\xE1 l\u1EDBn: mong \u0111\u1EE3i ${(_e = issue2.origin) != null ? _e : "gi\xE1 tr\u1ECB"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `Qu\xE1 nh\u1ECF: mong \u0111\u1EE3i ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i b\u1EAFt \u0111\u1EA7u b\u1EB1ng "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i k\u1EBFt th\xFAc b\u1EB1ng "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i bao g\u1ED3m "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `Chu\u1ED7i kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i kh\u1EDBp v\u1EDBi m\u1EABu ${_issue.pattern}`;
        return `${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format} kh\xF4ng h\u1EE3p l\u1EC7`;
      }
      case "not_multiple_of":
        return `S\u1ED1 kh\xF4ng h\u1EE3p l\u1EC7: ph\u1EA3i l\xE0 b\u1ED9i s\u1ED1 c\u1EE7a ${issue2.divisor}`;
      case "unrecognized_keys":
        return `Kh\xF3a kh\xF4ng \u0111\u01B0\u1EE3c nh\u1EADn d\u1EA1ng: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `Kh\xF3a kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
      case "invalid_union":
        return "\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7";
      case "invalid_element":
        return `Gi\xE1 tr\u1ECB kh\xF4ng h\u1EE3p l\u1EC7 trong ${issue2.origin}`;
      default:
        return `\u0110\u1EA7u v\xE0o kh\xF4ng h\u1EE3p l\u1EC7`;
    }
  };
};
function vi_default() {
  return {
    localeError: error44()
  };
}

// node_modules/zod/v4/locales/zh-CN.js
var error45 = () => {
  const Sizable = {
    string: { unit: "\u5B57\u7B26", verb: "\u5305\u542B" },
    file: { unit: "\u5B57\u8282", verb: "\u5305\u542B" },
    array: { unit: "\u9879", verb: "\u5305\u542B" },
    set: { unit: "\u9879", verb: "\u5305\u542B" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u8F93\u5165",
    email: "\u7535\u5B50\u90AE\u4EF6",
    url: "URL",
    emoji: "\u8868\u60C5\u7B26\u53F7",
    uuid: "UUID",
    uuidv4: "UUIDv4",
    uuidv6: "UUIDv6",
    nanoid: "nanoid",
    guid: "GUID",
    cuid: "cuid",
    cuid2: "cuid2",
    ulid: "ULID",
    xid: "XID",
    ksuid: "KSUID",
    datetime: "ISO\u65E5\u671F\u65F6\u95F4",
    date: "ISO\u65E5\u671F",
    time: "ISO\u65F6\u95F4",
    duration: "ISO\u65F6\u957F",
    ipv4: "IPv4\u5730\u5740",
    ipv6: "IPv6\u5730\u5740",
    cidrv4: "IPv4\u7F51\u6BB5",
    cidrv6: "IPv6\u7F51\u6BB5",
    base64: "base64\u7F16\u7801\u5B57\u7B26\u4E32",
    base64url: "base64url\u7F16\u7801\u5B57\u7B26\u4E32",
    json_string: "JSON\u5B57\u7B26\u4E32",
    e164: "E.164\u53F7\u7801",
    jwt: "JWT",
    template_literal: "\u8F93\u5165"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "\u6570\u5B57",
    array: "\u6570\u7EC4",
    null: "\u7A7A\u503C(null)"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B instanceof ${issue2.expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;
        }
        return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${expected}\uFF0C\u5B9E\u9645\u63A5\u6536 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u65E0\u6548\u8F93\u5165\uFF1A\u671F\u671B ${stringifyPrimitive(issue2.values[0])}`;
        return `\u65E0\u6548\u9009\u9879\uFF1A\u671F\u671B\u4EE5\u4E0B\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${(_c = issue2.origin) != null ? _c : "\u503C"} ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u4E2A\u5143\u7D20"}`;
        return `\u6570\u503C\u8FC7\u5927\uFF1A\u671F\u671B ${(_e = issue2.origin) != null ? _e : "\u503C"} ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u6570\u503C\u8FC7\u5C0F\uFF1A\u671F\u671B ${issue2.origin} ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.prefix}" \u5F00\u5934`;
        if (_issue.format === "ends_with")
          return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u4EE5 "${_issue.suffix}" \u7ED3\u5C3E`;
        if (_issue.format === "includes")
          return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u5305\u542B "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u65E0\u6548\u5B57\u7B26\u4E32\uFF1A\u5FC5\u987B\u6EE1\u8DB3\u6B63\u5219\u8868\u8FBE\u5F0F ${_issue.pattern}`;
        return `\u65E0\u6548${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u65E0\u6548\u6570\u5B57\uFF1A\u5FC5\u987B\u662F ${issue2.divisor} \u7684\u500D\u6570`;
      case "unrecognized_keys":
        return `\u51FA\u73B0\u672A\u77E5\u7684\u952E(key): ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `${issue2.origin} \u4E2D\u7684\u952E(key)\u65E0\u6548`;
      case "invalid_union":
        return "\u65E0\u6548\u8F93\u5165";
      case "invalid_element":
        return `${issue2.origin} \u4E2D\u5305\u542B\u65E0\u6548\u503C(value)`;
      default:
        return `\u65E0\u6548\u8F93\u5165`;
    }
  };
};
function zh_CN_default2() {
  return {
    localeError: error45()
  };
}

// node_modules/zod/v4/locales/zh-TW.js
var error46 = () => {
  const Sizable = {
    string: { unit: "\u5B57\u5143", verb: "\u64C1\u6709" },
    file: { unit: "\u4F4D\u5143\u7D44", verb: "\u64C1\u6709" },
    array: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" },
    set: { unit: "\u9805\u76EE", verb: "\u64C1\u6709" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u8F38\u5165",
    email: "\u90F5\u4EF6\u5730\u5740",
    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 \u65E5\u671F\u6642\u9593",
    date: "ISO \u65E5\u671F",
    time: "ISO \u6642\u9593",
    duration: "ISO \u671F\u9593",
    ipv4: "IPv4 \u4F4D\u5740",
    ipv6: "IPv6 \u4F4D\u5740",
    cidrv4: "IPv4 \u7BC4\u570D",
    cidrv6: "IPv6 \u7BC4\u570D",
    base64: "base64 \u7DE8\u78BC\u5B57\u4E32",
    base64url: "base64url \u7DE8\u78BC\u5B57\u4E32",
    json_string: "JSON \u5B57\u4E32",
    e164: "E.164 \u6578\u503C",
    jwt: "JWT",
    template_literal: "\u8F38\u5165"
  };
  const TypeDictionary = {
    nan: "NaN"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2, _e, _f;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA instanceof ${issue2.expected}\uFF0C\u4F46\u6536\u5230 ${received}`;
        }
        return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${expected}\uFF0C\u4F46\u6536\u5230 ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\u7121\u6548\u7684\u8F38\u5165\u503C\uFF1A\u9810\u671F\u70BA ${stringifyPrimitive(issue2.values[0])}`;
        return `\u7121\u6548\u7684\u9078\u9805\uFF1A\u9810\u671F\u70BA\u4EE5\u4E0B\u5176\u4E2D\u4E4B\u4E00 ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${(_c = issue2.origin) != null ? _c : "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()} ${(_d2 = sizing.unit) != null ? _d2 : "\u500B\u5143\u7D20"}`;
        return `\u6578\u503C\u904E\u5927\uFF1A\u9810\u671F ${(_e = issue2.origin) != null ? _e : "\u503C"} \u61C9\u70BA ${adj}${issue2.maximum.toString()}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing) {
          return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()} ${sizing.unit}`;
        }
        return `\u6578\u503C\u904E\u5C0F\uFF1A\u9810\u671F ${issue2.origin} \u61C9\u70BA ${adj}${issue2.minimum.toString()}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with") {
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.prefix}" \u958B\u982D`;
        }
        if (_issue.format === "ends_with")
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u4EE5 "${_issue.suffix}" \u7D50\u5C3E`;
        if (_issue.format === "includes")
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u5305\u542B "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u7121\u6548\u7684\u5B57\u4E32\uFF1A\u5FC5\u9808\u7B26\u5408\u683C\u5F0F ${_issue.pattern}`;
        return `\u7121\u6548\u7684 ${(_f = FormatDictionary[_issue.format]) != null ? _f : issue2.format}`;
      }
      case "not_multiple_of":
        return `\u7121\u6548\u7684\u6578\u5B57\uFF1A\u5FC5\u9808\u70BA ${issue2.divisor} \u7684\u500D\u6578`;
      case "unrecognized_keys":
        return `\u7121\u6CD5\u8B58\u5225\u7684\u9375\u503C${issue2.keys.length > 1 ? "\u5011" : ""}\uFF1A${joinValues(issue2.keys, "\u3001")}`;
      case "invalid_key":
        return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u9375\u503C`;
      case "invalid_union":
        return "\u7121\u6548\u7684\u8F38\u5165\u503C";
      case "invalid_element":
        return `${issue2.origin} \u4E2D\u6709\u7121\u6548\u7684\u503C`;
      default:
        return `\u7121\u6548\u7684\u8F38\u5165\u503C`;
    }
  };
};
function zh_TW_default2() {
  return {
    localeError: error46()
  };
}

// node_modules/zod/v4/locales/yo.js
var error47 = () => {
  const Sizable = {
    string: { unit: "\xE0mi", verb: "n\xED" },
    file: { unit: "bytes", verb: "n\xED" },
    array: { unit: "nkan", verb: "n\xED" },
    set: { unit: "nkan", verb: "n\xED" }
  };
  function getSizing(origin) {
    var _a3;
    return (_a3 = Sizable[origin]) != null ? _a3 : null;
  }
  const FormatDictionary = {
    regex: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9",
    email: "\xE0d\xEDr\u1EB9\u0301s\xEC \xECm\u1EB9\u0301l\xEC",
    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: "\xE0k\xF3k\xF2 ISO",
    date: "\u1ECDj\u1ECD\u0301 ISO",
    time: "\xE0k\xF3k\xF2 ISO",
    duration: "\xE0k\xF3k\xF2 t\xF3 p\xE9 ISO",
    ipv4: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv4",
    ipv6: "\xE0d\xEDr\u1EB9\u0301s\xEC IPv6",
    cidrv4: "\xE0gb\xE8gb\xE8 IPv4",
    cidrv6: "\xE0gb\xE8gb\xE8 IPv6",
    base64: "\u1ECD\u0300r\u1ECD\u0300 t\xED a k\u1ECD\u0301 n\xED base64",
    base64url: "\u1ECD\u0300r\u1ECD\u0300 base64url",
    json_string: "\u1ECD\u0300r\u1ECD\u0300 JSON",
    e164: "n\u1ECD\u0301mb\xE0 E.164",
    jwt: "JWT",
    template_literal: "\u1EB9\u0300r\u1ECD \xECb\xE1w\u1ECDl\xE9"
  };
  const TypeDictionary = {
    nan: "NaN",
    number: "n\u1ECD\u0301mb\xE0",
    array: "akop\u1ECD"
  };
  return (issue2) => {
    var _a3, _b2, _c, _d2;
    switch (issue2.code) {
      case "invalid_type": {
        const expected = (_a3 = TypeDictionary[issue2.expected]) != null ? _a3 : issue2.expected;
        const receivedType = parsedType(issue2.input);
        const received = (_b2 = TypeDictionary[receivedType]) != null ? _b2 : receivedType;
        if (/^[A-Z]/.test(issue2.expected)) {
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi instanceof ${issue2.expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`;
        }
        return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${expected}, \xE0m\u1ECD\u0300 a r\xED ${received}`;
      }
      case "invalid_value":
        if (issue2.values.length === 1)
          return `\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e: a n\xED l\xE1ti fi ${stringifyPrimitive(issue2.values[0])}`;
        return `\xC0\u1E63\xE0y\xE0n a\u1E63\xEC\u1E63e: yan \u1ECD\u0300kan l\xE1ra ${joinValues(issue2.values, "|")}`;
      case "too_big": {
        const adj = issue2.inclusive ? "<=" : "<";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${(_c = issue2.origin) != null ? _c : "iye"} ${sizing.verb} ${adj}${issue2.maximum} ${sizing.unit}`;
        return `T\xF3 p\u1ECD\u0300 j\xF9: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.maximum}`;
      }
      case "too_small": {
        const adj = issue2.inclusive ? ">=" : ">";
        const sizing = getSizing(issue2.origin);
        if (sizing)
          return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 p\xE9 ${issue2.origin} ${sizing.verb} ${adj}${issue2.minimum} ${sizing.unit}`;
        return `K\xE9r\xE9 ju: a n\xED l\xE1ti j\u1EB9\u0301 ${adj}${issue2.minimum}`;
      }
      case "invalid_format": {
        const _issue = issue2;
        if (_issue.format === "starts_with")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\u1EB9\u0300r\u1EB9\u0300 p\u1EB9\u0300l\xFA "${_issue.prefix}"`;
        if (_issue.format === "ends_with")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 par\xED p\u1EB9\u0300l\xFA "${_issue.suffix}"`;
        if (_issue.format === "includes")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 n\xED "${_issue.includes}"`;
        if (_issue.format === "regex")
          return `\u1ECC\u0300r\u1ECD\u0300 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 b\xE1 \xE0p\u1EB9\u1EB9r\u1EB9 mu ${_issue.pattern}`;
        return `A\u1E63\xEC\u1E63e: ${(_d2 = FormatDictionary[_issue.format]) != null ? _d2 : issue2.format}`;
      }
      case "not_multiple_of":
        return `N\u1ECD\u0301mb\xE0 a\u1E63\xEC\u1E63e: gb\u1ECD\u0301d\u1ECD\u0300 j\u1EB9\u0301 \xE8y\xE0 p\xEDp\xEDn ti ${issue2.divisor}`;
      case "unrecognized_keys":
        return `B\u1ECDt\xECn\xEC \xE0\xECm\u1ECD\u0300: ${joinValues(issue2.keys, ", ")}`;
      case "invalid_key":
        return `B\u1ECDt\xECn\xEC a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;
      case "invalid_union":
        return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
      case "invalid_element":
        return `Iye a\u1E63\xEC\u1E63e n\xEDn\xFA ${issue2.origin}`;
      default:
        return "\xCCb\xE1w\u1ECDl\xE9 a\u1E63\xEC\u1E63e";
    }
  };
};
function yo_default() {
  return {
    localeError: error47()
  };
}

// node_modules/zod/v4/core/registries.js
var _a;
var $output = /* @__PURE__ */ Symbol("ZodOutput");
var $input = /* @__PURE__ */ Symbol("ZodInput");
var $ZodRegistry = class {
  constructor() {
    this._map = /* @__PURE__ */ new WeakMap();
    this._idmap = /* @__PURE__ */ new Map();
  }
  add(schema, ..._meta) {
    const meta3 = _meta[0];
    this._map.set(schema, meta3);
    if (meta3 && typeof meta3 === "object" && "id" in meta3) {
      this._idmap.set(meta3.id, schema);
    }
    return this;
  }
  clear() {
    this._map = /* @__PURE__ */ new WeakMap();
    this._idmap = /* @__PURE__ */ new Map();
    return this;
  }
  remove(schema) {
    const meta3 = this._map.get(schema);
    if (meta3 && typeof meta3 === "object" && "id" in meta3) {
      this._idmap.delete(meta3.id);
    }
    this._map.delete(schema);
    return this;
  }
  get(schema) {
    var _a3;
    const p = schema._zod.parent;
    if (p) {
      const pm = { ...(_a3 = this.get(p)) != null ? _a3 : {} };
      delete pm.id;
      const f2 = { ...pm, ...this._map.get(schema) };
      return Object.keys(f2).length ? f2 : void 0;
    }
    return this._map.get(schema);
  }
  has(schema) {
    return this._map.has(schema);
  }
};
function registry() {
  return new $ZodRegistry();
}
var _a2;
(_a2 = (_a = globalThis).__zod_globalRegistry) != null ? _a2 : _a.__zod_globalRegistry = registry();
var globalRegistry = globalThis.__zod_globalRegistry;

// node_modules/zod/v4/core/api.js
// @__NO_SIDE_EFFECTS__
function _string(Class2, params) {
  return new Class2({
    type: "string",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedString(Class2, params) {
  return new Class2({
    type: "string",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _email(Class2, params) {
  return new Class2({
    type: "string",
    format: "email",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _guid(Class2, params) {
  return new Class2({
    type: "string",
    format: "guid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v4",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v6",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uuidv7(Class2, params) {
  return new Class2({
    type: "string",
    format: "uuid",
    check: "string_format",
    abort: false,
    version: "v7",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _url(Class2, params) {
  return new Class2({
    type: "string",
    format: "url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _emoji2(Class2, params) {
  return new Class2({
    type: "string",
    format: "emoji",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nanoid(Class2, params) {
  return new Class2({
    type: "string",
    format: "nanoid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cuid2(Class2, params) {
  return new Class2({
    type: "string",
    format: "cuid2",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ulid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ulid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _xid(Class2, params) {
  return new Class2({
    type: "string",
    format: "xid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ksuid(Class2, params) {
  return new Class2({
    type: "string",
    format: "ksuid",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ipv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _ipv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "ipv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _mac(Class2, params) {
  return new Class2({
    type: "string",
    format: "mac",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cidrv4(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv4",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _cidrv6(Class2, params) {
  return new Class2({
    type: "string",
    format: "cidrv6",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _base64(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _base64url(Class2, params) {
  return new Class2({
    type: "string",
    format: "base64url",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _e164(Class2, params) {
  return new Class2({
    type: "string",
    format: "e164",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _jwt(Class2, params) {
  return new Class2({
    type: "string",
    format: "jwt",
    check: "string_format",
    abort: false,
    ...normalizeParams(params)
  });
}
var TimePrecision = {
  Any: null,
  Minute: -1,
  Second: 0,
  Millisecond: 3,
  Microsecond: 6
};
// @__NO_SIDE_EFFECTS__
function _isoDateTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "datetime",
    check: "string_format",
    offset: false,
    local: false,
    precision: null,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoDate(Class2, params) {
  return new Class2({
    type: "string",
    format: "date",
    check: "string_format",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoTime(Class2, params) {
  return new Class2({
    type: "string",
    format: "time",
    check: "string_format",
    precision: null,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _isoDuration(Class2, params) {
  return new Class2({
    type: "string",
    format: "duration",
    check: "string_format",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _number(Class2, params) {
  return new Class2({
    type: "number",
    checks: [],
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedNumber(Class2, params) {
  return new Class2({
    type: "number",
    coerce: true,
    checks: [],
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _float32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float32",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _float64(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "float64",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "int32",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uint32(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "uint32",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _boolean(Class2, params) {
  return new Class2({
    type: "boolean",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedBoolean(Class2, params) {
  return new Class2({
    type: "boolean",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _bigint(Class2, params) {
  return new Class2({
    type: "bigint",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedBigint(Class2, params) {
  return new Class2({
    type: "bigint",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _int64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "int64",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uint64(Class2, params) {
  return new Class2({
    type: "bigint",
    check: "bigint_format",
    abort: false,
    format: "uint64",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _symbol(Class2, params) {
  return new Class2({
    type: "symbol",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _undefined2(Class2, params) {
  return new Class2({
    type: "undefined",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _null2(Class2, params) {
  return new Class2({
    type: "null",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _any(Class2) {
  return new Class2({
    type: "any"
  });
}
// @__NO_SIDE_EFFECTS__
function _unknown(Class2) {
  return new Class2({
    type: "unknown"
  });
}
// @__NO_SIDE_EFFECTS__
function _never(Class2, params) {
  return new Class2({
    type: "never",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _void(Class2, params) {
  return new Class2({
    type: "void",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _date(Class2, params) {
  return new Class2({
    type: "date",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _coercedDate(Class2, params) {
  return new Class2({
    type: "date",
    coerce: true,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nan(Class2, params) {
  return new Class2({
    type: "nan",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _lt(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
// @__NO_SIDE_EFFECTS__
function _lte(value, params) {
  return new $ZodCheckLessThan({
    check: "less_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
// @__NO_SIDE_EFFECTS__
function _gt(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: false
  });
}
// @__NO_SIDE_EFFECTS__
function _gte(value, params) {
  return new $ZodCheckGreaterThan({
    check: "greater_than",
    ...normalizeParams(params),
    value,
    inclusive: true
  });
}
// @__NO_SIDE_EFFECTS__
function _positive(params) {
  return /* @__PURE__ */ _gt(0, params);
}
// @__NO_SIDE_EFFECTS__
function _negative(params) {
  return /* @__PURE__ */ _lt(0, params);
}
// @__NO_SIDE_EFFECTS__
function _nonpositive(params) {
  return /* @__PURE__ */ _lte(0, params);
}
// @__NO_SIDE_EFFECTS__
function _nonnegative(params) {
  return /* @__PURE__ */ _gte(0, params);
}
// @__NO_SIDE_EFFECTS__
function _multipleOf(value, params) {
  return new $ZodCheckMultipleOf({
    check: "multiple_of",
    ...normalizeParams(params),
    value
  });
}
// @__NO_SIDE_EFFECTS__
function _maxSize(maximum, params) {
  return new $ZodCheckMaxSize({
    check: "max_size",
    ...normalizeParams(params),
    maximum
  });
}
// @__NO_SIDE_EFFECTS__
function _minSize(minimum, params) {
  return new $ZodCheckMinSize({
    check: "min_size",
    ...normalizeParams(params),
    minimum
  });
}
// @__NO_SIDE_EFFECTS__
function _size(size, params) {
  return new $ZodCheckSizeEquals({
    check: "size_equals",
    ...normalizeParams(params),
    size
  });
}
// @__NO_SIDE_EFFECTS__
function _maxLength(maximum, params) {
  const ch = new $ZodCheckMaxLength({
    check: "max_length",
    ...normalizeParams(params),
    maximum
  });
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _minLength(minimum, params) {
  return new $ZodCheckMinLength({
    check: "min_length",
    ...normalizeParams(params),
    minimum
  });
}
// @__NO_SIDE_EFFECTS__
function _length(length, params) {
  return new $ZodCheckLengthEquals({
    check: "length_equals",
    ...normalizeParams(params),
    length
  });
}
// @__NO_SIDE_EFFECTS__
function _regex(pattern, params) {
  return new $ZodCheckRegex({
    check: "string_format",
    format: "regex",
    ...normalizeParams(params),
    pattern
  });
}
// @__NO_SIDE_EFFECTS__
function _lowercase(params) {
  return new $ZodCheckLowerCase({
    check: "string_format",
    format: "lowercase",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _uppercase(params) {
  return new $ZodCheckUpperCase({
    check: "string_format",
    format: "uppercase",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _includes(includes, params) {
  return new $ZodCheckIncludes({
    check: "string_format",
    format: "includes",
    ...normalizeParams(params),
    includes
  });
}
// @__NO_SIDE_EFFECTS__
function _startsWith(prefix, params) {
  return new $ZodCheckStartsWith({
    check: "string_format",
    format: "starts_with",
    ...normalizeParams(params),
    prefix
  });
}
// @__NO_SIDE_EFFECTS__
function _endsWith(suffix, params) {
  return new $ZodCheckEndsWith({
    check: "string_format",
    format: "ends_with",
    ...normalizeParams(params),
    suffix
  });
}
// @__NO_SIDE_EFFECTS__
function _property(property, schema, params) {
  return new $ZodCheckProperty({
    check: "property",
    property,
    schema,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _mime(types, params) {
  return new $ZodCheckMimeType({
    check: "mime_type",
    mime: types,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _overwrite(tx) {
  return new $ZodCheckOverwrite({
    check: "overwrite",
    tx
  });
}
// @__NO_SIDE_EFFECTS__
function _normalize(form) {
  return /* @__PURE__ */ _overwrite((input) => input.normalize(form));
}
// @__NO_SIDE_EFFECTS__
function _trim() {
  return /* @__PURE__ */ _overwrite((input) => input.trim());
}
// @__NO_SIDE_EFFECTS__
function _toLowerCase() {
  return /* @__PURE__ */ _overwrite((input) => input.toLowerCase());
}
// @__NO_SIDE_EFFECTS__
function _toUpperCase() {
  return /* @__PURE__ */ _overwrite((input) => input.toUpperCase());
}
// @__NO_SIDE_EFFECTS__
function _slugify() {
  return /* @__PURE__ */ _overwrite((input) => slugify(input));
}
// @__NO_SIDE_EFFECTS__
function _array(Class2, element, params) {
  return new Class2({
    type: "array",
    element,
    // get element() {
    //   return element;
    // },
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _union(Class2, options, params) {
  return new Class2({
    type: "union",
    options,
    ...normalizeParams(params)
  });
}
function _xor(Class2, options, params) {
  return new Class2({
    type: "union",
    options,
    inclusive: false,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _discriminatedUnion(Class2, discriminator, options, params) {
  return new Class2({
    type: "union",
    options,
    discriminator,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _intersection(Class2, left, right) {
  return new Class2({
    type: "intersection",
    left,
    right
  });
}
// @__NO_SIDE_EFFECTS__
function _tuple(Class2, items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new Class2({
    type: "tuple",
    items,
    rest,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _record(Class2, keyType, valueType, params) {
  return new Class2({
    type: "record",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _map(Class2, keyType, valueType, params) {
  return new Class2({
    type: "map",
    keyType,
    valueType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _set(Class2, valueType, params) {
  return new Class2({
    type: "set",
    valueType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _enum(Class2, values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values;
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _nativeEnum(Class2, entries, params) {
  return new Class2({
    type: "enum",
    entries,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _literal(Class2, value, params) {
  return new Class2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _file(Class2, params) {
  return new Class2({
    type: "file",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _transform(Class2, fn) {
  return new Class2({
    type: "transform",
    transform: fn
  });
}
// @__NO_SIDE_EFFECTS__
function _optional(Class2, innerType) {
  return new Class2({
    type: "optional",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _nullable(Class2, innerType) {
  return new Class2({
    type: "nullable",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _default(Class2, innerType, defaultValue) {
  return new Class2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue);
    }
  });
}
// @__NO_SIDE_EFFECTS__
function _nonoptional(Class2, innerType, params) {
  return new Class2({
    type: "nonoptional",
    innerType,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _success(Class2, innerType) {
  return new Class2({
    type: "success",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _catch(Class2, innerType, catchValue) {
  return new Class2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
// @__NO_SIDE_EFFECTS__
function _pipe(Class2, in_, out) {
  return new Class2({
    type: "pipe",
    in: in_,
    out
  });
}
// @__NO_SIDE_EFFECTS__
function _readonly(Class2, innerType) {
  return new Class2({
    type: "readonly",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _templateLiteral(Class2, parts, params) {
  return new Class2({
    type: "template_literal",
    parts,
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _lazy(Class2, getter) {
  return new Class2({
    type: "lazy",
    getter
  });
}
// @__NO_SIDE_EFFECTS__
function _promise(Class2, innerType) {
  return new Class2({
    type: "promise",
    innerType
  });
}
// @__NO_SIDE_EFFECTS__
function _custom(Class2, fn, _params) {
  var _a3;
  const norm = normalizeParams(_params);
  (_a3 = norm.abort) != null ? _a3 : norm.abort = true;
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...norm
  });
  return schema;
}
// @__NO_SIDE_EFFECTS__
function _refine(Class2, fn, _params) {
  const schema = new Class2({
    type: "custom",
    check: "custom",
    fn,
    ...normalizeParams(_params)
  });
  return schema;
}
// @__NO_SIDE_EFFECTS__
function _superRefine(fn) {
  const ch = /* @__PURE__ */ _check((payload) => {
    payload.addIssue = (issue2) => {
      var _a3, _b2, _c, _d2;
      if (typeof issue2 === "string") {
        payload.issues.push(issue(issue2, payload.value, ch._zod.def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        (_a3 = _issue.code) != null ? _a3 : _issue.code = "custom";
        (_b2 = _issue.input) != null ? _b2 : _issue.input = payload.value;
        (_c = _issue.inst) != null ? _c : _issue.inst = ch;
        (_d2 = _issue.continue) != null ? _d2 : _issue.continue = !ch._zod.def.abort;
        payload.issues.push(issue(_issue));
      }
    };
    return fn(payload.value, payload);
  });
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _check(fn, params) {
  const ch = new $ZodCheck({
    check: "custom",
    ...normalizeParams(params)
  });
  ch._zod.check = fn;
  return ch;
}
// @__NO_SIDE_EFFECTS__
function describe(description) {
  const ch = new $ZodCheck({ check: "describe" });
  ch._zod.onattach = [
    (inst) => {
      var _a3;
      const existing = (_a3 = globalRegistry.get(inst)) != null ? _a3 : {};
      globalRegistry.add(inst, { ...existing, description });
    }
  ];
  ch._zod.check = () => {
  };
  return ch;
}
// @__NO_SIDE_EFFECTS__
function meta(metadata) {
  const ch = new $ZodCheck({ check: "meta" });
  ch._zod.onattach = [
    (inst) => {
      var _a3;
      const existing = (_a3 = globalRegistry.get(inst)) != null ? _a3 : {};
      globalRegistry.add(inst, { ...existing, ...metadata });
    }
  ];
  ch._zod.check = () => {
  };
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _stringbool(Classes, _params) {
  var _a3, _b2, _c, _d2, _e;
  const params = normalizeParams(_params);
  let truthyArray = (_a3 = params.truthy) != null ? _a3 : ["true", "1", "yes", "on", "y", "enabled"];
  let falsyArray = (_b2 = params.falsy) != null ? _b2 : ["false", "0", "no", "off", "n", "disabled"];
  if (params.case !== "sensitive") {
    truthyArray = truthyArray.map((v2) => typeof v2 === "string" ? v2.toLowerCase() : v2);
    falsyArray = falsyArray.map((v2) => typeof v2 === "string" ? v2.toLowerCase() : v2);
  }
  const truthySet = new Set(truthyArray);
  const falsySet = new Set(falsyArray);
  const _Codec = (_c = Classes.Codec) != null ? _c : $ZodCodec;
  const _Boolean = (_d2 = Classes.Boolean) != null ? _d2 : $ZodBoolean;
  const _String = (_e = Classes.String) != null ? _e : $ZodString;
  const stringSchema = new _String({ type: "string", error: params.error });
  const booleanSchema = new _Boolean({ type: "boolean", error: params.error });
  const codec2 = new _Codec({
    type: "pipe",
    in: stringSchema,
    out: booleanSchema,
    transform: ((input, payload) => {
      let data = input;
      if (params.case !== "sensitive")
        data = data.toLowerCase();
      if (truthySet.has(data)) {
        return true;
      } else if (falsySet.has(data)) {
        return false;
      } else {
        payload.issues.push({
          code: "invalid_value",
          expected: "stringbool",
          values: [...truthySet, ...falsySet],
          input: payload.value,
          inst: codec2,
          continue: false
        });
        return {};
      }
    }),
    reverseTransform: ((input, _payload) => {
      if (input === true) {
        return truthyArray[0] || "true";
      } else {
        return falsyArray[0] || "false";
      }
    }),
    error: params.error
  });
  return codec2;
}
// @__NO_SIDE_EFFECTS__
function _stringFormat(Class2, format, fnOrRegex, _params = {}) {
  const params = normalizeParams(_params);
  const def = {
    ...normalizeParams(_params),
    check: "string_format",
    type: "string",
    format,
    fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val),
    ...params
  };
  if (fnOrRegex instanceof RegExp) {
    def.pattern = fnOrRegex;
  }
  const inst = new Class2(def);
  return inst;
}

// node_modules/zod/v4/core/to-json-schema.js
function initializeContext(params) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i;
  let target = (_a3 = params == null ? void 0 : params.target) != null ? _a3 : "draft-2020-12";
  if (target === "draft-4")
    target = "draft-04";
  if (target === "draft-7")
    target = "draft-07";
  return {
    processors: (_b2 = params.processors) != null ? _b2 : {},
    metadataRegistry: (_c = params == null ? void 0 : params.metadata) != null ? _c : globalRegistry,
    target,
    unrepresentable: (_d2 = params == null ? void 0 : params.unrepresentable) != null ? _d2 : "throw",
    override: (_e = params == null ? void 0 : params.override) != null ? _e : (() => {
    }),
    io: (_f = params == null ? void 0 : params.io) != null ? _f : "output",
    counter: 0,
    seen: /* @__PURE__ */ new Map(),
    cycles: (_g = params == null ? void 0 : params.cycles) != null ? _g : "ref",
    reused: (_h = params == null ? void 0 : params.reused) != null ? _h : "inline",
    external: (_i = params == null ? void 0 : params.external) != null ? _i : void 0
  };
}
function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
  var _a4, _b2, _c;
  var _a3;
  const def = schema._zod.def;
  const seen = ctx.seen.get(schema);
  if (seen) {
    seen.count++;
    const isCycle = _params.schemaPath.includes(schema);
    if (isCycle) {
      seen.cycle = _params.path;
    }
    return seen.schema;
  }
  const result = { schema: {}, count: 1, cycle: void 0, path: _params.path };
  ctx.seen.set(schema, result);
  const overrideSchema = (_b2 = (_a4 = schema._zod).toJSONSchema) == null ? void 0 : _b2.call(_a4);
  if (overrideSchema) {
    result.schema = overrideSchema;
  } else {
    const params = {
      ..._params,
      schemaPath: [..._params.schemaPath, schema],
      path: _params.path
    };
    if (schema._zod.processJSONSchema) {
      schema._zod.processJSONSchema(ctx, result.schema, params);
    } else {
      const _json = result.schema;
      const processor = ctx.processors[def.type];
      if (!processor) {
        throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`);
      }
      processor(schema, ctx, _json, params);
    }
    const parent = schema._zod.parent;
    if (parent) {
      if (!result.ref)
        result.ref = parent;
      process2(parent, ctx, params);
      ctx.seen.get(parent).isParent = true;
    }
  }
  const meta3 = ctx.metadataRegistry.get(schema);
  if (meta3)
    Object.assign(result.schema, meta3);
  if (ctx.io === "input" && isTransforming(schema)) {
    delete result.schema.examples;
    delete result.schema.default;
  }
  if (ctx.io === "input" && result.schema._prefault)
    (_c = (_a3 = result.schema).default) != null ? _c : _a3.default = result.schema._prefault;
  delete result.schema._prefault;
  const _result = ctx.seen.get(schema);
  return _result.schema;
}
function extractDefs(ctx, schema) {
  var _a3, _b2, _c, _d2;
  const root = ctx.seen.get(schema);
  if (!root)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const idToSchema = /* @__PURE__ */ new Map();
  for (const entry of ctx.seen.entries()) {
    const id = (_a3 = ctx.metadataRegistry.get(entry[0])) == null ? void 0 : _a3.id;
    if (id) {
      const existing = idToSchema.get(id);
      if (existing && existing !== entry[0]) {
        throw new Error(`Duplicate schema id "${id}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);
      }
      idToSchema.set(id, entry[0]);
    }
  }
  const makeURI = (entry) => {
    var _a4, _b3, _c2, _d3, _e;
    const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
    if (ctx.external) {
      const externalId = (_a4 = ctx.external.registry.get(entry[0])) == null ? void 0 : _a4.id;
      const uriGenerator = (_b3 = ctx.external.uri) != null ? _b3 : ((id2) => id2);
      if (externalId) {
        return { ref: uriGenerator(externalId) };
      }
      const id = (_d3 = (_c2 = entry[1].defId) != null ? _c2 : entry[1].schema.id) != null ? _d3 : `schema${ctx.counter++}`;
      entry[1].defId = id;
      return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` };
    }
    if (entry[1] === root) {
      return { ref: "#" };
    }
    const uriPrefix = `#`;
    const defUriPrefix = `${uriPrefix}/${defsSegment}/`;
    const defId = (_e = entry[1].schema.id) != null ? _e : `__schema${ctx.counter++}`;
    return { defId, ref: defUriPrefix + defId };
  };
  const extractToDef = (entry) => {
    if (entry[1].schema.$ref) {
      return;
    }
    const seen = entry[1];
    const { ref, defId } = makeURI(entry);
    seen.def = { ...seen.schema };
    if (defId)
      seen.defId = defId;
    const schema2 = seen.schema;
    for (const key in schema2) {
      delete schema2[key];
    }
    schema2.$ref = ref;
  };
  if (ctx.cycles === "throw") {
    for (const entry of ctx.seen.entries()) {
      const seen = entry[1];
      if (seen.cycle) {
        throw new Error(`Cycle detected: #/${(_b2 = seen.cycle) == null ? void 0 : _b2.join("/")}/<root>

Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`);
      }
    }
  }
  for (const entry of ctx.seen.entries()) {
    const seen = entry[1];
    if (schema === entry[0]) {
      extractToDef(entry);
      continue;
    }
    if (ctx.external) {
      const ext = (_c = ctx.external.registry.get(entry[0])) == null ? void 0 : _c.id;
      if (schema !== entry[0] && ext) {
        extractToDef(entry);
        continue;
      }
    }
    const id = (_d2 = ctx.metadataRegistry.get(entry[0])) == null ? void 0 : _d2.id;
    if (id) {
      extractToDef(entry);
      continue;
    }
    if (seen.cycle) {
      extractToDef(entry);
      continue;
    }
    if (seen.count > 1) {
      if (ctx.reused === "ref") {
        extractToDef(entry);
        continue;
      }
    }
  }
}
function finalize(ctx, schema) {
  var _a3, _b2, _c, _d2, _e;
  const root = ctx.seen.get(schema);
  if (!root)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const flattenRef = (zodSchema) => {
    var _a4, _b3, _c2;
    const seen = ctx.seen.get(zodSchema);
    if (seen.ref === null)
      return;
    const schema2 = (_a4 = seen.def) != null ? _a4 : seen.schema;
    const _cached = { ...schema2 };
    const ref = seen.ref;
    seen.ref = null;
    if (ref) {
      flattenRef(ref);
      const refSeen = ctx.seen.get(ref);
      const refSchema = refSeen.schema;
      if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) {
        schema2.allOf = (_b3 = schema2.allOf) != null ? _b3 : [];
        schema2.allOf.push(refSchema);
      } else {
        Object.assign(schema2, refSchema);
      }
      Object.assign(schema2, _cached);
      const isParentRef = zodSchema._zod.parent === ref;
      if (isParentRef) {
        for (const key in schema2) {
          if (key === "$ref" || key === "allOf")
            continue;
          if (!(key in _cached)) {
            delete schema2[key];
          }
        }
      }
      if (refSchema.$ref && refSeen.def) {
        for (const key in schema2) {
          if (key === "$ref" || key === "allOf")
            continue;
          if (key in refSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(refSeen.def[key])) {
            delete schema2[key];
          }
        }
      }
    }
    const parent = zodSchema._zod.parent;
    if (parent && parent !== ref) {
      flattenRef(parent);
      const parentSeen = ctx.seen.get(parent);
      if (parentSeen == null ? void 0 : parentSeen.schema.$ref) {
        schema2.$ref = parentSeen.schema.$ref;
        if (parentSeen.def) {
          for (const key in schema2) {
            if (key === "$ref" || key === "allOf")
              continue;
            if (key in parentSeen.def && JSON.stringify(schema2[key]) === JSON.stringify(parentSeen.def[key])) {
              delete schema2[key];
            }
          }
        }
      }
    }
    ctx.override({
      zodSchema,
      jsonSchema: schema2,
      path: (_c2 = seen.path) != null ? _c2 : []
    });
  };
  for (const entry of [...ctx.seen.entries()].reverse()) {
    flattenRef(entry[0]);
  }
  const result = {};
  if (ctx.target === "draft-2020-12") {
    result.$schema = "https://json-schema.org/draft/2020-12/schema";
  } else if (ctx.target === "draft-07") {
    result.$schema = "http://json-schema.org/draft-07/schema#";
  } else if (ctx.target === "draft-04") {
    result.$schema = "http://json-schema.org/draft-04/schema#";
  } else if (ctx.target === "openapi-3.0") {
  } else {
  }
  if ((_a3 = ctx.external) == null ? void 0 : _a3.uri) {
    const id = (_b2 = ctx.external.registry.get(schema)) == null ? void 0 : _b2.id;
    if (!id)
      throw new Error("Schema is missing an `id` property");
    result.$id = ctx.external.uri(id);
  }
  Object.assign(result, (_c = root.def) != null ? _c : root.schema);
  const defs = (_e = (_d2 = ctx.external) == null ? void 0 : _d2.defs) != null ? _e : {};
  for (const entry of ctx.seen.entries()) {
    const seen = entry[1];
    if (seen.def && seen.defId) {
      defs[seen.defId] = seen.def;
    }
  }
  if (ctx.external) {
  } else {
    if (Object.keys(defs).length > 0) {
      if (ctx.target === "draft-2020-12") {
        result.$defs = defs;
      } else {
        result.definitions = defs;
      }
    }
  }
  try {
    const finalized = JSON.parse(JSON.stringify(result));
    Object.defineProperty(finalized, "~standard", {
      value: {
        ...schema["~standard"],
        jsonSchema: {
          input: createStandardJSONSchemaMethod(schema, "input", ctx.processors),
          output: createStandardJSONSchemaMethod(schema, "output", ctx.processors)
        }
      },
      enumerable: false,
      writable: false
    });
    return finalized;
  } catch (_err) {
    throw new Error("Error converting schema to JSON.");
  }
}
function isTransforming(_schema, _ctx) {
  const ctx = _ctx != null ? _ctx : { seen: /* @__PURE__ */ new Set() };
  if (ctx.seen.has(_schema))
    return false;
  ctx.seen.add(_schema);
  const def = _schema._zod.def;
  if (def.type === "transform")
    return true;
  if (def.type === "array")
    return isTransforming(def.element, ctx);
  if (def.type === "set")
    return isTransforming(def.valueType, ctx);
  if (def.type === "lazy")
    return isTransforming(def.getter(), ctx);
  if (def.type === "promise" || def.type === "optional" || def.type === "nonoptional" || def.type === "nullable" || def.type === "readonly" || def.type === "default" || def.type === "prefault") {
    return isTransforming(def.innerType, ctx);
  }
  if (def.type === "intersection") {
    return isTransforming(def.left, ctx) || isTransforming(def.right, ctx);
  }
  if (def.type === "record" || def.type === "map") {
    return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx);
  }
  if (def.type === "pipe") {
    return isTransforming(def.in, ctx) || isTransforming(def.out, ctx);
  }
  if (def.type === "object") {
    for (const key in def.shape) {
      if (isTransforming(def.shape[key], ctx))
        return true;
    }
    return false;
  }
  if (def.type === "union") {
    for (const option of def.options) {
      if (isTransforming(option, ctx))
        return true;
    }
    return false;
  }
  if (def.type === "tuple") {
    for (const item of def.items) {
      if (isTransforming(item, ctx))
        return true;
    }
    if (def.rest && isTransforming(def.rest, ctx))
      return true;
    return false;
  }
  return false;
}
var createToJSONSchemaMethod = (schema, processors = {}) => (params) => {
  const ctx = initializeContext({ ...params, processors });
  process2(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
};
var createStandardJSONSchemaMethod = (schema, io, processors = {}) => (params) => {
  const { libraryOptions, target } = params != null ? params : {};
  const ctx = initializeContext({ ...libraryOptions != null ? libraryOptions : {}, target, io, processors });
  process2(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
};

// node_modules/zod/v4/core/json-schema-processors.js
var formatMap = {
  guid: "uuid",
  url: "uri",
  datetime: "date-time",
  json_string: "json-string",
  regex: ""
  // do not set
};
var stringProcessor = (schema, ctx, _json, _params) => {
  var _a3;
  const json2 = _json;
  json2.type = "string";
  const { minimum, maximum, format, patterns, contentEncoding } = schema._zod.bag;
  if (typeof minimum === "number")
    json2.minLength = minimum;
  if (typeof maximum === "number")
    json2.maxLength = maximum;
  if (format) {
    json2.format = (_a3 = formatMap[format]) != null ? _a3 : format;
    if (json2.format === "")
      delete json2.format;
    if (format === "time") {
      delete json2.format;
    }
  }
  if (contentEncoding)
    json2.contentEncoding = contentEncoding;
  if (patterns && patterns.size > 0) {
    const regexes = [...patterns];
    if (regexes.length === 1)
      json2.pattern = regexes[0].source;
    else if (regexes.length > 1) {
      json2.allOf = [
        ...regexes.map((regex) => ({
          ...ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" ? { type: "string" } : {},
          pattern: regex.source
        }))
      ];
    }
  }
};
var numberProcessor = (schema, ctx, _json, _params) => {
  const json2 = _json;
  const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
  if (typeof format === "string" && format.includes("int"))
    json2.type = "integer";
  else
    json2.type = "number";
  if (typeof exclusiveMinimum === "number") {
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json2.minimum = exclusiveMinimum;
      json2.exclusiveMinimum = true;
    } else {
      json2.exclusiveMinimum = exclusiveMinimum;
    }
  }
  if (typeof minimum === "number") {
    json2.minimum = minimum;
    if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") {
      if (exclusiveMinimum >= minimum)
        delete json2.minimum;
      else
        delete json2.exclusiveMinimum;
    }
  }
  if (typeof exclusiveMaximum === "number") {
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json2.maximum = exclusiveMaximum;
      json2.exclusiveMaximum = true;
    } else {
      json2.exclusiveMaximum = exclusiveMaximum;
    }
  }
  if (typeof maximum === "number") {
    json2.maximum = maximum;
    if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") {
      if (exclusiveMaximum <= maximum)
        delete json2.maximum;
      else
        delete json2.exclusiveMaximum;
    }
  }
  if (typeof multipleOf === "number")
    json2.multipleOf = multipleOf;
};
var booleanProcessor = (_schema, _ctx, json2, _params) => {
  json2.type = "boolean";
};
var bigintProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("BigInt cannot be represented in JSON Schema");
  }
};
var symbolProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Symbols cannot be represented in JSON Schema");
  }
};
var nullProcessor = (_schema, ctx, json2, _params) => {
  if (ctx.target === "openapi-3.0") {
    json2.type = "string";
    json2.nullable = true;
    json2.enum = [null];
  } else {
    json2.type = "null";
  }
};
var undefinedProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Undefined cannot be represented in JSON Schema");
  }
};
var voidProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Void cannot be represented in JSON Schema");
  }
};
var neverProcessor = (_schema, _ctx, json2, _params) => {
  json2.not = {};
};
var anyProcessor = (_schema, _ctx, _json, _params) => {
};
var unknownProcessor = (_schema, _ctx, _json, _params) => {
};
var dateProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Date cannot be represented in JSON Schema");
  }
};
var enumProcessor = (schema, _ctx, json2, _params) => {
  const def = schema._zod.def;
  const values = getEnumValues(def.entries);
  if (values.every((v2) => typeof v2 === "number"))
    json2.type = "number";
  if (values.every((v2) => typeof v2 === "string"))
    json2.type = "string";
  json2.enum = values;
};
var literalProcessor = (schema, ctx, json2, _params) => {
  const def = schema._zod.def;
  const vals = [];
  for (const val of def.values) {
    if (val === void 0) {
      if (ctx.unrepresentable === "throw") {
        throw new Error("Literal `undefined` cannot be represented in JSON Schema");
      } else {
      }
    } else if (typeof val === "bigint") {
      if (ctx.unrepresentable === "throw") {
        throw new Error("BigInt literals cannot be represented in JSON Schema");
      } else {
        vals.push(Number(val));
      }
    } else {
      vals.push(val);
    }
  }
  if (vals.length === 0) {
  } else if (vals.length === 1) {
    const val = vals[0];
    json2.type = val === null ? "null" : typeof val;
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json2.enum = [val];
    } else {
      json2.const = val;
    }
  } else {
    if (vals.every((v2) => typeof v2 === "number"))
      json2.type = "number";
    if (vals.every((v2) => typeof v2 === "string"))
      json2.type = "string";
    if (vals.every((v2) => typeof v2 === "boolean"))
      json2.type = "boolean";
    if (vals.every((v2) => v2 === null))
      json2.type = "null";
    json2.enum = vals;
  }
};
var nanProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("NaN cannot be represented in JSON Schema");
  }
};
var templateLiteralProcessor = (schema, _ctx, json2, _params) => {
  const _json = json2;
  const pattern = schema._zod.pattern;
  if (!pattern)
    throw new Error("Pattern not found in template literal");
  _json.type = "string";
  _json.pattern = pattern.source;
};
var fileProcessor = (schema, _ctx, json2, _params) => {
  const _json = json2;
  const file2 = {
    type: "string",
    format: "binary",
    contentEncoding: "binary"
  };
  const { minimum, maximum, mime } = schema._zod.bag;
  if (minimum !== void 0)
    file2.minLength = minimum;
  if (maximum !== void 0)
    file2.maxLength = maximum;
  if (mime) {
    if (mime.length === 1) {
      file2.contentMediaType = mime[0];
      Object.assign(_json, file2);
    } else {
      Object.assign(_json, file2);
      _json.anyOf = mime.map((m2) => ({ contentMediaType: m2 }));
    }
  } else {
    Object.assign(_json, file2);
  }
};
var successProcessor = (_schema, _ctx, json2, _params) => {
  json2.type = "boolean";
};
var customProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Custom types cannot be represented in JSON Schema");
  }
};
var functionProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Function types cannot be represented in JSON Schema");
  }
};
var transformProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Transforms cannot be represented in JSON Schema");
  }
};
var mapProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Map cannot be represented in JSON Schema");
  }
};
var setProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Set cannot be represented in JSON Schema");
  }
};
var arrayProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json2.minItems = minimum;
  if (typeof maximum === "number")
    json2.maxItems = maximum;
  json2.type = "array";
  json2.items = process2(def.element, ctx, { ...params, path: [...params.path, "items"] });
};
var objectProcessor = (schema, ctx, _json, params) => {
  var _a3;
  const json2 = _json;
  const def = schema._zod.def;
  json2.type = "object";
  json2.properties = {};
  const shape = def.shape;
  for (const key in shape) {
    json2.properties[key] = process2(shape[key], ctx, {
      ...params,
      path: [...params.path, "properties", key]
    });
  }
  const allKeys = new Set(Object.keys(shape));
  const requiredKeys = new Set([...allKeys].filter((key) => {
    const v2 = def.shape[key]._zod;
    if (ctx.io === "input") {
      return v2.optin === void 0;
    } else {
      return v2.optout === void 0;
    }
  }));
  if (requiredKeys.size > 0) {
    json2.required = Array.from(requiredKeys);
  }
  if (((_a3 = def.catchall) == null ? void 0 : _a3._zod.def.type) === "never") {
    json2.additionalProperties = false;
  } else if (!def.catchall) {
    if (ctx.io === "output")
      json2.additionalProperties = false;
  } else if (def.catchall) {
    json2.additionalProperties = process2(def.catchall, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
};
var unionProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  const isExclusive = def.inclusive === false;
  const options = def.options.map((x, i2) => process2(x, ctx, {
    ...params,
    path: [...params.path, isExclusive ? "oneOf" : "anyOf", i2]
  }));
  if (isExclusive) {
    json2.oneOf = options;
  } else {
    json2.anyOf = options;
  }
};
var intersectionProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  const a2 = process2(def.left, ctx, {
    ...params,
    path: [...params.path, "allOf", 0]
  });
  const b10 = process2(def.right, ctx, {
    ...params,
    path: [...params.path, "allOf", 1]
  });
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
  const allOf = [
    ...isSimpleIntersection(a2) ? a2.allOf : [a2],
    ...isSimpleIntersection(b10) ? b10.allOf : [b10]
  ];
  json2.allOf = allOf;
};
var tupleProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  json2.type = "array";
  const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items";
  const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems";
  const prefixItems = def.items.map((x, i2) => process2(x, ctx, {
    ...params,
    path: [...params.path, prefixPath, i2]
  }));
  const rest = def.rest ? process2(def.rest, ctx, {
    ...params,
    path: [...params.path, restPath, ...ctx.target === "openapi-3.0" ? [def.items.length] : []]
  }) : null;
  if (ctx.target === "draft-2020-12") {
    json2.prefixItems = prefixItems;
    if (rest) {
      json2.items = rest;
    }
  } else if (ctx.target === "openapi-3.0") {
    json2.items = {
      anyOf: prefixItems
    };
    if (rest) {
      json2.items.anyOf.push(rest);
    }
    json2.minItems = prefixItems.length;
    if (!rest) {
      json2.maxItems = prefixItems.length;
    }
  } else {
    json2.items = prefixItems;
    if (rest) {
      json2.additionalItems = rest;
    }
  }
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json2.minItems = minimum;
  if (typeof maximum === "number")
    json2.maxItems = maximum;
};
var recordProcessor = (schema, ctx, _json, params) => {
  const json2 = _json;
  const def = schema._zod.def;
  json2.type = "object";
  const keyType = def.keyType;
  const keyBag = keyType._zod.bag;
  const patterns = keyBag == null ? void 0 : keyBag.patterns;
  if (def.mode === "loose" && patterns && patterns.size > 0) {
    const valueSchema = process2(def.valueType, ctx, {
      ...params,
      path: [...params.path, "patternProperties", "*"]
    });
    json2.patternProperties = {};
    for (const pattern of patterns) {
      json2.patternProperties[pattern.source] = valueSchema;
    }
  } else {
    if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
      json2.propertyNames = process2(def.keyType, ctx, {
        ...params,
        path: [...params.path, "propertyNames"]
      });
    }
    json2.additionalProperties = process2(def.valueType, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
  const keyValues = keyType._zod.values;
  if (keyValues) {
    const validKeyValues = [...keyValues].filter((v2) => typeof v2 === "string" || typeof v2 === "number");
    if (validKeyValues.length > 0) {
      json2.required = validKeyValues;
    }
  }
};
var nullableProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  const inner = process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  if (ctx.target === "openapi-3.0") {
    seen.ref = def.innerType;
    json2.nullable = true;
  } else {
    json2.anyOf = [inner, { type: "null" }];
  }
};
var nonoptionalProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var defaultProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json2.default = JSON.parse(JSON.stringify(def.defaultValue));
};
var prefaultProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  if (ctx.io === "input")
    json2._prefault = JSON.parse(JSON.stringify(def.defaultValue));
};
var catchProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  let catchValue;
  try {
    catchValue = def.catchValue(void 0);
  } catch (e2) {
    throw new Error("Dynamic catch values are not supported in JSON Schema");
  }
  json2.default = catchValue;
};
var pipeProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  const innerType = ctx.io === "input" ? def.in._zod.def.type === "transform" ? def.out : def.in : def.out;
  process2(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var readonlyProcessor = (schema, ctx, json2, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json2.readOnly = true;
};
var promiseProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var optionalProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
};
var lazyProcessor = (schema, ctx, _json, params) => {
  const innerType = schema._zod.innerType;
  process2(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var allProcessors = {
  string: stringProcessor,
  number: numberProcessor,
  boolean: booleanProcessor,
  bigint: bigintProcessor,
  symbol: symbolProcessor,
  null: nullProcessor,
  undefined: undefinedProcessor,
  void: voidProcessor,
  never: neverProcessor,
  any: anyProcessor,
  unknown: unknownProcessor,
  date: dateProcessor,
  enum: enumProcessor,
  literal: literalProcessor,
  nan: nanProcessor,
  template_literal: templateLiteralProcessor,
  file: fileProcessor,
  success: successProcessor,
  custom: customProcessor,
  function: functionProcessor,
  transform: transformProcessor,
  map: mapProcessor,
  set: setProcessor,
  array: arrayProcessor,
  object: objectProcessor,
  union: unionProcessor,
  intersection: intersectionProcessor,
  tuple: tupleProcessor,
  record: recordProcessor,
  nullable: nullableProcessor,
  nonoptional: nonoptionalProcessor,
  default: defaultProcessor,
  prefault: prefaultProcessor,
  catch: catchProcessor,
  pipe: pipeProcessor,
  readonly: readonlyProcessor,
  promise: promiseProcessor,
  optional: optionalProcessor,
  lazy: lazyProcessor
};
function toJSONSchema(input, params) {
  if ("_idmap" in input) {
    const registry2 = input;
    const ctx2 = initializeContext({ ...params, processors: allProcessors });
    const defs = {};
    for (const entry of registry2._idmap.entries()) {
      const [_10, schema] = entry;
      process2(schema, ctx2);
    }
    const schemas = {};
    const external = {
      registry: registry2,
      uri: params == null ? void 0 : params.uri,
      defs
    };
    ctx2.external = external;
    for (const entry of registry2._idmap.entries()) {
      const [key, schema] = entry;
      extractDefs(ctx2, schema);
      schemas[key] = finalize(ctx2, schema);
    }
    if (Object.keys(defs).length > 0) {
      const defsSegment = ctx2.target === "draft-2020-12" ? "$defs" : "definitions";
      schemas.__shared = {
        [defsSegment]: defs
      };
    }
    return { schemas };
  }
  const ctx = initializeContext({ ...params, processors: allProcessors });
  process2(input, ctx);
  extractDefs(ctx, input);
  return finalize(ctx, input);
}

// node_modules/zod/v4/core/json-schema-generator.js
var JSONSchemaGenerator = class {
  /** @deprecated Access via ctx instead */
  get metadataRegistry() {
    return this.ctx.metadataRegistry;
  }
  /** @deprecated Access via ctx instead */
  get target() {
    return this.ctx.target;
  }
  /** @deprecated Access via ctx instead */
  get unrepresentable() {
    return this.ctx.unrepresentable;
  }
  /** @deprecated Access via ctx instead */
  get override() {
    return this.ctx.override;
  }
  /** @deprecated Access via ctx instead */
  get io() {
    return this.ctx.io;
  }
  /** @deprecated Access via ctx instead */
  get counter() {
    return this.ctx.counter;
  }
  set counter(value) {
    this.ctx.counter = value;
  }
  /** @deprecated Access via ctx instead */
  get seen() {
    return this.ctx.seen;
  }
  constructor(params) {
    var _a3;
    let normalizedTarget = (_a3 = params == null ? void 0 : params.target) != null ? _a3 : "draft-2020-12";
    if (normalizedTarget === "draft-4")
      normalizedTarget = "draft-04";
    if (normalizedTarget === "draft-7")
      normalizedTarget = "draft-07";
    this.ctx = initializeContext({
      processors: allProcessors,
      target: normalizedTarget,
      ...(params == null ? void 0 : params.metadata) && { metadata: params.metadata },
      ...(params == null ? void 0 : params.unrepresentable) && { unrepresentable: params.unrepresentable },
      ...(params == null ? void 0 : params.override) && { override: params.override },
      ...(params == null ? void 0 : params.io) && { io: params.io }
    });
  }
  /**
   * Process a schema to prepare it for JSON Schema generation.
   * This must be called before emit().
   */
  process(schema, _params = { path: [], schemaPath: [] }) {
    return process2(schema, this.ctx, _params);
  }
  /**
   * Emit the final JSON Schema after processing.
   * Must call process() first.
   */
  emit(schema, _params) {
    if (_params) {
      if (_params.cycles)
        this.ctx.cycles = _params.cycles;
      if (_params.reused)
        this.ctx.reused = _params.reused;
      if (_params.external)
        this.ctx.external = _params.external;
    }
    extractDefs(this.ctx, schema);
    const result = finalize(this.ctx, schema);
    const { "~standard": _10, ...plainResult } = result;
    return plainResult;
  }
};

// node_modules/zod/v4/core/json-schema.js
var json_schema_exports = {};

// node_modules/zod/v4/mini/schemas.js
var ZodMiniType = /* @__PURE__ */ $constructor("ZodMiniType", (inst, def) => {
  if (!inst._zod)
    throw new Error("Uninitialized schema in ZodMiniType.");
  $ZodType.init(inst, def);
  inst.def = def;
  inst.type = def.type;
  inst.parse = (data, params) => parse(inst, data, params, { callee: inst.parse });
  inst.safeParse = (data, params) => safeParse(inst, data, params);
  inst.parseAsync = async (data, params) => parseAsync(inst, data, params, { callee: inst.parseAsync });
  inst.safeParseAsync = async (data, params) => safeParseAsync(inst, data, params);
  inst.check = (...checks) => {
    var _a3;
    return inst.clone({
      ...def,
      checks: [
        ...(_a3 = def.checks) != null ? _a3 : [],
        ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
      ]
    }, { parent: true });
  };
  inst.with = inst.check;
  inst.clone = (_def, params) => clone(inst, _def, params);
  inst.brand = () => inst;
  inst.register = ((reg, meta3) => {
    reg.add(inst, meta3);
    return inst;
  });
  inst.apply = (fn) => fn(inst);
});
var ZodMiniString = /* @__PURE__ */ $constructor("ZodMiniString", (inst, def) => {
  $ZodString.init(inst, def);
  ZodMiniType.init(inst, def);
});
var ZodMiniStringFormat = /* @__PURE__ */ $constructor("ZodMiniStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  ZodMiniString.init(inst, def);
});
var ZodMiniNumber = /* @__PURE__ */ $constructor("ZodMiniNumber", (inst, def) => {
  $ZodNumber.init(inst, def);
  ZodMiniType.init(inst, def);
});
var ZodMiniBoolean = /* @__PURE__ */ $constructor("ZodMiniBoolean", (inst, def) => {
  $ZodBoolean.init(inst, def);
  ZodMiniType.init(inst, def);
});
var ZodMiniBigInt = /* @__PURE__ */ $constructor("ZodMiniBigInt", (inst, def) => {
  $ZodBigInt.init(inst, def);
  ZodMiniType.init(inst, def);
});
var ZodMiniDate = /* @__PURE__ */ $constructor("ZodMiniDate", (inst, def) => {
  $ZodDate.init(inst, def);
  ZodMiniType.init(inst, def);
});

// node_modules/zod/v4/mini/iso.js
var iso_exports = {};
__export(iso_exports, {
  ZodMiniISODate: () => ZodMiniISODate,
  ZodMiniISODateTime: () => ZodMiniISODateTime,
  ZodMiniISODuration: () => ZodMiniISODuration,
  ZodMiniISOTime: () => ZodMiniISOTime,
  date: () => date2,
  datetime: () => datetime2,
  duration: () => duration2,
  time: () => time2
});
var ZodMiniISODateTime = /* @__PURE__ */ $constructor("ZodMiniISODateTime", (inst, def) => {
  $ZodISODateTime.init(inst, def);
  ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
function datetime2(params) {
  return _isoDateTime(ZodMiniISODateTime, params);
}
var ZodMiniISODate = /* @__PURE__ */ $constructor("ZodMiniISODate", (inst, def) => {
  $ZodISODate.init(inst, def);
  ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
function date2(params) {
  return _isoDate(ZodMiniISODate, params);
}
var ZodMiniISOTime = /* @__PURE__ */ $constructor("ZodMiniISOTime", (inst, def) => {
  $ZodISOTime.init(inst, def);
  ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
function time2(params) {
  return _isoTime(ZodMiniISOTime, params);
}
var ZodMiniISODuration = /* @__PURE__ */ $constructor("ZodMiniISODuration", (inst, def) => {
  $ZodISODuration.init(inst, def);
  ZodMiniStringFormat.init(inst, def);
});
// @__NO_SIDE_EFFECTS__
function duration2(params) {
  return _isoDuration(ZodMiniISODuration, params);
}

// node_modules/zod/v4/mini/coerce.js
var coerce_exports = {};
__export(coerce_exports, {
  bigint: () => bigint2,
  boolean: () => boolean2,
  date: () => date3,
  number: () => number2,
  string: () => string2
});
// @__NO_SIDE_EFFECTS__
function string2(params) {
  return _coercedString(ZodMiniString, params);
}
// @__NO_SIDE_EFFECTS__
function number2(params) {
  return _coercedNumber(ZodMiniNumber, params);
}
// @__NO_SIDE_EFFECTS__
function boolean2(params) {
  return _coercedBoolean(ZodMiniBoolean, params);
}
// @__NO_SIDE_EFFECTS__
function bigint2(params) {
  return _coercedBigint(ZodMiniBigInt, params);
}
// @__NO_SIDE_EFFECTS__
function date3(params) {
  return _coercedDate(ZodMiniDate, params);
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
function isZ4Schema(s4) {
  const schema = s4;
  return !!schema._zod;
}
function safeParse2(schema, data) {
  if (isZ4Schema(schema)) {
    const result2 = safeParse(schema, data);
    return result2;
  }
  const v3Schema = schema;
  const result = v3Schema.safeParse(data);
  return result;
}
function getObjectShape(schema) {
  var _a3, _b2;
  if (!schema)
    return void 0;
  let rawShape;
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    rawShape = (_b2 = (_a3 = v4Schema._zod) == null ? void 0 : _a3.def) == null ? void 0 : _b2.shape;
  } else {
    const v3Schema = schema;
    rawShape = v3Schema.shape;
  }
  if (!rawShape)
    return void 0;
  if (typeof rawShape === "function") {
    try {
      return rawShape();
    } catch (e2) {
      return void 0;
    }
  }
  return rawShape;
}
function getLiteralValue(schema) {
  var _a3;
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    const def2 = (_a3 = v4Schema._zod) == null ? void 0 : _a3.def;
    if (def2) {
      if (def2.value !== void 0)
        return def2.value;
      if (Array.isArray(def2.values) && def2.values.length > 0) {
        return def2.values[0];
      }
    }
  }
  const v3Schema = schema;
  const def = v3Schema._def;
  if (def) {
    if (def.value !== void 0)
      return def.value;
    if (Array.isArray(def.values) && def.values.length > 0) {
      return def.values[0];
    }
  }
  const directValue = schema.value;
  if (directValue !== void 0)
    return directValue;
  return void 0;
}

// node_modules/zod/v4/classic/schemas.js
var schemas_exports3 = {};
__export(schemas_exports3, {
  ZodAny: () => ZodAny2,
  ZodArray: () => ZodArray2,
  ZodBase64: () => ZodBase64,
  ZodBase64URL: () => ZodBase64URL,
  ZodBigInt: () => ZodBigInt2,
  ZodBigIntFormat: () => ZodBigIntFormat,
  ZodBoolean: () => ZodBoolean2,
  ZodCIDRv4: () => ZodCIDRv4,
  ZodCIDRv6: () => ZodCIDRv6,
  ZodCUID: () => ZodCUID,
  ZodCUID2: () => ZodCUID2,
  ZodCatch: () => ZodCatch2,
  ZodCodec: () => ZodCodec,
  ZodCustom: () => ZodCustom,
  ZodCustomStringFormat: () => ZodCustomStringFormat,
  ZodDate: () => ZodDate2,
  ZodDefault: () => ZodDefault2,
  ZodDiscriminatedUnion: () => ZodDiscriminatedUnion2,
  ZodE164: () => ZodE164,
  ZodEmail: () => ZodEmail,
  ZodEmoji: () => ZodEmoji,
  ZodEnum: () => ZodEnum2,
  ZodExactOptional: () => ZodExactOptional,
  ZodFile: () => ZodFile,
  ZodFunction: () => ZodFunction2,
  ZodGUID: () => ZodGUID,
  ZodIPv4: () => ZodIPv4,
  ZodIPv6: () => ZodIPv6,
  ZodIntersection: () => ZodIntersection2,
  ZodJWT: () => ZodJWT,
  ZodKSUID: () => ZodKSUID,
  ZodLazy: () => ZodLazy2,
  ZodLiteral: () => ZodLiteral2,
  ZodMAC: () => ZodMAC,
  ZodMap: () => ZodMap2,
  ZodNaN: () => ZodNaN2,
  ZodNanoID: () => ZodNanoID,
  ZodNever: () => ZodNever2,
  ZodNonOptional: () => ZodNonOptional,
  ZodNull: () => ZodNull2,
  ZodNullable: () => ZodNullable2,
  ZodNumber: () => ZodNumber2,
  ZodNumberFormat: () => ZodNumberFormat,
  ZodObject: () => ZodObject2,
  ZodOptional: () => ZodOptional2,
  ZodPipe: () => ZodPipe,
  ZodPrefault: () => ZodPrefault,
  ZodPromise: () => ZodPromise2,
  ZodReadonly: () => ZodReadonly2,
  ZodRecord: () => ZodRecord2,
  ZodSet: () => ZodSet2,
  ZodString: () => ZodString2,
  ZodStringFormat: () => ZodStringFormat,
  ZodSuccess: () => ZodSuccess,
  ZodSymbol: () => ZodSymbol2,
  ZodTemplateLiteral: () => ZodTemplateLiteral,
  ZodTransform: () => ZodTransform,
  ZodTuple: () => ZodTuple2,
  ZodType: () => ZodType2,
  ZodULID: () => ZodULID,
  ZodURL: () => ZodURL,
  ZodUUID: () => ZodUUID,
  ZodUndefined: () => ZodUndefined2,
  ZodUnion: () => ZodUnion2,
  ZodUnknown: () => ZodUnknown2,
  ZodVoid: () => ZodVoid2,
  ZodXID: () => ZodXID,
  ZodXor: () => ZodXor,
  _ZodString: () => _ZodString,
  _default: () => _default2,
  _function: () => _function,
  any: () => any,
  array: () => array,
  base64: () => base642,
  base64url: () => base64url2,
  bigint: () => bigint3,
  boolean: () => boolean3,
  catch: () => _catch2,
  check: () => check,
  cidrv4: () => cidrv42,
  cidrv6: () => cidrv62,
  codec: () => codec,
  cuid: () => cuid3,
  cuid2: () => cuid22,
  custom: () => custom,
  date: () => date5,
  describe: () => describe2,
  discriminatedUnion: () => discriminatedUnion,
  e164: () => e1642,
  email: () => email2,
  emoji: () => emoji2,
  enum: () => _enum2,
  exactOptional: () => exactOptional,
  file: () => file,
  float32: () => float32,
  float64: () => float64,
  function: () => _function,
  guid: () => guid2,
  hash: () => hash,
  hex: () => hex2,
  hostname: () => hostname3,
  httpUrl: () => httpUrl,
  instanceof: () => _instanceof,
  int: () => int,
  int32: () => int32,
  int64: () => int64,
  intersection: () => intersection,
  ipv4: () => ipv42,
  ipv6: () => ipv62,
  json: () => json,
  jwt: () => jwt,
  keyof: () => keyof,
  ksuid: () => ksuid2,
  lazy: () => lazy,
  literal: () => literal,
  looseObject: () => looseObject,
  looseRecord: () => looseRecord,
  mac: () => mac2,
  map: () => map,
  meta: () => meta2,
  nan: () => nan,
  nanoid: () => nanoid2,
  nativeEnum: () => nativeEnum,
  never: () => never,
  nonoptional: () => nonoptional,
  null: () => _null3,
  nullable: () => nullable,
  nullish: () => nullish2,
  number: () => number3,
  object: () => object2,
  optional: () => optional,
  partialRecord: () => partialRecord,
  pipe: () => pipe,
  prefault: () => prefault,
  preprocess: () => preprocess,
  promise: () => promise,
  readonly: () => readonly,
  record: () => record,
  refine: () => refine,
  set: () => set,
  strictObject: () => strictObject,
  string: () => string3,
  stringFormat: () => stringFormat,
  stringbool: () => stringbool,
  success: () => success,
  superRefine: () => superRefine,
  symbol: () => symbol,
  templateLiteral: () => templateLiteral,
  transform: () => transform,
  tuple: () => tuple,
  uint32: () => uint32,
  uint64: () => uint64,
  ulid: () => ulid2,
  undefined: () => _undefined3,
  union: () => union,
  unknown: () => unknown,
  url: () => url,
  uuid: () => uuid2,
  uuidv4: () => uuidv4,
  uuidv6: () => uuidv6,
  uuidv7: () => uuidv7,
  void: () => _void2,
  xid: () => xid2,
  xor: () => xor
});

// node_modules/zod/v4/classic/checks.js
var checks_exports2 = {};
__export(checks_exports2, {
  endsWith: () => _endsWith,
  gt: () => _gt,
  gte: () => _gte,
  includes: () => _includes,
  length: () => _length,
  lowercase: () => _lowercase,
  lt: () => _lt,
  lte: () => _lte,
  maxLength: () => _maxLength,
  maxSize: () => _maxSize,
  mime: () => _mime,
  minLength: () => _minLength,
  minSize: () => _minSize,
  multipleOf: () => _multipleOf,
  negative: () => _negative,
  nonnegative: () => _nonnegative,
  nonpositive: () => _nonpositive,
  normalize: () => _normalize,
  overwrite: () => _overwrite,
  positive: () => _positive,
  property: () => _property,
  regex: () => _regex,
  size: () => _size,
  slugify: () => _slugify,
  startsWith: () => _startsWith,
  toLowerCase: () => _toLowerCase,
  toUpperCase: () => _toUpperCase,
  trim: () => _trim,
  uppercase: () => _uppercase
});

// node_modules/zod/v4/classic/iso.js
var iso_exports2 = {};
__export(iso_exports2, {
  ZodISODate: () => ZodISODate,
  ZodISODateTime: () => ZodISODateTime,
  ZodISODuration: () => ZodISODuration,
  ZodISOTime: () => ZodISOTime,
  date: () => date4,
  datetime: () => datetime3,
  duration: () => duration3,
  time: () => time3
});
var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
  $ZodISODateTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function datetime3(params) {
  return _isoDateTime(ZodISODateTime, params);
}
var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
  $ZodISODate.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function date4(params) {
  return _isoDate(ZodISODate, params);
}
var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
  $ZodISOTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function time3(params) {
  return _isoTime(ZodISOTime, params);
}
var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
  $ZodISODuration.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function duration3(params) {
  return _isoDuration(ZodISODuration, params);
}

// node_modules/zod/v4/classic/errors.js
var initializer2 = (inst, issues) => {
  $ZodError.init(inst, issues);
  inst.name = "ZodError";
  Object.defineProperties(inst, {
    format: {
      value: (mapper) => formatError(inst, mapper)
      // enumerable: false,
    },
    flatten: {
      value: (mapper) => flattenError(inst, mapper)
      // enumerable: false,
    },
    addIssue: {
      value: (issue2) => {
        inst.issues.push(issue2);
        inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
      }
      // enumerable: false,
    },
    addIssues: {
      value: (issues2) => {
        inst.issues.push(...issues2);
        inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2);
      }
      // enumerable: false,
    },
    isEmpty: {
      get() {
        return inst.issues.length === 0;
      }
      // enumerable: false,
    }
  });
};
var ZodError2 = $constructor("ZodError", initializer2);
var ZodRealError = $constructor("ZodError", initializer2, {
  Parent: Error
});

// node_modules/zod/v4/classic/parse.js
var parse2 = /* @__PURE__ */ _parse(ZodRealError);
var parseAsync2 = /* @__PURE__ */ _parseAsync(ZodRealError);
var safeParse3 = /* @__PURE__ */ _safeParse(ZodRealError);
var safeParseAsync2 = /* @__PURE__ */ _safeParseAsync(ZodRealError);
var encode2 = /* @__PURE__ */ _encode(ZodRealError);
var decode2 = /* @__PURE__ */ _decode(ZodRealError);
var encodeAsync2 = /* @__PURE__ */ _encodeAsync(ZodRealError);
var decodeAsync2 = /* @__PURE__ */ _decodeAsync(ZodRealError);
var safeEncode2 = /* @__PURE__ */ _safeEncode(ZodRealError);
var safeDecode2 = /* @__PURE__ */ _safeDecode(ZodRealError);
var safeEncodeAsync2 = /* @__PURE__ */ _safeEncodeAsync(ZodRealError);
var safeDecodeAsync2 = /* @__PURE__ */ _safeDecodeAsync(ZodRealError);

// node_modules/zod/v4/classic/schemas.js
var ZodType2 = /* @__PURE__ */ $constructor("ZodType", (inst, def) => {
  $ZodType.init(inst, def);
  Object.assign(inst["~standard"], {
    jsonSchema: {
      input: createStandardJSONSchemaMethod(inst, "input"),
      output: createStandardJSONSchemaMethod(inst, "output")
    }
  });
  inst.toJSONSchema = createToJSONSchemaMethod(inst, {});
  inst.def = def;
  inst.type = def.type;
  Object.defineProperty(inst, "_def", { value: def });
  inst.check = (...checks) => {
    var _a3;
    return inst.clone(util_exports.mergeDefs(def, {
      checks: [
        ...(_a3 = def.checks) != null ? _a3 : [],
        ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
      ]
    }), {
      parent: true
    });
  };
  inst.with = inst.check;
  inst.clone = (def2, params) => clone(inst, def2, params);
  inst.brand = () => inst;
  inst.register = ((reg, meta3) => {
    reg.add(inst, meta3);
    return inst;
  });
  inst.parse = (data, params) => parse2(inst, data, params, { callee: inst.parse });
  inst.safeParse = (data, params) => safeParse3(inst, data, params);
  inst.parseAsync = async (data, params) => parseAsync2(inst, data, params, { callee: inst.parseAsync });
  inst.safeParseAsync = async (data, params) => safeParseAsync2(inst, data, params);
  inst.spa = inst.safeParseAsync;
  inst.encode = (data, params) => encode2(inst, data, params);
  inst.decode = (data, params) => decode2(inst, data, params);
  inst.encodeAsync = async (data, params) => encodeAsync2(inst, data, params);
  inst.decodeAsync = async (data, params) => decodeAsync2(inst, data, params);
  inst.safeEncode = (data, params) => safeEncode2(inst, data, params);
  inst.safeDecode = (data, params) => safeDecode2(inst, data, params);
  inst.safeEncodeAsync = async (data, params) => safeEncodeAsync2(inst, data, params);
  inst.safeDecodeAsync = async (data, params) => safeDecodeAsync2(inst, data, params);
  inst.refine = (check2, params) => inst.check(refine(check2, params));
  inst.superRefine = (refinement) => inst.check(superRefine(refinement));
  inst.overwrite = (fn) => inst.check(_overwrite(fn));
  inst.optional = () => optional(inst);
  inst.exactOptional = () => exactOptional(inst);
  inst.nullable = () => nullable(inst);
  inst.nullish = () => optional(nullable(inst));
  inst.nonoptional = (params) => nonoptional(inst, params);
  inst.array = () => array(inst);
  inst.or = (arg) => union([inst, arg]);
  inst.and = (arg) => intersection(inst, arg);
  inst.transform = (tx) => pipe(inst, transform(tx));
  inst.default = (def2) => _default2(inst, def2);
  inst.prefault = (def2) => prefault(inst, def2);
  inst.catch = (params) => _catch2(inst, params);
  inst.pipe = (target) => pipe(inst, target);
  inst.readonly = () => readonly(inst);
  inst.describe = (description) => {
    const cl = inst.clone();
    globalRegistry.add(cl, { description });
    return cl;
  };
  Object.defineProperty(inst, "description", {
    get() {
      var _a3;
      return (_a3 = globalRegistry.get(inst)) == null ? void 0 : _a3.description;
    },
    configurable: true
  });
  inst.meta = (...args) => {
    if (args.length === 0) {
      return globalRegistry.get(inst);
    }
    const cl = inst.clone();
    globalRegistry.add(cl, args[0]);
    return cl;
  };
  inst.isOptional = () => inst.safeParse(void 0).success;
  inst.isNullable = () => inst.safeParse(null).success;
  inst.apply = (fn) => fn(inst);
  return inst;
});
var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
  var _a3, _b2, _c;
  $ZodString.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => stringProcessor(inst, ctx, json2, params);
  const bag = inst._zod.bag;
  inst.format = (_a3 = bag.format) != null ? _a3 : null;
  inst.minLength = (_b2 = bag.minimum) != null ? _b2 : null;
  inst.maxLength = (_c = bag.maximum) != null ? _c : null;
  inst.regex = (...args) => inst.check(_regex(...args));
  inst.includes = (...args) => inst.check(_includes(...args));
  inst.startsWith = (...args) => inst.check(_startsWith(...args));
  inst.endsWith = (...args) => inst.check(_endsWith(...args));
  inst.min = (...args) => inst.check(_minLength(...args));
  inst.max = (...args) => inst.check(_maxLength(...args));
  inst.length = (...args) => inst.check(_length(...args));
  inst.nonempty = (...args) => inst.check(_minLength(1, ...args));
  inst.lowercase = (params) => inst.check(_lowercase(params));
  inst.uppercase = (params) => inst.check(_uppercase(params));
  inst.trim = () => inst.check(_trim());
  inst.normalize = (...args) => inst.check(_normalize(...args));
  inst.toLowerCase = () => inst.check(_toLowerCase());
  inst.toUpperCase = () => inst.check(_toUpperCase());
  inst.slugify = () => inst.check(_slugify());
});
var ZodString2 = /* @__PURE__ */ $constructor("ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  _ZodString.init(inst, def);
  inst.email = (params) => inst.check(_email(ZodEmail, params));
  inst.url = (params) => inst.check(_url(ZodURL, params));
  inst.jwt = (params) => inst.check(_jwt(ZodJWT, params));
  inst.emoji = (params) => inst.check(_emoji2(ZodEmoji, params));
  inst.guid = (params) => inst.check(_guid(ZodGUID, params));
  inst.uuid = (params) => inst.check(_uuid(ZodUUID, params));
  inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params));
  inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params));
  inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params));
  inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params));
  inst.guid = (params) => inst.check(_guid(ZodGUID, params));
  inst.cuid = (params) => inst.check(_cuid(ZodCUID, params));
  inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params));
  inst.ulid = (params) => inst.check(_ulid(ZodULID, params));
  inst.base64 = (params) => inst.check(_base64(ZodBase64, params));
  inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params));
  inst.xid = (params) => inst.check(_xid(ZodXID, params));
  inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params));
  inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params));
  inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params));
  inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params));
  inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params));
  inst.e164 = (params) => inst.check(_e164(ZodE164, params));
  inst.datetime = (params) => inst.check(datetime3(params));
  inst.date = (params) => inst.check(date4(params));
  inst.time = (params) => inst.check(time3(params));
  inst.duration = (params) => inst.check(duration3(params));
});
function string3(params) {
  return _string(ZodString2, params);
}
var ZodStringFormat = /* @__PURE__ */ $constructor("ZodStringFormat", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  _ZodString.init(inst, def);
});
var ZodEmail = /* @__PURE__ */ $constructor("ZodEmail", (inst, def) => {
  $ZodEmail.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function email2(params) {
  return _email(ZodEmail, params);
}
var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
  $ZodGUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function guid2(params) {
  return _guid(ZodGUID, params);
}
var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
  $ZodUUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function uuid2(params) {
  return _uuid(ZodUUID, params);
}
function uuidv4(params) {
  return _uuidv4(ZodUUID, params);
}
function uuidv6(params) {
  return _uuidv6(ZodUUID, params);
}
function uuidv7(params) {
  return _uuidv7(ZodUUID, params);
}
var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
  $ZodURL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function url(params) {
  return _url(ZodURL, params);
}
function httpUrl(params) {
  return _url(ZodURL, {
    protocol: /^https?$/,
    hostname: regexes_exports.domain,
    ...util_exports.normalizeParams(params)
  });
}
var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
  $ZodEmoji.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function emoji2(params) {
  return _emoji2(ZodEmoji, params);
}
var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
  $ZodNanoID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function nanoid2(params) {
  return _nanoid(ZodNanoID, params);
}
var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
  $ZodCUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cuid3(params) {
  return _cuid(ZodCUID, params);
}
var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
  $ZodCUID2.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cuid22(params) {
  return _cuid2(ZodCUID2, params);
}
var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
  $ZodULID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ulid2(params) {
  return _ulid(ZodULID, params);
}
var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
  $ZodXID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function xid2(params) {
  return _xid(ZodXID, params);
}
var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
  $ZodKSUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ksuid2(params) {
  return _ksuid(ZodKSUID, params);
}
var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
  $ZodIPv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ipv42(params) {
  return _ipv4(ZodIPv4, params);
}
var ZodMAC = /* @__PURE__ */ $constructor("ZodMAC", (inst, def) => {
  $ZodMAC.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function mac2(params) {
  return _mac(ZodMAC, params);
}
var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
  $ZodIPv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function ipv62(params) {
  return _ipv6(ZodIPv6, params);
}
var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
  $ZodCIDRv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cidrv42(params) {
  return _cidrv4(ZodCIDRv4, params);
}
var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
  $ZodCIDRv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function cidrv62(params) {
  return _cidrv6(ZodCIDRv6, params);
}
var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
  $ZodBase64.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function base642(params) {
  return _base64(ZodBase64, params);
}
var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
  $ZodBase64URL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function base64url2(params) {
  return _base64url(ZodBase64URL, params);
}
var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
  $ZodE164.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function e1642(params) {
  return _e164(ZodE164, params);
}
var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
  $ZodJWT.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function jwt(params) {
  return _jwt(ZodJWT, params);
}
var ZodCustomStringFormat = /* @__PURE__ */ $constructor("ZodCustomStringFormat", (inst, def) => {
  $ZodCustomStringFormat.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function stringFormat(format, fnOrRegex, _params = {}) {
  return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params);
}
function hostname3(_params) {
  return _stringFormat(ZodCustomStringFormat, "hostname", regexes_exports.hostname, _params);
}
function hex2(_params) {
  return _stringFormat(ZodCustomStringFormat, "hex", regexes_exports.hex, _params);
}
function hash(alg, params) {
  var _a3;
  const enc = (_a3 = params == null ? void 0 : params.enc) != null ? _a3 : "hex";
  const format = `${alg}_${enc}`;
  const regex = regexes_exports[format];
  if (!regex)
    throw new Error(`Unrecognized hash format: ${format}`);
  return _stringFormat(ZodCustomStringFormat, format, regex, params);
}
var ZodNumber2 = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i;
  $ZodNumber.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => numberProcessor(inst, ctx, json2, params);
  inst.gt = (value, params) => inst.check(_gt(value, params));
  inst.gte = (value, params) => inst.check(_gte(value, params));
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.lt = (value, params) => inst.check(_lt(value, params));
  inst.lte = (value, params) => inst.check(_lte(value, params));
  inst.max = (value, params) => inst.check(_lte(value, params));
  inst.int = (params) => inst.check(int(params));
  inst.safe = (params) => inst.check(int(params));
  inst.positive = (params) => inst.check(_gt(0, params));
  inst.nonnegative = (params) => inst.check(_gte(0, params));
  inst.negative = (params) => inst.check(_lt(0, params));
  inst.nonpositive = (params) => inst.check(_lte(0, params));
  inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
  inst.step = (value, params) => inst.check(_multipleOf(value, params));
  inst.finite = () => inst;
  const bag = inst._zod.bag;
  inst.minValue = (_c = Math.max((_a3 = bag.minimum) != null ? _a3 : Number.NEGATIVE_INFINITY, (_b2 = bag.exclusiveMinimum) != null ? _b2 : Number.NEGATIVE_INFINITY)) != null ? _c : null;
  inst.maxValue = (_f = Math.min((_d2 = bag.maximum) != null ? _d2 : Number.POSITIVE_INFINITY, (_e = bag.exclusiveMaximum) != null ? _e : Number.POSITIVE_INFINITY)) != null ? _f : null;
  inst.isInt = ((_g = bag.format) != null ? _g : "").includes("int") || Number.isSafeInteger((_h = bag.multipleOf) != null ? _h : 0.5);
  inst.isFinite = true;
  inst.format = (_i = bag.format) != null ? _i : null;
});
function number3(params) {
  return _number(ZodNumber2, params);
}
var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
  $ZodNumberFormat.init(inst, def);
  ZodNumber2.init(inst, def);
});
function int(params) {
  return _int(ZodNumberFormat, params);
}
function float32(params) {
  return _float32(ZodNumberFormat, params);
}
function float64(params) {
  return _float64(ZodNumberFormat, params);
}
function int32(params) {
  return _int32(ZodNumberFormat, params);
}
function uint32(params) {
  return _uint32(ZodNumberFormat, params);
}
var ZodBoolean2 = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
  $ZodBoolean.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => booleanProcessor(inst, ctx, json2, params);
});
function boolean3(params) {
  return _boolean(ZodBoolean2, params);
}
var ZodBigInt2 = /* @__PURE__ */ $constructor("ZodBigInt", (inst, def) => {
  var _a3, _b2, _c;
  $ZodBigInt.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => bigintProcessor(inst, ctx, json2, params);
  inst.gte = (value, params) => inst.check(_gte(value, params));
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.gt = (value, params) => inst.check(_gt(value, params));
  inst.gte = (value, params) => inst.check(_gte(value, params));
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.lt = (value, params) => inst.check(_lt(value, params));
  inst.lte = (value, params) => inst.check(_lte(value, params));
  inst.max = (value, params) => inst.check(_lte(value, params));
  inst.positive = (params) => inst.check(_gt(BigInt(0), params));
  inst.negative = (params) => inst.check(_lt(BigInt(0), params));
  inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params));
  inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params));
  inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params));
  const bag = inst._zod.bag;
  inst.minValue = (_a3 = bag.minimum) != null ? _a3 : null;
  inst.maxValue = (_b2 = bag.maximum) != null ? _b2 : null;
  inst.format = (_c = bag.format) != null ? _c : null;
});
function bigint3(params) {
  return _bigint(ZodBigInt2, params);
}
var ZodBigIntFormat = /* @__PURE__ */ $constructor("ZodBigIntFormat", (inst, def) => {
  $ZodBigIntFormat.init(inst, def);
  ZodBigInt2.init(inst, def);
});
function int64(params) {
  return _int64(ZodBigIntFormat, params);
}
function uint64(params) {
  return _uint64(ZodBigIntFormat, params);
}
var ZodSymbol2 = /* @__PURE__ */ $constructor("ZodSymbol", (inst, def) => {
  $ZodSymbol.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => symbolProcessor(inst, ctx, json2, params);
});
function symbol(params) {
  return _symbol(ZodSymbol2, params);
}
var ZodUndefined2 = /* @__PURE__ */ $constructor("ZodUndefined", (inst, def) => {
  $ZodUndefined.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => undefinedProcessor(inst, ctx, json2, params);
});
function _undefined3(params) {
  return _undefined2(ZodUndefined2, params);
}
var ZodNull2 = /* @__PURE__ */ $constructor("ZodNull", (inst, def) => {
  $ZodNull.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nullProcessor(inst, ctx, json2, params);
});
function _null3(params) {
  return _null2(ZodNull2, params);
}
var ZodAny2 = /* @__PURE__ */ $constructor("ZodAny", (inst, def) => {
  $ZodAny.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => anyProcessor(inst, ctx, json2, params);
});
function any() {
  return _any(ZodAny2);
}
var ZodUnknown2 = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
  $ZodUnknown.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => unknownProcessor(inst, ctx, json2, params);
});
function unknown() {
  return _unknown(ZodUnknown2);
}
var ZodNever2 = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
  $ZodNever.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => neverProcessor(inst, ctx, json2, params);
});
function never(params) {
  return _never(ZodNever2, params);
}
var ZodVoid2 = /* @__PURE__ */ $constructor("ZodVoid", (inst, def) => {
  $ZodVoid.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => voidProcessor(inst, ctx, json2, params);
});
function _void2(params) {
  return _void(ZodVoid2, params);
}
var ZodDate2 = /* @__PURE__ */ $constructor("ZodDate", (inst, def) => {
  $ZodDate.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => dateProcessor(inst, ctx, json2, params);
  inst.min = (value, params) => inst.check(_gte(value, params));
  inst.max = (value, params) => inst.check(_lte(value, params));
  const c = inst._zod.bag;
  inst.minDate = c.minimum ? new Date(c.minimum) : null;
  inst.maxDate = c.maximum ? new Date(c.maximum) : null;
});
function date5(params) {
  return _date(ZodDate2, params);
}
var ZodArray2 = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
  $ZodArray.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => arrayProcessor(inst, ctx, json2, params);
  inst.element = def.element;
  inst.min = (minLength, params) => inst.check(_minLength(minLength, params));
  inst.nonempty = (params) => inst.check(_minLength(1, params));
  inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params));
  inst.length = (len, params) => inst.check(_length(len, params));
  inst.unwrap = () => inst.element;
});
function array(element, params) {
  return _array(ZodArray2, element, params);
}
function keyof(schema) {
  const shape = schema._zod.def.shape;
  return _enum2(Object.keys(shape));
}
var ZodObject2 = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
  $ZodObjectJIT.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => objectProcessor(inst, ctx, json2, params);
  util_exports.defineLazy(inst, "shape", () => {
    return def.shape;
  });
  inst.keyof = () => _enum2(Object.keys(inst._zod.def.shape));
  inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall });
  inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
  inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() });
  inst.strict = () => inst.clone({ ...inst._zod.def, catchall: never() });
  inst.strip = () => inst.clone({ ...inst._zod.def, catchall: void 0 });
  inst.extend = (incoming) => {
    return util_exports.extend(inst, incoming);
  };
  inst.safeExtend = (incoming) => {
    return util_exports.safeExtend(inst, incoming);
  };
  inst.merge = (other) => util_exports.merge(inst, other);
  inst.pick = (mask) => util_exports.pick(inst, mask);
  inst.omit = (mask) => util_exports.omit(inst, mask);
  inst.partial = (...args) => util_exports.partial(ZodOptional2, inst, args[0]);
  inst.required = (...args) => util_exports.required(ZodNonOptional, inst, args[0]);
});
function object2(shape, params) {
  const def = {
    type: "object",
    shape: shape != null ? shape : {},
    ...util_exports.normalizeParams(params)
  };
  return new ZodObject2(def);
}
function strictObject(shape, params) {
  return new ZodObject2({
    type: "object",
    shape,
    catchall: never(),
    ...util_exports.normalizeParams(params)
  });
}
function looseObject(shape, params) {
  return new ZodObject2({
    type: "object",
    shape,
    catchall: unknown(),
    ...util_exports.normalizeParams(params)
  });
}
var ZodUnion2 = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
  $ZodUnion.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
  inst.options = def.options;
});
function union(options, params) {
  return new ZodUnion2({
    type: "union",
    options,
    ...util_exports.normalizeParams(params)
  });
}
var ZodXor = /* @__PURE__ */ $constructor("ZodXor", (inst, def) => {
  ZodUnion2.init(inst, def);
  $ZodXor.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => unionProcessor(inst, ctx, json2, params);
  inst.options = def.options;
});
function xor(options, params) {
  return new ZodXor({
    type: "union",
    options,
    inclusive: false,
    ...util_exports.normalizeParams(params)
  });
}
var ZodDiscriminatedUnion2 = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
  ZodUnion2.init(inst, def);
  $ZodDiscriminatedUnion.init(inst, def);
});
function discriminatedUnion(discriminator, options, params) {
  return new ZodDiscriminatedUnion2({
    type: "union",
    options,
    discriminator,
    ...util_exports.normalizeParams(params)
  });
}
var ZodIntersection2 = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
  $ZodIntersection.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => intersectionProcessor(inst, ctx, json2, params);
});
function intersection(left, right) {
  return new ZodIntersection2({
    type: "intersection",
    left,
    right
  });
}
var ZodTuple2 = /* @__PURE__ */ $constructor("ZodTuple", (inst, def) => {
  $ZodTuple.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => tupleProcessor(inst, ctx, json2, params);
  inst.rest = (rest) => inst.clone({
    ...inst._zod.def,
    rest
  });
});
function tuple(items, _paramsOrRest, _params) {
  const hasRest = _paramsOrRest instanceof $ZodType;
  const params = hasRest ? _params : _paramsOrRest;
  const rest = hasRest ? _paramsOrRest : null;
  return new ZodTuple2({
    type: "tuple",
    items,
    rest,
    ...util_exports.normalizeParams(params)
  });
}
var ZodRecord2 = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
  $ZodRecord.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => recordProcessor(inst, ctx, json2, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
});
function record(keyType, valueType, params) {
  return new ZodRecord2({
    type: "record",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function partialRecord(keyType, valueType, params) {
  const k10 = clone(keyType);
  k10._zod.values = void 0;
  return new ZodRecord2({
    type: "record",
    keyType: k10,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
function looseRecord(keyType, valueType, params) {
  return new ZodRecord2({
    type: "record",
    keyType,
    valueType,
    mode: "loose",
    ...util_exports.normalizeParams(params)
  });
}
var ZodMap2 = /* @__PURE__ */ $constructor("ZodMap", (inst, def) => {
  $ZodMap.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => mapProcessor(inst, ctx, json2, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
  inst.min = (...args) => inst.check(_minSize(...args));
  inst.nonempty = (params) => inst.check(_minSize(1, params));
  inst.max = (...args) => inst.check(_maxSize(...args));
  inst.size = (...args) => inst.check(_size(...args));
});
function map(keyType, valueType, params) {
  return new ZodMap2({
    type: "map",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
var ZodSet2 = /* @__PURE__ */ $constructor("ZodSet", (inst, def) => {
  $ZodSet.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => setProcessor(inst, ctx, json2, params);
  inst.min = (...args) => inst.check(_minSize(...args));
  inst.nonempty = (params) => inst.check(_minSize(1, params));
  inst.max = (...args) => inst.check(_maxSize(...args));
  inst.size = (...args) => inst.check(_size(...args));
});
function set(valueType, params) {
  return new ZodSet2({
    type: "set",
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
var ZodEnum2 = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
  $ZodEnum.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => enumProcessor(inst, ctx, json2, params);
  inst.enum = def.entries;
  inst.options = Object.values(def.entries);
  const keys = new Set(Object.keys(def.entries));
  inst.extract = (values, params) => {
    const newEntries = {};
    for (const value of values) {
      if (keys.has(value)) {
        newEntries[value] = def.entries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum2({
      ...def,
      checks: [],
      ...util_exports.normalizeParams(params),
      entries: newEntries
    });
  };
  inst.exclude = (values, params) => {
    const newEntries = { ...def.entries };
    for (const value of values) {
      if (keys.has(value)) {
        delete newEntries[value];
      } else
        throw new Error(`Key ${value} not found in enum`);
    }
    return new ZodEnum2({
      ...def,
      checks: [],
      ...util_exports.normalizeParams(params),
      entries: newEntries
    });
  };
});
function _enum2(values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v2) => [v2, v2])) : values;
  return new ZodEnum2({
    type: "enum",
    entries,
    ...util_exports.normalizeParams(params)
  });
}
function nativeEnum(entries, params) {
  return new ZodEnum2({
    type: "enum",
    entries,
    ...util_exports.normalizeParams(params)
  });
}
var ZodLiteral2 = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
  $ZodLiteral.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => literalProcessor(inst, ctx, json2, params);
  inst.values = new Set(def.values);
  Object.defineProperty(inst, "value", {
    get() {
      if (def.values.length > 1) {
        throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");
      }
      return def.values[0];
    }
  });
});
function literal(value, params) {
  return new ZodLiteral2({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...util_exports.normalizeParams(params)
  });
}
var ZodFile = /* @__PURE__ */ $constructor("ZodFile", (inst, def) => {
  $ZodFile.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => fileProcessor(inst, ctx, json2, params);
  inst.min = (size, params) => inst.check(_minSize(size, params));
  inst.max = (size, params) => inst.check(_maxSize(size, params));
  inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params));
});
function file(params) {
  return _file(ZodFile, params);
}
var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
  $ZodTransform.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => transformProcessor(inst, ctx, json2, params);
  inst._zod.parse = (payload, _ctx) => {
    if (_ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    payload.addIssue = (issue2) => {
      var _a3, _b2, _c;
      if (typeof issue2 === "string") {
        payload.issues.push(util_exports.issue(issue2, payload.value, def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        (_a3 = _issue.code) != null ? _a3 : _issue.code = "custom";
        (_b2 = _issue.input) != null ? _b2 : _issue.input = payload.value;
        (_c = _issue.inst) != null ? _c : _issue.inst = inst;
        payload.issues.push(util_exports.issue(_issue));
      }
    };
    const output = def.transform(payload.value, payload);
    if (output instanceof Promise) {
      return output.then((output2) => {
        payload.value = output2;
        return payload;
      });
    }
    payload.value = output;
    return payload;
  };
});
function transform(fn) {
  return new ZodTransform({
    type: "transform",
    transform: fn
  });
}
var ZodOptional2 = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
  return new ZodOptional2({
    type: "optional",
    innerType
  });
}
var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
  $ZodExactOptional.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => optionalProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function exactOptional(innerType) {
  return new ZodExactOptional({
    type: "optional",
    innerType
  });
}
var ZodNullable2 = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
  $ZodNullable.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nullableProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
  return new ZodNullable2({
    type: "nullable",
    innerType
  });
}
function nullish2(innerType) {
  return optional(nullable(innerType));
}
var ZodDefault2 = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
  $ZodDefault.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => defaultProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeDefault = inst.unwrap;
});
function _default2(innerType, defaultValue) {
  return new ZodDefault2({
    type: "default",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue);
    }
  });
}
var ZodPrefault = /* @__PURE__ */ $constructor("ZodPrefault", (inst, def) => {
  $ZodPrefault.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => prefaultProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function prefault(innerType, defaultValue) {
  return new ZodPrefault({
    type: "prefault",
    innerType,
    get defaultValue() {
      return typeof defaultValue === "function" ? defaultValue() : util_exports.shallowClone(defaultValue);
    }
  });
}
var ZodNonOptional = /* @__PURE__ */ $constructor("ZodNonOptional", (inst, def) => {
  $ZodNonOptional.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nonoptionalProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params) {
  return new ZodNonOptional({
    type: "nonoptional",
    innerType,
    ...util_exports.normalizeParams(params)
  });
}
var ZodSuccess = /* @__PURE__ */ $constructor("ZodSuccess", (inst, def) => {
  $ZodSuccess.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => successProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function success(innerType) {
  return new ZodSuccess({
    type: "success",
    innerType
  });
}
var ZodCatch2 = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
  $ZodCatch.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => catchProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeCatch = inst.unwrap;
});
function _catch2(innerType, catchValue) {
  return new ZodCatch2({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
var ZodNaN2 = /* @__PURE__ */ $constructor("ZodNaN", (inst, def) => {
  $ZodNaN.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => nanProcessor(inst, ctx, json2, params);
});
function nan(params) {
  return _nan(ZodNaN2, params);
}
var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
  $ZodPipe.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => pipeProcessor(inst, ctx, json2, params);
  inst.in = def.in;
  inst.out = def.out;
});
function pipe(in_, out) {
  return new ZodPipe({
    type: "pipe",
    in: in_,
    out
    // ...util.normalizeParams(params),
  });
}
var ZodCodec = /* @__PURE__ */ $constructor("ZodCodec", (inst, def) => {
  ZodPipe.init(inst, def);
  $ZodCodec.init(inst, def);
});
function codec(in_, out, params) {
  return new ZodCodec({
    type: "pipe",
    in: in_,
    out,
    transform: params.decode,
    reverseTransform: params.encode
  });
}
var ZodReadonly2 = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
  $ZodReadonly.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => readonlyProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function readonly(innerType) {
  return new ZodReadonly2({
    type: "readonly",
    innerType
  });
}
var ZodTemplateLiteral = /* @__PURE__ */ $constructor("ZodTemplateLiteral", (inst, def) => {
  $ZodTemplateLiteral.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => templateLiteralProcessor(inst, ctx, json2, params);
});
function templateLiteral(parts, params) {
  return new ZodTemplateLiteral({
    type: "template_literal",
    parts,
    ...util_exports.normalizeParams(params)
  });
}
var ZodLazy2 = /* @__PURE__ */ $constructor("ZodLazy", (inst, def) => {
  $ZodLazy.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => lazyProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.getter();
});
function lazy(getter) {
  return new ZodLazy2({
    type: "lazy",
    getter
  });
}
var ZodPromise2 = /* @__PURE__ */ $constructor("ZodPromise", (inst, def) => {
  $ZodPromise.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => promiseProcessor(inst, ctx, json2, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function promise(innerType) {
  return new ZodPromise2({
    type: "promise",
    innerType
  });
}
var ZodFunction2 = /* @__PURE__ */ $constructor("ZodFunction", (inst, def) => {
  $ZodFunction.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => functionProcessor(inst, ctx, json2, params);
});
function _function(params) {
  var _a3, _b2;
  return new ZodFunction2({
    type: "function",
    input: Array.isArray(params == null ? void 0 : params.input) ? tuple(params == null ? void 0 : params.input) : (_a3 = params == null ? void 0 : params.input) != null ? _a3 : array(unknown()),
    output: (_b2 = params == null ? void 0 : params.output) != null ? _b2 : unknown()
  });
}
var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
  $ZodCustom.init(inst, def);
  ZodType2.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json2, params) => customProcessor(inst, ctx, json2, params);
});
function check(fn) {
  const ch = new $ZodCheck({
    check: "custom"
    // ...util.normalizeParams(params),
  });
  ch._zod.check = fn;
  return ch;
}
function custom(fn, _params) {
  return _custom(ZodCustom, fn != null ? fn : (() => true), _params);
}
function refine(fn, _params = {}) {
  return _refine(ZodCustom, fn, _params);
}
function superRefine(fn) {
  return _superRefine(fn);
}
var describe2 = describe;
var meta2 = meta;
function _instanceof(cls, params = {}) {
  const inst = new ZodCustom({
    type: "custom",
    check: "custom",
    fn: (data) => data instanceof cls,
    abort: true,
    ...util_exports.normalizeParams(params)
  });
  inst._zod.bag.Class = cls;
  inst._zod.check = (payload) => {
    var _a3;
    if (!(payload.value instanceof cls)) {
      payload.issues.push({
        code: "invalid_type",
        expected: cls.name,
        input: payload.value,
        inst,
        path: [...(_a3 = inst._zod.def.path) != null ? _a3 : []]
      });
    }
  };
  return inst;
}
var stringbool = (...args) => _stringbool({
  Codec: ZodCodec,
  Boolean: ZodBoolean2,
  String: ZodString2
}, ...args);
function json(params) {
  const jsonSchema = lazy(() => {
    return union([string3(params), number3(), boolean3(), _null3(), array(jsonSchema), record(string3(), jsonSchema)]);
  });
  return jsonSchema;
}
function preprocess(fn, schema) {
  return pipe(transform(fn), schema);
}

// node_modules/zod/v4/classic/compat.js
var ZodIssueCode2 = {
  invalid_type: "invalid_type",
  too_big: "too_big",
  too_small: "too_small",
  invalid_format: "invalid_format",
  not_multiple_of: "not_multiple_of",
  unrecognized_keys: "unrecognized_keys",
  invalid_union: "invalid_union",
  invalid_key: "invalid_key",
  invalid_element: "invalid_element",
  invalid_value: "invalid_value",
  custom: "custom"
};
var ZodFirstPartyTypeKind2;
/* @__PURE__ */ (function(ZodFirstPartyTypeKind3) {
})(ZodFirstPartyTypeKind2 || (ZodFirstPartyTypeKind2 = {}));

// node_modules/zod/v4/classic/from-json-schema.js
var z = {
  ...schemas_exports3,
  ...checks_exports2,
  iso: iso_exports2
};

// node_modules/zod/v4/classic/coerce.js
var coerce_exports2 = {};
__export(coerce_exports2, {
  bigint: () => bigint4,
  boolean: () => boolean4,
  date: () => date6,
  number: () => number4,
  string: () => string4
});
function string4(params) {
  return _coercedString(ZodString2, params);
}
function number4(params) {
  return _coercedNumber(ZodNumber2, params);
}
function boolean4(params) {
  return _coercedBoolean(ZodBoolean2, params);
}
function bigint4(params) {
  return _coercedBigint(ZodBigInt2, params);
}
function date6(params) {
  return _coercedDate(ZodDate2, params);
}

// node_modules/zod/v4/classic/external.js
config(en_default3());

// node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
var LATEST_PROTOCOL_VERSION = "2025-11-25";
var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-06-18", "2025-03-26", "2024-11-05", "2024-10-07"];
var RELATED_TASK_META_KEY = "io.modelcontextprotocol/related-task";
var JSONRPC_VERSION = "2.0";
var AssertObjectSchema = custom((v2) => v2 !== null && (typeof v2 === "object" || typeof v2 === "function"));
var ProgressTokenSchema = union([string3(), number3().int()]);
var CursorSchema = string3();
var TaskCreationParamsSchema = looseObject({
  /**
   * Requested duration in milliseconds to retain task from creation.
   */
  ttl: number3().optional(),
  /**
   * Time in milliseconds to wait between task status requests.
   */
  pollInterval: number3().optional()
});
var TaskMetadataSchema = object2({
  ttl: number3().optional()
});
var RelatedTaskMetadataSchema = object2({
  taskId: string3()
});
var RequestMetaSchema = looseObject({
  /**
   * If specified, the caller is requesting out-of-band progress notifications for this request (as represented by notifications/progress). The value of this parameter is an opaque token that will be attached to any subsequent notifications. The receiver is not obligated to provide these notifications.
   */
  progressToken: ProgressTokenSchema.optional(),
  /**
   * If specified, this request is related to the provided task.
   */
  [RELATED_TASK_META_KEY]: RelatedTaskMetadataSchema.optional()
});
var BaseRequestParamsSchema = object2({
  /**
   * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
   */
  _meta: RequestMetaSchema.optional()
});
var TaskAugmentedRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * If specified, the caller is requesting task-augmented execution for this request.
   * The request will return a CreateTaskResult immediately, and the actual result can be
   * retrieved later via tasks/result.
   *
   * Task augmentation is subject to capability negotiation - receivers MUST declare support
   * for task augmentation of specific request types in their capabilities.
   */
  task: TaskMetadataSchema.optional()
});
var isTaskAugmentedRequestParams = (value) => TaskAugmentedRequestParamsSchema.safeParse(value).success;
var RequestSchema = object2({
  method: string3(),
  params: BaseRequestParamsSchema.loose().optional()
});
var NotificationsParamsSchema = object2({
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: RequestMetaSchema.optional()
});
var NotificationSchema = object2({
  method: string3(),
  params: NotificationsParamsSchema.loose().optional()
});
var ResultSchema = looseObject({
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: RequestMetaSchema.optional()
});
var RequestIdSchema = union([string3(), number3().int()]);
var JSONRPCRequestSchema = object2({
  jsonrpc: literal(JSONRPC_VERSION),
  id: RequestIdSchema,
  ...RequestSchema.shape
}).strict();
var isJSONRPCRequest = (value) => JSONRPCRequestSchema.safeParse(value).success;
var JSONRPCNotificationSchema = object2({
  jsonrpc: literal(JSONRPC_VERSION),
  ...NotificationSchema.shape
}).strict();
var isJSONRPCNotification = (value) => JSONRPCNotificationSchema.safeParse(value).success;
var JSONRPCResultResponseSchema = object2({
  jsonrpc: literal(JSONRPC_VERSION),
  id: RequestIdSchema,
  result: ResultSchema
}).strict();
var isJSONRPCResultResponse = (value) => JSONRPCResultResponseSchema.safeParse(value).success;
var ErrorCode;
(function(ErrorCode2) {
  ErrorCode2[ErrorCode2["ConnectionClosed"] = -32e3] = "ConnectionClosed";
  ErrorCode2[ErrorCode2["RequestTimeout"] = -32001] = "RequestTimeout";
  ErrorCode2[ErrorCode2["ParseError"] = -32700] = "ParseError";
  ErrorCode2[ErrorCode2["InvalidRequest"] = -32600] = "InvalidRequest";
  ErrorCode2[ErrorCode2["MethodNotFound"] = -32601] = "MethodNotFound";
  ErrorCode2[ErrorCode2["InvalidParams"] = -32602] = "InvalidParams";
  ErrorCode2[ErrorCode2["InternalError"] = -32603] = "InternalError";
  ErrorCode2[ErrorCode2["UrlElicitationRequired"] = -32042] = "UrlElicitationRequired";
})(ErrorCode || (ErrorCode = {}));
var JSONRPCErrorResponseSchema = object2({
  jsonrpc: literal(JSONRPC_VERSION),
  id: RequestIdSchema.optional(),
  error: object2({
    /**
     * The error type that occurred.
     */
    code: number3().int(),
    /**
     * A short description of the error. The message SHOULD be limited to a concise single sentence.
     */
    message: string3(),
    /**
     * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
     */
    data: unknown().optional()
  })
}).strict();
var isJSONRPCErrorResponse = (value) => JSONRPCErrorResponseSchema.safeParse(value).success;
var JSONRPCMessageSchema = union([
  JSONRPCRequestSchema,
  JSONRPCNotificationSchema,
  JSONRPCResultResponseSchema,
  JSONRPCErrorResponseSchema
]);
var JSONRPCResponseSchema = union([JSONRPCResultResponseSchema, JSONRPCErrorResponseSchema]);
var EmptyResultSchema = ResultSchema.strict();
var CancelledNotificationParamsSchema = NotificationsParamsSchema.extend({
  /**
   * The ID of the request to cancel.
   *
   * This MUST correspond to the ID of a request previously issued in the same direction.
   */
  requestId: RequestIdSchema.optional(),
  /**
   * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
   */
  reason: string3().optional()
});
var CancelledNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/cancelled"),
  params: CancelledNotificationParamsSchema
});
var IconSchema = object2({
  /**
   * URL or data URI for the icon.
   */
  src: string3(),
  /**
   * Optional MIME type for the icon.
   */
  mimeType: string3().optional(),
  /**
   * Optional array of strings that specify sizes at which the icon can be used.
   * Each string should be in WxH format (e.g., `"48x48"`, `"96x96"`) or `"any"` for scalable formats like SVG.
   *
   * If not provided, the client should assume that the icon can be used at any size.
   */
  sizes: array(string3()).optional(),
  /**
   * Optional specifier for the theme this icon is designed for. `light` indicates
   * the icon is designed to be used with a light background, and `dark` indicates
   * the icon is designed to be used with a dark background.
   *
   * If not provided, the client should assume the icon can be used with any theme.
   */
  theme: _enum2(["light", "dark"]).optional()
});
var IconsSchema = object2({
  /**
   * Optional set of sized icons that the client can display in a user interface.
   *
   * Clients that support rendering icons MUST support at least the following MIME types:
   * - `image/png` - PNG images (safe, universal compatibility)
   * - `image/jpeg` (and `image/jpg`) - JPEG images (safe, universal compatibility)
   *
   * Clients that support rendering icons SHOULD also support:
   * - `image/svg+xml` - SVG images (scalable but requires security precautions)
   * - `image/webp` - WebP images (modern, efficient format)
   */
  icons: array(IconSchema).optional()
});
var BaseMetadataSchema = object2({
  /** Intended for programmatic or logical use, but used as a display name in past specs or fallback */
  name: string3(),
  /**
   * Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
   * even by those unfamiliar with domain-specific terminology.
   *
   * If not provided, the name should be used for display (except for Tool,
   * where `annotations.title` should be given precedence over using `name`,
   * if present).
   */
  title: string3().optional()
});
var ImplementationSchema = BaseMetadataSchema.extend({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  version: string3(),
  /**
   * An optional URL of the website for this implementation.
   */
  websiteUrl: string3().optional(),
  /**
   * An optional human-readable description of what this implementation does.
   *
   * This can be used by clients or servers to provide context about their purpose
   * and capabilities. For example, a server might describe the types of resources
   * or tools it provides, while a client might describe its intended use case.
   */
  description: string3().optional()
});
var FormElicitationCapabilitySchema = intersection(object2({
  applyDefaults: boolean3().optional()
}), record(string3(), unknown()));
var ElicitationCapabilitySchema = preprocess((value) => {
  if (value && typeof value === "object" && !Array.isArray(value)) {
    if (Object.keys(value).length === 0) {
      return { form: {} };
    }
  }
  return value;
}, intersection(object2({
  form: FormElicitationCapabilitySchema.optional(),
  url: AssertObjectSchema.optional()
}), record(string3(), unknown()).optional()));
var ClientTasksCapabilitySchema = looseObject({
  /**
   * Present if the client supports listing tasks.
   */
  list: AssertObjectSchema.optional(),
  /**
   * Present if the client supports cancelling tasks.
   */
  cancel: AssertObjectSchema.optional(),
  /**
   * Capabilities for task creation on specific request types.
   */
  requests: looseObject({
    /**
     * Task support for sampling requests.
     */
    sampling: looseObject({
      createMessage: AssertObjectSchema.optional()
    }).optional(),
    /**
     * Task support for elicitation requests.
     */
    elicitation: looseObject({
      create: AssertObjectSchema.optional()
    }).optional()
  }).optional()
});
var ServerTasksCapabilitySchema = looseObject({
  /**
   * Present if the server supports listing tasks.
   */
  list: AssertObjectSchema.optional(),
  /**
   * Present if the server supports cancelling tasks.
   */
  cancel: AssertObjectSchema.optional(),
  /**
   * Capabilities for task creation on specific request types.
   */
  requests: looseObject({
    /**
     * Task support for tool requests.
     */
    tools: looseObject({
      call: AssertObjectSchema.optional()
    }).optional()
  }).optional()
});
var ClientCapabilitiesSchema = object2({
  /**
   * Experimental, non-standard capabilities that the client supports.
   */
  experimental: record(string3(), AssertObjectSchema).optional(),
  /**
   * Present if the client supports sampling from an LLM.
   */
  sampling: object2({
    /**
     * Present if the client supports context inclusion via includeContext parameter.
     * If not declared, servers SHOULD only use `includeContext: "none"` (or omit it).
     */
    context: AssertObjectSchema.optional(),
    /**
     * Present if the client supports tool use via tools and toolChoice parameters.
     */
    tools: AssertObjectSchema.optional()
  }).optional(),
  /**
   * Present if the client supports eliciting user input.
   */
  elicitation: ElicitationCapabilitySchema.optional(),
  /**
   * Present if the client supports listing roots.
   */
  roots: object2({
    /**
     * Whether the client supports issuing notifications for changes to the roots list.
     */
    listChanged: boolean3().optional()
  }).optional(),
  /**
   * Present if the client supports task creation.
   */
  tasks: ClientTasksCapabilitySchema.optional(),
  /**
   * Extensions that the client supports. Keys are extension identifiers (vendor-prefix/extension-name).
   */
  extensions: record(string3(), AssertObjectSchema).optional()
});
var InitializeRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * The latest version of the Model Context Protocol that the client supports. The client MAY decide to support older versions as well.
   */
  protocolVersion: string3(),
  capabilities: ClientCapabilitiesSchema,
  clientInfo: ImplementationSchema
});
var InitializeRequestSchema = RequestSchema.extend({
  method: literal("initialize"),
  params: InitializeRequestParamsSchema
});
var ServerCapabilitiesSchema = object2({
  /**
   * Experimental, non-standard capabilities that the server supports.
   */
  experimental: record(string3(), AssertObjectSchema).optional(),
  /**
   * Present if the server supports sending log messages to the client.
   */
  logging: AssertObjectSchema.optional(),
  /**
   * Present if the server supports sending completions to the client.
   */
  completions: AssertObjectSchema.optional(),
  /**
   * Present if the server offers any prompt templates.
   */
  prompts: object2({
    /**
     * Whether this server supports issuing notifications for changes to the prompt list.
     */
    listChanged: boolean3().optional()
  }).optional(),
  /**
   * Present if the server offers any resources to read.
   */
  resources: object2({
    /**
     * Whether this server supports clients subscribing to resource updates.
     */
    subscribe: boolean3().optional(),
    /**
     * Whether this server supports issuing notifications for changes to the resource list.
     */
    listChanged: boolean3().optional()
  }).optional(),
  /**
   * Present if the server offers any tools to call.
   */
  tools: object2({
    /**
     * Whether this server supports issuing notifications for changes to the tool list.
     */
    listChanged: boolean3().optional()
  }).optional(),
  /**
   * Present if the server supports task creation.
   */
  tasks: ServerTasksCapabilitySchema.optional(),
  /**
   * Extensions that the server supports. Keys are extension identifiers (vendor-prefix/extension-name).
   */
  extensions: record(string3(), AssertObjectSchema).optional()
});
var InitializeResultSchema = ResultSchema.extend({
  /**
   * The version of the Model Context Protocol that the server wants to use. This may not match the version that the client requested. If the client cannot support this version, it MUST disconnect.
   */
  protocolVersion: string3(),
  capabilities: ServerCapabilitiesSchema,
  serverInfo: ImplementationSchema,
  /**
   * Instructions describing how to use the server and its features.
   *
   * This can be used by clients to improve the LLM's understanding of available tools, resources, etc. It can be thought of like a "hint" to the model. For example, this information MAY be added to the system prompt.
   */
  instructions: string3().optional()
});
var InitializedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/initialized"),
  params: NotificationsParamsSchema.optional()
});
var isInitializedNotification = (value) => InitializedNotificationSchema.safeParse(value).success;
var PingRequestSchema = RequestSchema.extend({
  method: literal("ping"),
  params: BaseRequestParamsSchema.optional()
});
var ProgressSchema = object2({
  /**
   * The progress thus far. This should increase every time progress is made, even if the total is unknown.
   */
  progress: number3(),
  /**
   * Total number of items to process (or total progress required), if known.
   */
  total: optional(number3()),
  /**
   * An optional message describing the current progress.
   */
  message: optional(string3())
});
var ProgressNotificationParamsSchema = object2({
  ...NotificationsParamsSchema.shape,
  ...ProgressSchema.shape,
  /**
   * The progress token which was given in the initial request, used to associate this notification with the request that is proceeding.
   */
  progressToken: ProgressTokenSchema
});
var ProgressNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/progress"),
  params: ProgressNotificationParamsSchema
});
var PaginatedRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * An opaque token representing the current pagination position.
   * If provided, the server should return results starting after this cursor.
   */
  cursor: CursorSchema.optional()
});
var PaginatedRequestSchema = RequestSchema.extend({
  params: PaginatedRequestParamsSchema.optional()
});
var PaginatedResultSchema = ResultSchema.extend({
  /**
   * An opaque token representing the pagination position after the last returned result.
   * If present, there may be more results available.
   */
  nextCursor: CursorSchema.optional()
});
var TaskStatusSchema = _enum2(["working", "input_required", "completed", "failed", "cancelled"]);
var TaskSchema = object2({
  taskId: string3(),
  status: TaskStatusSchema,
  /**
   * Time in milliseconds to keep task results available after completion.
   * If null, the task has unlimited lifetime until manually cleaned up.
   */
  ttl: union([number3(), _null3()]),
  /**
   * ISO 8601 timestamp when the task was created.
   */
  createdAt: string3(),
  /**
   * ISO 8601 timestamp when the task was last updated.
   */
  lastUpdatedAt: string3(),
  pollInterval: optional(number3()),
  /**
   * Optional diagnostic message for failed tasks or other status information.
   */
  statusMessage: optional(string3())
});
var CreateTaskResultSchema = ResultSchema.extend({
  task: TaskSchema
});
var TaskStatusNotificationParamsSchema = NotificationsParamsSchema.merge(TaskSchema);
var TaskStatusNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/tasks/status"),
  params: TaskStatusNotificationParamsSchema
});
var GetTaskRequestSchema = RequestSchema.extend({
  method: literal("tasks/get"),
  params: BaseRequestParamsSchema.extend({
    taskId: string3()
  })
});
var GetTaskResultSchema = ResultSchema.merge(TaskSchema);
var GetTaskPayloadRequestSchema = RequestSchema.extend({
  method: literal("tasks/result"),
  params: BaseRequestParamsSchema.extend({
    taskId: string3()
  })
});
var GetTaskPayloadResultSchema = ResultSchema.loose();
var ListTasksRequestSchema = PaginatedRequestSchema.extend({
  method: literal("tasks/list")
});
var ListTasksResultSchema = PaginatedResultSchema.extend({
  tasks: array(TaskSchema)
});
var CancelTaskRequestSchema = RequestSchema.extend({
  method: literal("tasks/cancel"),
  params: BaseRequestParamsSchema.extend({
    taskId: string3()
  })
});
var CancelTaskResultSchema = ResultSchema.merge(TaskSchema);
var ResourceContentsSchema = object2({
  /**
   * The URI of this resource.
   */
  uri: string3(),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optional(string3()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var TextResourceContentsSchema = ResourceContentsSchema.extend({
  /**
   * The text of the item. This must only be set if the item can actually be represented as text (not binary data).
   */
  text: string3()
});
var Base64Schema = string3().refine((val) => {
  try {
    atob(val);
    return true;
  } catch (e2) {
    return false;
  }
}, { message: "Invalid Base64 string" });
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
  /**
   * A base64-encoded string representing the binary data of the item.
   */
  blob: Base64Schema
});
var RoleSchema = _enum2(["user", "assistant"]);
var AnnotationsSchema = object2({
  /**
   * Intended audience(s) for the resource.
   */
  audience: array(RoleSchema).optional(),
  /**
   * Importance hint for the resource, from 0 (least) to 1 (most).
   */
  priority: number3().min(0).max(1).optional(),
  /**
   * ISO 8601 timestamp for the most recent modification.
   */
  lastModified: iso_exports2.datetime({ offset: true }).optional()
});
var ResourceSchema = object2({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * The URI of this resource.
   */
  uri: string3(),
  /**
   * A description of what this resource represents.
   *
   * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
   */
  description: optional(string3()),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optional(string3()),
  /**
   * The size of the raw resource content, in bytes (i.e., before base64 encoding or any tokenization), if known.
   *
   * This can be used by Hosts to display file sizes and estimate context window usage.
   */
  size: optional(number3()),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optional(looseObject({}))
});
var ResourceTemplateSchema = object2({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * A URI template (according to RFC 6570) that can be used to construct resource URIs.
   */
  uriTemplate: string3(),
  /**
   * A description of what this template is for.
   *
   * This can be used by clients to improve the LLM's understanding of available resources. It can be thought of like a "hint" to the model.
   */
  description: optional(string3()),
  /**
   * The MIME type for all resources that match this template. This should only be included if all resources matching this template have the same type.
   */
  mimeType: optional(string3()),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optional(looseObject({}))
});
var ListResourcesRequestSchema = PaginatedRequestSchema.extend({
  method: literal("resources/list")
});
var ListResourcesResultSchema = PaginatedResultSchema.extend({
  resources: array(ResourceSchema)
});
var ListResourceTemplatesRequestSchema = PaginatedRequestSchema.extend({
  method: literal("resources/templates/list")
});
var ListResourceTemplatesResultSchema = PaginatedResultSchema.extend({
  resourceTemplates: array(ResourceTemplateSchema)
});
var ResourceRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * The URI of the resource to read. The URI can use any protocol; it is up to the server how to interpret it.
   *
   * @format uri
   */
  uri: string3()
});
var ReadResourceRequestParamsSchema = ResourceRequestParamsSchema;
var ReadResourceRequestSchema = RequestSchema.extend({
  method: literal("resources/read"),
  params: ReadResourceRequestParamsSchema
});
var ReadResourceResultSchema = ResultSchema.extend({
  contents: array(union([TextResourceContentsSchema, BlobResourceContentsSchema]))
});
var ResourceListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/resources/list_changed"),
  params: NotificationsParamsSchema.optional()
});
var SubscribeRequestParamsSchema = ResourceRequestParamsSchema;
var SubscribeRequestSchema = RequestSchema.extend({
  method: literal("resources/subscribe"),
  params: SubscribeRequestParamsSchema
});
var UnsubscribeRequestParamsSchema = ResourceRequestParamsSchema;
var UnsubscribeRequestSchema = RequestSchema.extend({
  method: literal("resources/unsubscribe"),
  params: UnsubscribeRequestParamsSchema
});
var ResourceUpdatedNotificationParamsSchema = NotificationsParamsSchema.extend({
  /**
   * The URI of the resource that has been updated. This might be a sub-resource of the one that the client actually subscribed to.
   */
  uri: string3()
});
var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/resources/updated"),
  params: ResourceUpdatedNotificationParamsSchema
});
var PromptArgumentSchema = object2({
  /**
   * The name of the argument.
   */
  name: string3(),
  /**
   * A human-readable description of the argument.
   */
  description: optional(string3()),
  /**
   * Whether this argument must be provided.
   */
  required: optional(boolean3())
});
var PromptSchema = object2({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * An optional description of what this prompt provides
   */
  description: optional(string3()),
  /**
   * A list of arguments to use for templating the prompt.
   */
  arguments: optional(array(PromptArgumentSchema)),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: optional(looseObject({}))
});
var ListPromptsRequestSchema = PaginatedRequestSchema.extend({
  method: literal("prompts/list")
});
var ListPromptsResultSchema = PaginatedResultSchema.extend({
  prompts: array(PromptSchema)
});
var GetPromptRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * The name of the prompt or prompt template.
   */
  name: string3(),
  /**
   * Arguments to use for templating the prompt.
   */
  arguments: record(string3(), string3()).optional()
});
var GetPromptRequestSchema = RequestSchema.extend({
  method: literal("prompts/get"),
  params: GetPromptRequestParamsSchema
});
var TextContentSchema = object2({
  type: literal("text"),
  /**
   * The text content of the message.
   */
  text: string3(),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var ImageContentSchema = object2({
  type: literal("image"),
  /**
   * The base64-encoded image data.
   */
  data: Base64Schema,
  /**
   * The MIME type of the image. Different providers may support different image types.
   */
  mimeType: string3(),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var AudioContentSchema = object2({
  type: literal("audio"),
  /**
   * The base64-encoded audio data.
   */
  data: Base64Schema,
  /**
   * The MIME type of the audio. Different providers may support different audio types.
   */
  mimeType: string3(),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var ToolUseContentSchema = object2({
  type: literal("tool_use"),
  /**
   * The name of the tool to invoke.
   * Must match a tool name from the request's tools array.
   */
  name: string3(),
  /**
   * Unique identifier for this tool call.
   * Used to correlate with ToolResultContent in subsequent messages.
   */
  id: string3(),
  /**
   * Arguments to pass to the tool.
   * Must conform to the tool's inputSchema.
   */
  input: record(string3(), unknown()),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var EmbeddedResourceSchema = object2({
  type: literal("resource"),
  resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
  /**
   * Optional annotations for the client.
   */
  annotations: AnnotationsSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var ResourceLinkSchema = ResourceSchema.extend({
  type: literal("resource_link")
});
var ContentBlockSchema = union([
  TextContentSchema,
  ImageContentSchema,
  AudioContentSchema,
  ResourceLinkSchema,
  EmbeddedResourceSchema
]);
var PromptMessageSchema = object2({
  role: RoleSchema,
  content: ContentBlockSchema
});
var GetPromptResultSchema = ResultSchema.extend({
  /**
   * An optional description for the prompt.
   */
  description: string3().optional(),
  messages: array(PromptMessageSchema)
});
var PromptListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/prompts/list_changed"),
  params: NotificationsParamsSchema.optional()
});
var ToolAnnotationsSchema = object2({
  /**
   * A human-readable title for the tool.
   */
  title: string3().optional(),
  /**
   * If true, the tool does not modify its environment.
   *
   * Default: false
   */
  readOnlyHint: boolean3().optional(),
  /**
   * If true, the tool may perform destructive updates to its environment.
   * If false, the tool performs only additive updates.
   *
   * (This property is meaningful only when `readOnlyHint == false`)
   *
   * Default: true
   */
  destructiveHint: boolean3().optional(),
  /**
   * If true, calling the tool repeatedly with the same arguments
   * will have no additional effect on the its environment.
   *
   * (This property is meaningful only when `readOnlyHint == false`)
   *
   * Default: false
   */
  idempotentHint: boolean3().optional(),
  /**
   * If true, this tool may interact with an "open world" of external
   * entities. If false, the tool's domain of interaction is closed.
   * For example, the world of a web search tool is open, whereas that
   * of a memory tool is not.
   *
   * Default: true
   */
  openWorldHint: boolean3().optional()
});
var ToolExecutionSchema = object2({
  /**
   * Indicates the tool's preference for task-augmented execution.
   * - "required": Clients MUST invoke the tool as a task
   * - "optional": Clients MAY invoke the tool as a task or normal request
   * - "forbidden": Clients MUST NOT attempt to invoke the tool as a task
   *
   * If not present, defaults to "forbidden".
   */
  taskSupport: _enum2(["required", "optional", "forbidden"]).optional()
});
var ToolSchema = object2({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * A human-readable description of the tool.
   */
  description: string3().optional(),
  /**
   * A JSON Schema 2020-12 object defining the expected parameters for the tool.
   * Must have type: 'object' at the root level per MCP spec.
   */
  inputSchema: object2({
    type: literal("object"),
    properties: record(string3(), AssertObjectSchema).optional(),
    required: array(string3()).optional()
  }).catchall(unknown()),
  /**
   * An optional JSON Schema 2020-12 object defining the structure of the tool's output
   * returned in the structuredContent field of a CallToolResult.
   * Must have type: 'object' at the root level per MCP spec.
   */
  outputSchema: object2({
    type: literal("object"),
    properties: record(string3(), AssertObjectSchema).optional(),
    required: array(string3()).optional()
  }).catchall(unknown()).optional(),
  /**
   * Optional additional tool information.
   */
  annotations: ToolAnnotationsSchema.optional(),
  /**
   * Execution-related properties for this tool.
   */
  execution: ToolExecutionSchema.optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var ListToolsRequestSchema = PaginatedRequestSchema.extend({
  method: literal("tools/list")
});
var ListToolsResultSchema = PaginatedResultSchema.extend({
  tools: array(ToolSchema)
});
var CallToolResultSchema = ResultSchema.extend({
  /**
   * A list of content objects that represent the result of the tool call.
   *
   * If the Tool does not define an outputSchema, this field MUST be present in the result.
   * For backwards compatibility, this field is always present, but it may be empty.
   */
  content: array(ContentBlockSchema).default([]),
  /**
   * An object containing structured tool output.
   *
   * If the Tool defines an outputSchema, this field MUST be present in the result, and contain a JSON object that matches the schema.
   */
  structuredContent: record(string3(), unknown()).optional(),
  /**
   * Whether the tool call ended in an error.
   *
   * If not set, this is assumed to be false (the call was successful).
   *
   * Any errors that originate from the tool SHOULD be reported inside the result
   * object, with `isError` set to true, _not_ as an MCP protocol-level error
   * response. Otherwise, the LLM would not be able to see that an error occurred
   * and self-correct.
   *
   * However, any errors in _finding_ the tool, an error indicating that the
   * server does not support tool calls, or any other exceptional conditions,
   * should be reported as an MCP error response.
   */
  isError: boolean3().optional()
});
var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
  toolResult: unknown()
}));
var CallToolRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
  /**
   * The name of the tool to call.
   */
  name: string3(),
  /**
   * Arguments to pass to the tool.
   */
  arguments: record(string3(), unknown()).optional()
});
var CallToolRequestSchema = RequestSchema.extend({
  method: literal("tools/call"),
  params: CallToolRequestParamsSchema
});
var ToolListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/tools/list_changed"),
  params: NotificationsParamsSchema.optional()
});
var ListChangedOptionsBaseSchema = object2({
  /**
   * If true, the list will be refreshed automatically when a list changed notification is received.
   * The callback will be called with the updated list.
   *
   * If false, the callback will be called with null items, allowing manual refresh.
   *
   * @default true
   */
  autoRefresh: boolean3().default(true),
  /**
   * Debounce time in milliseconds for list changed notification processing.
   *
   * Multiple notifications received within this timeframe will only trigger one refresh.
   * Set to 0 to disable debouncing.
   *
   * @default 300
   */
  debounceMs: number3().int().nonnegative().default(300)
});
var LoggingLevelSchema = _enum2(["debug", "info", "notice", "warning", "error", "critical", "alert", "emergency"]);
var SetLevelRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * The level of logging that the client wants to receive from the server. The server should send all logs at this level and higher (i.e., more severe) to the client as notifications/logging/message.
   */
  level: LoggingLevelSchema
});
var SetLevelRequestSchema = RequestSchema.extend({
  method: literal("logging/setLevel"),
  params: SetLevelRequestParamsSchema
});
var LoggingMessageNotificationParamsSchema = NotificationsParamsSchema.extend({
  /**
   * The severity of this log message.
   */
  level: LoggingLevelSchema,
  /**
   * An optional name of the logger issuing this message.
   */
  logger: string3().optional(),
  /**
   * The data to be logged, such as a string message or an object. Any JSON serializable type is allowed here.
   */
  data: unknown()
});
var LoggingMessageNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/message"),
  params: LoggingMessageNotificationParamsSchema
});
var ModelHintSchema = object2({
  /**
   * A hint for a model name.
   */
  name: string3().optional()
});
var ModelPreferencesSchema = object2({
  /**
   * Optional hints to use for model selection.
   */
  hints: array(ModelHintSchema).optional(),
  /**
   * How much to prioritize cost when selecting a model.
   */
  costPriority: number3().min(0).max(1).optional(),
  /**
   * How much to prioritize sampling speed (latency) when selecting a model.
   */
  speedPriority: number3().min(0).max(1).optional(),
  /**
   * How much to prioritize intelligence and capabilities when selecting a model.
   */
  intelligencePriority: number3().min(0).max(1).optional()
});
var ToolChoiceSchema = object2({
  /**
   * Controls when tools are used:
   * - "auto": Model decides whether to use tools (default)
   * - "required": Model MUST use at least one tool before completing
   * - "none": Model MUST NOT use any tools
   */
  mode: _enum2(["auto", "required", "none"]).optional()
});
var ToolResultContentSchema = object2({
  type: literal("tool_result"),
  toolUseId: string3().describe("The unique identifier for the corresponding tool call."),
  content: array(ContentBlockSchema).default([]),
  structuredContent: object2({}).loose().optional(),
  isError: boolean3().optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var SamplingContentSchema = discriminatedUnion("type", [TextContentSchema, ImageContentSchema, AudioContentSchema]);
var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
  TextContentSchema,
  ImageContentSchema,
  AudioContentSchema,
  ToolUseContentSchema,
  ToolResultContentSchema
]);
var SamplingMessageSchema = object2({
  role: RoleSchema,
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)]),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var CreateMessageRequestParamsSchema = TaskAugmentedRequestParamsSchema.extend({
  messages: array(SamplingMessageSchema),
  /**
   * The server's preferences for which model to select. The client MAY modify or omit this request.
   */
  modelPreferences: ModelPreferencesSchema.optional(),
  /**
   * An optional system prompt the server wants to use for sampling. The client MAY modify or omit this prompt.
   */
  systemPrompt: string3().optional(),
  /**
   * A request to include context from one or more MCP servers (including the caller), to be attached to the prompt.
   * The client MAY ignore this request.
   *
   * Default is "none". Values "thisServer" and "allServers" are soft-deprecated. Servers SHOULD only use these values if the client
   * declares ClientCapabilities.sampling.context. These values may be removed in future spec releases.
   */
  includeContext: _enum2(["none", "thisServer", "allServers"]).optional(),
  temperature: number3().optional(),
  /**
   * The requested maximum number of tokens to sample (to prevent runaway completions).
   *
   * The client MAY choose to sample fewer tokens than the requested maximum.
   */
  maxTokens: number3().int(),
  stopSequences: array(string3()).optional(),
  /**
   * Optional metadata to pass through to the LLM provider. The format of this metadata is provider-specific.
   */
  metadata: AssertObjectSchema.optional(),
  /**
   * Tools that the model may use during generation.
   * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
   */
  tools: array(ToolSchema).optional(),
  /**
   * Controls how the model uses tools.
   * The client MUST return an error if this field is provided but ClientCapabilities.sampling.tools is not declared.
   * Default is `{ mode: "auto" }`.
   */
  toolChoice: ToolChoiceSchema.optional()
});
var CreateMessageRequestSchema = RequestSchema.extend({
  method: literal("sampling/createMessage"),
  params: CreateMessageRequestParamsSchema
});
var CreateMessageResultSchema = ResultSchema.extend({
  /**
   * The name of the model that generated the message.
   */
  model: string3(),
  /**
   * The reason why sampling stopped, if known.
   *
   * Standard values:
   * - "endTurn": Natural end of the assistant's turn
   * - "stopSequence": A stop sequence was encountered
   * - "maxTokens": Maximum token limit was reached
   *
   * This field is an open string to allow for provider-specific stop reasons.
   */
  stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens"]).or(string3())),
  role: RoleSchema,
  /**
   * Response content. Single content block (text, image, or audio).
   */
  content: SamplingContentSchema
});
var CreateMessageResultWithToolsSchema = ResultSchema.extend({
  /**
   * The name of the model that generated the message.
   */
  model: string3(),
  /**
   * The reason why sampling stopped, if known.
   *
   * Standard values:
   * - "endTurn": Natural end of the assistant's turn
   * - "stopSequence": A stop sequence was encountered
   * - "maxTokens": Maximum token limit was reached
   * - "toolUse": The model wants to use one or more tools
   *
   * This field is an open string to allow for provider-specific stop reasons.
   */
  stopReason: optional(_enum2(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string3())),
  role: RoleSchema,
  /**
   * Response content. May be a single block or array. May include ToolUseContent if stopReason is "toolUse".
   */
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
});
var BooleanSchemaSchema = object2({
  type: literal("boolean"),
  title: string3().optional(),
  description: string3().optional(),
  default: boolean3().optional()
});
var StringSchemaSchema = object2({
  type: literal("string"),
  title: string3().optional(),
  description: string3().optional(),
  minLength: number3().optional(),
  maxLength: number3().optional(),
  format: _enum2(["email", "uri", "date", "date-time"]).optional(),
  default: string3().optional()
});
var NumberSchemaSchema = object2({
  type: _enum2(["number", "integer"]),
  title: string3().optional(),
  description: string3().optional(),
  minimum: number3().optional(),
  maximum: number3().optional(),
  default: number3().optional()
});
var UntitledSingleSelectEnumSchemaSchema = object2({
  type: literal("string"),
  title: string3().optional(),
  description: string3().optional(),
  enum: array(string3()),
  default: string3().optional()
});
var TitledSingleSelectEnumSchemaSchema = object2({
  type: literal("string"),
  title: string3().optional(),
  description: string3().optional(),
  oneOf: array(object2({
    const: string3(),
    title: string3()
  })),
  default: string3().optional()
});
var LegacyTitledEnumSchemaSchema = object2({
  type: literal("string"),
  title: string3().optional(),
  description: string3().optional(),
  enum: array(string3()),
  enumNames: array(string3()).optional(),
  default: string3().optional()
});
var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
var UntitledMultiSelectEnumSchemaSchema = object2({
  type: literal("array"),
  title: string3().optional(),
  description: string3().optional(),
  minItems: number3().optional(),
  maxItems: number3().optional(),
  items: object2({
    type: literal("string"),
    enum: array(string3())
  }),
  default: array(string3()).optional()
});
var TitledMultiSelectEnumSchemaSchema = object2({
  type: literal("array"),
  title: string3().optional(),
  description: string3().optional(),
  minItems: number3().optional(),
  maxItems: number3().optional(),
  items: object2({
    anyOf: array(object2({
      const: string3(),
      title: string3()
    }))
  }),
  default: array(string3()).optional()
});
var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
var ElicitRequestFormParamsSchema = TaskAugmentedRequestParamsSchema.extend({
  /**
   * The elicitation mode.
   *
   * Optional for backward compatibility. Clients MUST treat missing mode as "form".
   */
  mode: literal("form").optional(),
  /**
   * The message to present to the user describing what information is being requested.
   */
  message: string3(),
  /**
   * A restricted subset of JSON Schema.
   * Only top-level properties are allowed, without nesting.
   */
  requestedSchema: object2({
    type: literal("object"),
    properties: record(string3(), PrimitiveSchemaDefinitionSchema),
    required: array(string3()).optional()
  })
});
var ElicitRequestURLParamsSchema = TaskAugmentedRequestParamsSchema.extend({
  /**
   * The elicitation mode.
   */
  mode: literal("url"),
  /**
   * The message to present to the user explaining why the interaction is needed.
   */
  message: string3(),
  /**
   * The ID of the elicitation, which must be unique within the context of the server.
   * The client MUST treat this ID as an opaque value.
   */
  elicitationId: string3(),
  /**
   * The URL that the user should navigate to.
   */
  url: string3().url()
});
var ElicitRequestParamsSchema = union([ElicitRequestFormParamsSchema, ElicitRequestURLParamsSchema]);
var ElicitRequestSchema = RequestSchema.extend({
  method: literal("elicitation/create"),
  params: ElicitRequestParamsSchema
});
var ElicitationCompleteNotificationParamsSchema = NotificationsParamsSchema.extend({
  /**
   * The ID of the elicitation that completed.
   */
  elicitationId: string3()
});
var ElicitationCompleteNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/elicitation/complete"),
  params: ElicitationCompleteNotificationParamsSchema
});
var ElicitResultSchema = ResultSchema.extend({
  /**
   * The user action in response to the elicitation.
   * - "accept": User submitted the form/confirmed the action
   * - "decline": User explicitly decline the action
   * - "cancel": User dismissed without making an explicit choice
   */
  action: _enum2(["accept", "decline", "cancel"]),
  /**
   * The submitted form data, only present when action is "accept".
   * Contains values matching the requested schema.
   * Per MCP spec, content is "typically omitted" for decline/cancel actions.
   * We normalize null to undefined for leniency while maintaining type compatibility.
   */
  content: preprocess((val) => val === null ? void 0 : val, record(string3(), union([string3(), number3(), boolean3(), array(string3())])).optional())
});
var ResourceTemplateReferenceSchema = object2({
  type: literal("ref/resource"),
  /**
   * The URI or URI template of the resource.
   */
  uri: string3()
});
var PromptReferenceSchema = object2({
  type: literal("ref/prompt"),
  /**
   * The name of the prompt or prompt template
   */
  name: string3()
});
var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
  ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
  /**
   * The argument's information
   */
  argument: object2({
    /**
     * The name of the argument
     */
    name: string3(),
    /**
     * The value of the argument to use for completion matching.
     */
    value: string3()
  }),
  context: object2({
    /**
     * Previously-resolved variables in a URI template or prompt.
     */
    arguments: record(string3(), string3()).optional()
  }).optional()
});
var CompleteRequestSchema = RequestSchema.extend({
  method: literal("completion/complete"),
  params: CompleteRequestParamsSchema
});
var CompleteResultSchema = ResultSchema.extend({
  completion: looseObject({
    /**
     * An array of completion values. Must not exceed 100 items.
     */
    values: array(string3()).max(100),
    /**
     * The total number of completion options available. This can exceed the number of values actually sent in the response.
     */
    total: optional(number3().int()),
    /**
     * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
     */
    hasMore: optional(boolean3())
  })
});
var RootSchema = object2({
  /**
   * The URI identifying the root. This *must* start with file:// for now.
   */
  uri: string3().startsWith("file://"),
  /**
   * An optional name for the root.
   */
  name: string3().optional(),
  /**
   * See [MCP specification](https://github.com/modelcontextprotocol/modelcontextprotocol/blob/47339c03c143bb4ec01a26e721a1b8fe66634ebe/docs/specification/draft/basic/index.mdx#general-fields)
   * for notes on _meta usage.
   */
  _meta: record(string3(), unknown()).optional()
});
var ListRootsRequestSchema = RequestSchema.extend({
  method: literal("roots/list"),
  params: BaseRequestParamsSchema.optional()
});
var ListRootsResultSchema = ResultSchema.extend({
  roots: array(RootSchema)
});
var RootsListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/roots/list_changed"),
  params: NotificationsParamsSchema.optional()
});
var ClientRequestSchema = union([
  PingRequestSchema,
  InitializeRequestSchema,
  CompleteRequestSchema,
  SetLevelRequestSchema,
  GetPromptRequestSchema,
  ListPromptsRequestSchema,
  ListResourcesRequestSchema,
  ListResourceTemplatesRequestSchema,
  ReadResourceRequestSchema,
  SubscribeRequestSchema,
  UnsubscribeRequestSchema,
  CallToolRequestSchema,
  ListToolsRequestSchema,
  GetTaskRequestSchema,
  GetTaskPayloadRequestSchema,
  ListTasksRequestSchema,
  CancelTaskRequestSchema
]);
var ClientNotificationSchema = union([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  InitializedNotificationSchema,
  RootsListChangedNotificationSchema,
  TaskStatusNotificationSchema
]);
var ClientResultSchema = union([
  EmptyResultSchema,
  CreateMessageResultSchema,
  CreateMessageResultWithToolsSchema,
  ElicitResultSchema,
  ListRootsResultSchema,
  GetTaskResultSchema,
  ListTasksResultSchema,
  CreateTaskResultSchema
]);
var ServerRequestSchema = union([
  PingRequestSchema,
  CreateMessageRequestSchema,
  ElicitRequestSchema,
  ListRootsRequestSchema,
  GetTaskRequestSchema,
  GetTaskPayloadRequestSchema,
  ListTasksRequestSchema,
  CancelTaskRequestSchema
]);
var ServerNotificationSchema = union([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  LoggingMessageNotificationSchema,
  ResourceUpdatedNotificationSchema,
  ResourceListChangedNotificationSchema,
  ToolListChangedNotificationSchema,
  PromptListChangedNotificationSchema,
  TaskStatusNotificationSchema,
  ElicitationCompleteNotificationSchema
]);
var ServerResultSchema = union([
  EmptyResultSchema,
  InitializeResultSchema,
  CompleteResultSchema,
  GetPromptResultSchema,
  ListPromptsResultSchema,
  ListResourcesResultSchema,
  ListResourceTemplatesResultSchema,
  ReadResourceResultSchema,
  CallToolResultSchema,
  ListToolsResultSchema,
  GetTaskResultSchema,
  ListTasksResultSchema,
  CreateTaskResultSchema
]);
var McpError = class _McpError extends Error {
  constructor(code, message, data) {
    super(`MCP error ${code}: ${message}`);
    this.code = code;
    this.data = data;
    this.name = "McpError";
  }
  /**
   * Factory method to create the appropriate error type based on the error code and data
   */
  static fromError(code, message, data) {
    if (code === ErrorCode.UrlElicitationRequired && data) {
      const errorData = data;
      if (errorData.elicitations) {
        return new UrlElicitationRequiredError(errorData.elicitations, message);
      }
    }
    return new _McpError(code, message, data);
  }
};
var UrlElicitationRequiredError = class extends McpError {
  constructor(elicitations, message = `URL elicitation${elicitations.length > 1 ? "s" : ""} required`) {
    super(ErrorCode.UrlElicitationRequired, message, {
      elicitations
    });
  }
  get elicitations() {
    var _a3, _b2;
    return (_b2 = (_a3 = this.data) == null ? void 0 : _a3.elicitations) != null ? _b2 : [];
  }
};

// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/interfaces.js
function isTerminal(status) {
  return status === "completed" || status === "failed" || status === "cancelled";
}

// node_modules/zod-to-json-schema/dist/esm/parsers/string.js
var ALPHA_NUMERIC = new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
function getMethodLiteral(schema) {
  const shape = getObjectShape(schema);
  const methodSchema = shape == null ? void 0 : shape.method;
  if (!methodSchema) {
    throw new Error("Schema is missing a method literal");
  }
  const value = getLiteralValue(methodSchema);
  if (typeof value !== "string") {
    throw new Error("Schema method literal must be a string");
  }
  return value;
}
function parseWithCompat(schema, data) {
  const result = safeParse2(schema, data);
  if (!result.success) {
    throw result.error;
  }
  return result.data;
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/protocol.js
var DEFAULT_REQUEST_TIMEOUT_MSEC = 6e4;
var Protocol = class {
  constructor(_options) {
    this._options = _options;
    this._requestMessageId = 0;
    this._requestHandlers = /* @__PURE__ */ new Map();
    this._requestHandlerAbortControllers = /* @__PURE__ */ new Map();
    this._notificationHandlers = /* @__PURE__ */ new Map();
    this._responseHandlers = /* @__PURE__ */ new Map();
    this._progressHandlers = /* @__PURE__ */ new Map();
    this._timeoutInfo = /* @__PURE__ */ new Map();
    this._pendingDebouncedNotifications = /* @__PURE__ */ new Set();
    this._taskProgressTokens = /* @__PURE__ */ new Map();
    this._requestResolvers = /* @__PURE__ */ new Map();
    this.setNotificationHandler(CancelledNotificationSchema, (notification) => {
      this._oncancel(notification);
    });
    this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
      this._onprogress(notification);
    });
    this.setRequestHandler(
      PingRequestSchema,
      // Automatic pong by default.
      (_request) => ({})
    );
    this._taskStore = _options == null ? void 0 : _options.taskStore;
    this._taskMessageQueue = _options == null ? void 0 : _options.taskMessageQueue;
    if (this._taskStore) {
      this.setRequestHandler(GetTaskRequestSchema, async (request, extra) => {
        const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
        if (!task) {
          throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
        }
        return {
          ...task
        };
      });
      this.setRequestHandler(GetTaskPayloadRequestSchema, async (request, extra) => {
        const handleTaskResult = async () => {
          var _a3;
          const taskId = request.params.taskId;
          if (this._taskMessageQueue) {
            let queuedMessage;
            while (queuedMessage = await this._taskMessageQueue.dequeue(taskId, extra.sessionId)) {
              if (queuedMessage.type === "response" || queuedMessage.type === "error") {
                const message = queuedMessage.message;
                const requestId = message.id;
                const resolver = this._requestResolvers.get(requestId);
                if (resolver) {
                  this._requestResolvers.delete(requestId);
                  if (queuedMessage.type === "response") {
                    resolver(message);
                  } else {
                    const errorMessage = message;
                    const error48 = new McpError(errorMessage.error.code, errorMessage.error.message, errorMessage.error.data);
                    resolver(error48);
                  }
                } else {
                  const messageType = queuedMessage.type === "response" ? "Response" : "Error";
                  this._onerror(new Error(`${messageType} handler missing for request ${requestId}`));
                }
                continue;
              }
              await ((_a3 = this._transport) == null ? void 0 : _a3.send(queuedMessage.message, { relatedRequestId: extra.requestId }));
            }
          }
          const task = await this._taskStore.getTask(taskId, extra.sessionId);
          if (!task) {
            throw new McpError(ErrorCode.InvalidParams, `Task not found: ${taskId}`);
          }
          if (!isTerminal(task.status)) {
            await this._waitForTaskUpdate(taskId, extra.signal);
            return await handleTaskResult();
          }
          if (isTerminal(task.status)) {
            const result = await this._taskStore.getTaskResult(taskId, extra.sessionId);
            this._clearTaskQueue(taskId);
            return {
              ...result,
              _meta: {
                ...result._meta,
                [RELATED_TASK_META_KEY]: {
                  taskId
                }
              }
            };
          }
          return await handleTaskResult();
        };
        return await handleTaskResult();
      });
      this.setRequestHandler(ListTasksRequestSchema, async (request, extra) => {
        var _a3;
        try {
          const { tasks, nextCursor } = await this._taskStore.listTasks((_a3 = request.params) == null ? void 0 : _a3.cursor, extra.sessionId);
          return {
            tasks,
            nextCursor,
            _meta: {}
          };
        } catch (error48) {
          throw new McpError(ErrorCode.InvalidParams, `Failed to list tasks: ${error48 instanceof Error ? error48.message : String(error48)}`);
        }
      });
      this.setRequestHandler(CancelTaskRequestSchema, async (request, extra) => {
        try {
          const task = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
          if (!task) {
            throw new McpError(ErrorCode.InvalidParams, `Task not found: ${request.params.taskId}`);
          }
          if (isTerminal(task.status)) {
            throw new McpError(ErrorCode.InvalidParams, `Cannot cancel task in terminal status: ${task.status}`);
          }
          await this._taskStore.updateTaskStatus(request.params.taskId, "cancelled", "Client cancelled task execution.", extra.sessionId);
          this._clearTaskQueue(request.params.taskId);
          const cancelledTask = await this._taskStore.getTask(request.params.taskId, extra.sessionId);
          if (!cancelledTask) {
            throw new McpError(ErrorCode.InvalidParams, `Task not found after cancellation: ${request.params.taskId}`);
          }
          return {
            _meta: {},
            ...cancelledTask
          };
        } catch (error48) {
          if (error48 instanceof McpError) {
            throw error48;
          }
          throw new McpError(ErrorCode.InvalidRequest, `Failed to cancel task: ${error48 instanceof Error ? error48.message : String(error48)}`);
        }
      });
    }
  }
  async _oncancel(notification) {
    if (!notification.params.requestId) {
      return;
    }
    const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
    controller == null ? void 0 : controller.abort(notification.params.reason);
  }
  _setupTimeout(messageId, timeout, maxTotalTimeout, onTimeout, resetTimeoutOnProgress = false) {
    this._timeoutInfo.set(messageId, {
      timeoutId: setTimeout(onTimeout, timeout),
      startTime: Date.now(),
      timeout,
      maxTotalTimeout,
      resetTimeoutOnProgress,
      onTimeout
    });
  }
  _resetTimeout(messageId) {
    const info = this._timeoutInfo.get(messageId);
    if (!info)
      return false;
    const totalElapsed = Date.now() - info.startTime;
    if (info.maxTotalTimeout && totalElapsed >= info.maxTotalTimeout) {
      this._timeoutInfo.delete(messageId);
      throw McpError.fromError(ErrorCode.RequestTimeout, "Maximum total timeout exceeded", {
        maxTotalTimeout: info.maxTotalTimeout,
        totalElapsed
      });
    }
    clearTimeout(info.timeoutId);
    info.timeoutId = setTimeout(info.onTimeout, info.timeout);
    return true;
  }
  _cleanupTimeout(messageId) {
    const info = this._timeoutInfo.get(messageId);
    if (info) {
      clearTimeout(info.timeoutId);
      this._timeoutInfo.delete(messageId);
    }
  }
  /**
   * Attaches to the given transport, starts it, and starts listening for messages.
   *
   * The Protocol object assumes ownership of the Transport, replacing any callbacks that have already been set, and expects that it is the only user of the Transport instance going forward.
   */
  async connect(transport) {
    var _a3, _b2, _c;
    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 = transport;
    const _onclose = (_a3 = this.transport) == null ? void 0 : _a3.onclose;
    this._transport.onclose = () => {
      _onclose == null ? void 0 : _onclose();
      this._onclose();
    };
    const _onerror = (_b2 = this.transport) == null ? void 0 : _b2.onerror;
    this._transport.onerror = (error48) => {
      _onerror == null ? void 0 : _onerror(error48);
      this._onerror(error48);
    };
    const _onmessage = (_c = this._transport) == null ? void 0 : _c.onmessage;
    this._transport.onmessage = (message, extra) => {
      _onmessage == null ? void 0 : _onmessage(message, extra);
      if (isJSONRPCResultResponse(message) || isJSONRPCErrorResponse(message)) {
        this._onresponse(message);
      } else if (isJSONRPCRequest(message)) {
        this._onrequest(message, extra);
      } else if (isJSONRPCNotification(message)) {
        this._onnotification(message);
      } else {
        this._onerror(new Error(`Unknown message type: ${JSON.stringify(message)}`));
      }
    };
    await this._transport.start();
  }
  _onclose() {
    var _a3;
    const responseHandlers = this._responseHandlers;
    this._responseHandlers = /* @__PURE__ */ new Map();
    this._progressHandlers.clear();
    this._taskProgressTokens.clear();
    this._pendingDebouncedNotifications.clear();
    for (const info of this._timeoutInfo.values()) {
      clearTimeout(info.timeoutId);
    }
    this._timeoutInfo.clear();
    for (const controller of this._requestHandlerAbortControllers.values()) {
      controller.abort();
    }
    this._requestHandlerAbortControllers.clear();
    const error48 = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
    this._transport = void 0;
    (_a3 = this.onclose) == null ? void 0 : _a3.call(this);
    for (const handler of responseHandlers.values()) {
      handler(error48);
    }
  }
  _onerror(error48) {
    var _a3;
    (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error48);
  }
  _onnotification(notification) {
    var _a3;
    const handler = (_a3 = this._notificationHandlers.get(notification.method)) != null ? _a3 : this.fallbackNotificationHandler;
    if (handler === void 0) {
      return;
    }
    Promise.resolve().then(() => handler(notification)).catch((error48) => this._onerror(new Error(`Uncaught error in notification handler: ${error48}`)));
  }
  _onrequest(request, extra) {
    var _a3, _b2, _c, _d2, _e;
    const handler = (_a3 = this._requestHandlers.get(request.method)) != null ? _a3 : this.fallbackRequestHandler;
    const capturedTransport = this._transport;
    const relatedTaskId = (_d2 = (_c = (_b2 = request.params) == null ? void 0 : _b2._meta) == null ? void 0 : _c[RELATED_TASK_META_KEY]) == null ? void 0 : _d2.taskId;
    if (handler === void 0) {
      const errorResponse = {
        jsonrpc: "2.0",
        id: request.id,
        error: {
          code: ErrorCode.MethodNotFound,
          message: "Method not found"
        }
      };
      if (relatedTaskId && this._taskMessageQueue) {
        this._enqueueTaskMessage(relatedTaskId, {
          type: "error",
          message: errorResponse,
          timestamp: Date.now()
        }, capturedTransport == null ? void 0 : capturedTransport.sessionId).catch((error48) => this._onerror(new Error(`Failed to enqueue error response: ${error48}`)));
      } else {
        capturedTransport == null ? void 0 : capturedTransport.send(errorResponse).catch((error48) => this._onerror(new Error(`Failed to send an error response: ${error48}`)));
      }
      return;
    }
    const abortController = new AbortController();
    this._requestHandlerAbortControllers.set(request.id, abortController);
    const taskCreationParams = isTaskAugmentedRequestParams(request.params) ? request.params.task : void 0;
    const taskStore = this._taskStore ? this.requestTaskStore(request, capturedTransport == null ? void 0 : capturedTransport.sessionId) : void 0;
    const fullExtra = {
      signal: abortController.signal,
      sessionId: capturedTransport == null ? void 0 : capturedTransport.sessionId,
      _meta: (_e = request.params) == null ? void 0 : _e._meta,
      sendNotification: async (notification) => {
        if (abortController.signal.aborted)
          return;
        const notificationOptions = { relatedRequestId: request.id };
        if (relatedTaskId) {
          notificationOptions.relatedTask = { taskId: relatedTaskId };
        }
        await this.notification(notification, notificationOptions);
      },
      sendRequest: async (r2, resultSchema, options) => {
        var _a4, _b3;
        if (abortController.signal.aborted) {
          throw new McpError(ErrorCode.ConnectionClosed, "Request was cancelled");
        }
        const requestOptions = { ...options, relatedRequestId: request.id };
        if (relatedTaskId && !requestOptions.relatedTask) {
          requestOptions.relatedTask = { taskId: relatedTaskId };
        }
        const effectiveTaskId = (_b3 = (_a4 = requestOptions.relatedTask) == null ? void 0 : _a4.taskId) != null ? _b3 : relatedTaskId;
        if (effectiveTaskId && taskStore) {
          await taskStore.updateTaskStatus(effectiveTaskId, "input_required");
        }
        return await this.request(r2, resultSchema, requestOptions);
      },
      authInfo: extra == null ? void 0 : extra.authInfo,
      requestId: request.id,
      requestInfo: extra == null ? void 0 : extra.requestInfo,
      taskId: relatedTaskId,
      taskStore,
      taskRequestedTtl: taskCreationParams == null ? void 0 : taskCreationParams.ttl,
      closeSSEStream: extra == null ? void 0 : extra.closeSSEStream,
      closeStandaloneSSEStream: extra == null ? void 0 : extra.closeStandaloneSSEStream
    };
    Promise.resolve().then(() => {
      if (taskCreationParams) {
        this.assertTaskHandlerCapability(request.method);
      }
    }).then(() => handler(request, fullExtra)).then(async (result) => {
      if (abortController.signal.aborted) {
        return;
      }
      const response = {
        result,
        jsonrpc: "2.0",
        id: request.id
      };
      if (relatedTaskId && this._taskMessageQueue) {
        await this._enqueueTaskMessage(relatedTaskId, {
          type: "response",
          message: response,
          timestamp: Date.now()
        }, capturedTransport == null ? void 0 : capturedTransport.sessionId);
      } else {
        await (capturedTransport == null ? void 0 : capturedTransport.send(response));
      }
    }, async (error48) => {
      var _a4;
      if (abortController.signal.aborted) {
        return;
      }
      const errorResponse = {
        jsonrpc: "2.0",
        id: request.id,
        error: {
          code: Number.isSafeInteger(error48["code"]) ? error48["code"] : ErrorCode.InternalError,
          message: (_a4 = error48.message) != null ? _a4 : "Internal error",
          ...error48["data"] !== void 0 && { data: error48["data"] }
        }
      };
      if (relatedTaskId && this._taskMessageQueue) {
        await this._enqueueTaskMessage(relatedTaskId, {
          type: "error",
          message: errorResponse,
          timestamp: Date.now()
        }, capturedTransport == null ? void 0 : capturedTransport.sessionId);
      } else {
        await (capturedTransport == null ? void 0 : capturedTransport.send(errorResponse));
      }
    }).catch((error48) => this._onerror(new Error(`Failed to send response: ${error48}`))).finally(() => {
      if (this._requestHandlerAbortControllers.get(request.id) === abortController) {
        this._requestHandlerAbortControllers.delete(request.id);
      }
    });
  }
  _onprogress(notification) {
    const { progressToken, ...params } = notification.params;
    const messageId = Number(progressToken);
    const handler = this._progressHandlers.get(messageId);
    if (!handler) {
      this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(notification)}`));
      return;
    }
    const responseHandler = this._responseHandlers.get(messageId);
    const timeoutInfo = this._timeoutInfo.get(messageId);
    if (timeoutInfo && responseHandler && timeoutInfo.resetTimeoutOnProgress) {
      try {
        this._resetTimeout(messageId);
      } catch (error48) {
        this._responseHandlers.delete(messageId);
        this._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        responseHandler(error48);
        return;
      }
    }
    handler(params);
  }
  _onresponse(response) {
    const messageId = Number(response.id);
    const resolver = this._requestResolvers.get(messageId);
    if (resolver) {
      this._requestResolvers.delete(messageId);
      if (isJSONRPCResultResponse(response)) {
        resolver(response);
      } else {
        const error48 = new McpError(response.error.code, response.error.message, response.error.data);
        resolver(error48);
      }
      return;
    }
    const handler = this._responseHandlers.get(messageId);
    if (handler === void 0) {
      this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(response)}`));
      return;
    }
    this._responseHandlers.delete(messageId);
    this._cleanupTimeout(messageId);
    let isTaskResponse = false;
    if (isJSONRPCResultResponse(response) && response.result && typeof response.result === "object") {
      const result = response.result;
      if (result.task && typeof result.task === "object") {
        const task = result.task;
        if (typeof task.taskId === "string") {
          isTaskResponse = true;
          this._taskProgressTokens.set(task.taskId, messageId);
        }
      }
    }
    if (!isTaskResponse) {
      this._progressHandlers.delete(messageId);
    }
    if (isJSONRPCResultResponse(response)) {
      handler(response);
    } else {
      const error48 = McpError.fromError(response.error.code, response.error.message, response.error.data);
      handler(error48);
    }
  }
  get transport() {
    return this._transport;
  }
  /**
   * Closes the connection.
   */
  async close() {
    var _a3;
    await ((_a3 = this._transport) == null ? void 0 : _a3.close());
  }
  /**
   * Sends a request and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * @example
   * ```typescript
   * const stream = protocol.requestStream(request, resultSchema, options);
   * for await (const message of stream) {
   *   switch (message.type) {
   *     case 'taskCreated':
   *       console.log('Task created:', message.task.taskId);
   *       break;
   *     case 'taskStatus':
   *       console.log('Task status:', message.task.status);
   *       break;
   *     case 'result':
   *       console.log('Final result:', message.result);
   *       break;
   *     case 'error':
   *       console.error('Error:', message.error);
   *       break;
   *   }
   * }
   * ```
   *
   * @experimental Use `client.experimental.tasks.requestStream()` to access this method.
   */
  async *requestStream(request, resultSchema, options) {
    var _a3, _b2, _c, _d2;
    const { task } = options != null ? options : {};
    if (!task) {
      try {
        const result = await this.request(request, resultSchema, options);
        yield { type: "result", result };
      } catch (error48) {
        yield {
          type: "error",
          error: error48 instanceof McpError ? error48 : new McpError(ErrorCode.InternalError, String(error48))
        };
      }
      return;
    }
    let taskId;
    try {
      const createResult = await this.request(request, CreateTaskResultSchema, options);
      if (createResult.task) {
        taskId = createResult.task.taskId;
        yield { type: "taskCreated", task: createResult.task };
      } else {
        throw new McpError(ErrorCode.InternalError, "Task creation did not return a task");
      }
      while (true) {
        const task2 = await this.getTask({ taskId }, options);
        yield { type: "taskStatus", task: task2 };
        if (isTerminal(task2.status)) {
          if (task2.status === "completed") {
            const result = await this.getTaskResult({ taskId }, resultSchema, options);
            yield { type: "result", result };
          } else if (task2.status === "failed") {
            yield {
              type: "error",
              error: new McpError(ErrorCode.InternalError, `Task ${taskId} failed`)
            };
          } else if (task2.status === "cancelled") {
            yield {
              type: "error",
              error: new McpError(ErrorCode.InternalError, `Task ${taskId} was cancelled`)
            };
          }
          return;
        }
        if (task2.status === "input_required") {
          const result = await this.getTaskResult({ taskId }, resultSchema, options);
          yield { type: "result", result };
          return;
        }
        const pollInterval = (_c = (_b2 = task2.pollInterval) != null ? _b2 : (_a3 = this._options) == null ? void 0 : _a3.defaultTaskPollInterval) != null ? _c : 1e3;
        await new Promise((resolve8) => setTimeout(resolve8, pollInterval));
        (_d2 = options == null ? void 0 : options.signal) == null ? void 0 : _d2.throwIfAborted();
      }
    } catch (error48) {
      yield {
        type: "error",
        error: error48 instanceof McpError ? error48 : new McpError(ErrorCode.InternalError, String(error48))
      };
    }
  }
  /**
   * Sends a request and waits for a response.
   *
   * Do not use this method to emit notifications! Use notification() instead.
   */
  request(request, resultSchema, options) {
    const { relatedRequestId, resumptionToken, onresumptiontoken, task, relatedTask } = options != null ? options : {};
    return new Promise((resolve8, reject) => {
      var _a3, _b2, _c, _d2, _e, _f, _g;
      const earlyReject = (error48) => {
        reject(error48);
      };
      if (!this._transport) {
        earlyReject(new Error("Not connected"));
        return;
      }
      if (((_a3 = this._options) == null ? void 0 : _a3.enforceStrictCapabilities) === true) {
        try {
          this.assertCapabilityForMethod(request.method);
          if (task) {
            this.assertTaskCapability(request.method);
          }
        } catch (e2) {
          earlyReject(e2);
          return;
        }
      }
      (_b2 = options == null ? void 0 : options.signal) == null ? void 0 : _b2.throwIfAborted();
      const messageId = this._requestMessageId++;
      const jsonrpcRequest = {
        ...request,
        jsonrpc: "2.0",
        id: messageId
      };
      if (options == null ? void 0 : options.onprogress) {
        this._progressHandlers.set(messageId, options.onprogress);
        jsonrpcRequest.params = {
          ...request.params,
          _meta: {
            ...((_c = request.params) == null ? void 0 : _c._meta) || {},
            progressToken: messageId
          }
        };
      }
      if (task) {
        jsonrpcRequest.params = {
          ...jsonrpcRequest.params,
          task
        };
      }
      if (relatedTask) {
        jsonrpcRequest.params = {
          ...jsonrpcRequest.params,
          _meta: {
            ...((_d2 = jsonrpcRequest.params) == null ? void 0 : _d2._meta) || {},
            [RELATED_TASK_META_KEY]: relatedTask
          }
        };
      }
      const cancel = (reason) => {
        var _a4;
        this._responseHandlers.delete(messageId);
        this._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        (_a4 = this._transport) == null ? void 0 : _a4.send({
          jsonrpc: "2.0",
          method: "notifications/cancelled",
          params: {
            requestId: messageId,
            reason: String(reason)
          }
        }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error49) => this._onerror(new Error(`Failed to send cancellation: ${error49}`)));
        const error48 = reason instanceof McpError ? reason : new McpError(ErrorCode.RequestTimeout, String(reason));
        reject(error48);
      };
      this._responseHandlers.set(messageId, (response) => {
        var _a4;
        if ((_a4 = options == null ? void 0 : options.signal) == null ? void 0 : _a4.aborted) {
          return;
        }
        if (response instanceof Error) {
          return reject(response);
        }
        try {
          const parseResult = safeParse2(resultSchema, response.result);
          if (!parseResult.success) {
            reject(parseResult.error);
          } else {
            resolve8(parseResult.data);
          }
        } catch (error48) {
          reject(error48);
        }
      });
      (_e = options == null ? void 0 : options.signal) == null ? void 0 : _e.addEventListener("abort", () => {
        var _a4;
        cancel((_a4 = options == null ? void 0 : options.signal) == null ? void 0 : _a4.reason);
      });
      const timeout = (_f = options == null ? void 0 : options.timeout) != null ? _f : DEFAULT_REQUEST_TIMEOUT_MSEC;
      const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
      this._setupTimeout(messageId, timeout, options == null ? void 0 : options.maxTotalTimeout, timeoutHandler, (_g = options == null ? void 0 : options.resetTimeoutOnProgress) != null ? _g : false);
      const relatedTaskId = relatedTask == null ? void 0 : relatedTask.taskId;
      if (relatedTaskId) {
        const responseResolver = (response) => {
          const handler = this._responseHandlers.get(messageId);
          if (handler) {
            handler(response);
          } else {
            this._onerror(new Error(`Response handler missing for side-channeled request ${messageId}`));
          }
        };
        this._requestResolvers.set(messageId, responseResolver);
        this._enqueueTaskMessage(relatedTaskId, {
          type: "request",
          message: jsonrpcRequest,
          timestamp: Date.now()
        }).catch((error48) => {
          this._cleanupTimeout(messageId);
          reject(error48);
        });
      } else {
        this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error48) => {
          this._cleanupTimeout(messageId);
          reject(error48);
        });
      }
    });
  }
  /**
   * Gets the current status of a task.
   *
   * @experimental Use `client.experimental.tasks.getTask()` to access this method.
   */
  async getTask(params, options) {
    return this.request({ method: "tasks/get", params }, GetTaskResultSchema, options);
  }
  /**
   * Retrieves the result of a completed task.
   *
   * @experimental Use `client.experimental.tasks.getTaskResult()` to access this method.
   */
  async getTaskResult(params, resultSchema, options) {
    return this.request({ method: "tasks/result", params }, resultSchema, options);
  }
  /**
   * Lists tasks, optionally starting from a pagination cursor.
   *
   * @experimental Use `client.experimental.tasks.listTasks()` to access this method.
   */
  async listTasks(params, options) {
    return this.request({ method: "tasks/list", params }, ListTasksResultSchema, options);
  }
  /**
   * Cancels a specific task.
   *
   * @experimental Use `client.experimental.tasks.cancelTask()` to access this method.
   */
  async cancelTask(params, options) {
    return this.request({ method: "tasks/cancel", params }, CancelTaskResultSchema, options);
  }
  /**
   * Emits a notification, which is a one-way message that does not expect a response.
   */
  async notification(notification, options) {
    var _a3, _b2, _c, _d2, _e;
    if (!this._transport) {
      throw new Error("Not connected");
    }
    this.assertNotificationCapability(notification.method);
    const relatedTaskId = (_a3 = options == null ? void 0 : options.relatedTask) == null ? void 0 : _a3.taskId;
    if (relatedTaskId) {
      const jsonrpcNotification2 = {
        ...notification,
        jsonrpc: "2.0",
        params: {
          ...notification.params,
          _meta: {
            ...((_b2 = notification.params) == null ? void 0 : _b2._meta) || {},
            [RELATED_TASK_META_KEY]: options.relatedTask
          }
        }
      };
      await this._enqueueTaskMessage(relatedTaskId, {
        type: "notification",
        message: jsonrpcNotification2,
        timestamp: Date.now()
      });
      return;
    }
    const debouncedMethods = (_d2 = (_c = this._options) == null ? void 0 : _c.debouncedNotificationMethods) != null ? _d2 : [];
    const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options == null ? void 0 : options.relatedRequestId) && !(options == null ? void 0 : options.relatedTask);
    if (canDebounce) {
      if (this._pendingDebouncedNotifications.has(notification.method)) {
        return;
      }
      this._pendingDebouncedNotifications.add(notification.method);
      Promise.resolve().then(() => {
        var _a4, _b3;
        this._pendingDebouncedNotifications.delete(notification.method);
        if (!this._transport) {
          return;
        }
        let jsonrpcNotification2 = {
          ...notification,
          jsonrpc: "2.0"
        };
        if (options == null ? void 0 : options.relatedTask) {
          jsonrpcNotification2 = {
            ...jsonrpcNotification2,
            params: {
              ...jsonrpcNotification2.params,
              _meta: {
                ...((_a4 = jsonrpcNotification2.params) == null ? void 0 : _a4._meta) || {},
                [RELATED_TASK_META_KEY]: options.relatedTask
              }
            }
          };
        }
        (_b3 = this._transport) == null ? void 0 : _b3.send(jsonrpcNotification2, options).catch((error48) => this._onerror(error48));
      });
      return;
    }
    let jsonrpcNotification = {
      ...notification,
      jsonrpc: "2.0"
    };
    if (options == null ? void 0 : options.relatedTask) {
      jsonrpcNotification = {
        ...jsonrpcNotification,
        params: {
          ...jsonrpcNotification.params,
          _meta: {
            ...((_e = jsonrpcNotification.params) == null ? void 0 : _e._meta) || {},
            [RELATED_TASK_META_KEY]: options.relatedTask
          }
        }
      };
    }
    await this._transport.send(jsonrpcNotification, options);
  }
  /**
   * Registers a handler to invoke when this protocol object receives a request with the given method.
   *
   * Note that this will replace any previous request handler for the same method.
   */
  setRequestHandler(requestSchema, handler) {
    const method = getMethodLiteral(requestSchema);
    this.assertRequestHandlerCapability(method);
    this._requestHandlers.set(method, (request, extra) => {
      const parsed = parseWithCompat(requestSchema, request);
      return Promise.resolve(handler(parsed, extra));
    });
  }
  /**
   * Removes the request handler for the given method.
   */
  removeRequestHandler(method) {
    this._requestHandlers.delete(method);
  }
  /**
   * Asserts that a request handler has not already been set for the given method, in preparation for a new one being automatically installed.
   */
  assertCanSetRequestHandler(method) {
    if (this._requestHandlers.has(method)) {
      throw new Error(`A request handler for ${method} already exists, which would be overridden`);
    }
  }
  /**
   * Registers a handler to invoke when this protocol object receives a notification with the given method.
   *
   * Note that this will replace any previous notification handler for the same method.
   */
  setNotificationHandler(notificationSchema, handler) {
    const method = getMethodLiteral(notificationSchema);
    this._notificationHandlers.set(method, (notification) => {
      const parsed = parseWithCompat(notificationSchema, notification);
      return Promise.resolve(handler(parsed));
    });
  }
  /**
   * Removes the notification handler for the given method.
   */
  removeNotificationHandler(method) {
    this._notificationHandlers.delete(method);
  }
  /**
   * Cleans up the progress handler associated with a task.
   * This should be called when a task reaches a terminal status.
   */
  _cleanupTaskProgressHandler(taskId) {
    const progressToken = this._taskProgressTokens.get(taskId);
    if (progressToken !== void 0) {
      this._progressHandlers.delete(progressToken);
      this._taskProgressTokens.delete(taskId);
    }
  }
  /**
   * Enqueues a task-related message for side-channel delivery via tasks/result.
   * @param taskId The task ID to associate the message with
   * @param message The message to enqueue
   * @param sessionId Optional session ID for binding the operation to a specific session
   * @throws Error if taskStore is not configured or if enqueue fails (e.g., queue overflow)
   *
   * Note: If enqueue fails, it's the TaskMessageQueue implementation's responsibility to handle
   * the error appropriately (e.g., by failing the task, logging, etc.). The Protocol layer
   * simply propagates the error.
   */
  async _enqueueTaskMessage(taskId, message, sessionId) {
    var _a3;
    if (!this._taskStore || !this._taskMessageQueue) {
      throw new Error("Cannot enqueue task message: taskStore and taskMessageQueue are not configured");
    }
    const maxQueueSize = (_a3 = this._options) == null ? void 0 : _a3.maxTaskQueueSize;
    await this._taskMessageQueue.enqueue(taskId, message, sessionId, maxQueueSize);
  }
  /**
   * Clears the message queue for a task and rejects any pending request resolvers.
   * @param taskId The task ID whose queue should be cleared
   * @param sessionId Optional session ID for binding the operation to a specific session
   */
  async _clearTaskQueue(taskId, sessionId) {
    if (this._taskMessageQueue) {
      const messages = await this._taskMessageQueue.dequeueAll(taskId, sessionId);
      for (const message of messages) {
        if (message.type === "request" && isJSONRPCRequest(message.message)) {
          const requestId = message.message.id;
          const resolver = this._requestResolvers.get(requestId);
          if (resolver) {
            resolver(new McpError(ErrorCode.InternalError, "Task cancelled or completed"));
            this._requestResolvers.delete(requestId);
          } else {
            this._onerror(new Error(`Resolver missing for request ${requestId} during task ${taskId} cleanup`));
          }
        }
      }
    }
  }
  /**
   * Waits for a task update (new messages or status change) with abort signal support.
   * Uses polling to check for updates at the task's configured poll interval.
   * @param taskId The task ID to wait for
   * @param signal Abort signal to cancel the wait
   * @returns Promise that resolves when an update occurs or rejects if aborted
   */
  async _waitForTaskUpdate(taskId, signal) {
    var _a3, _b2, _c;
    let interval = (_b2 = (_a3 = this._options) == null ? void 0 : _a3.defaultTaskPollInterval) != null ? _b2 : 1e3;
    try {
      const task = await ((_c = this._taskStore) == null ? void 0 : _c.getTask(taskId));
      if (task == null ? void 0 : task.pollInterval) {
        interval = task.pollInterval;
      }
    } catch (e2) {
    }
    return new Promise((resolve8, reject) => {
      if (signal.aborted) {
        reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
        return;
      }
      const timeoutId = setTimeout(resolve8, interval);
      signal.addEventListener("abort", () => {
        clearTimeout(timeoutId);
        reject(new McpError(ErrorCode.InvalidRequest, "Request cancelled"));
      }, { once: true });
    });
  }
  requestTaskStore(request, sessionId) {
    const taskStore = this._taskStore;
    if (!taskStore) {
      throw new Error("No task store configured");
    }
    return {
      createTask: async (taskParams) => {
        if (!request) {
          throw new Error("No request provided");
        }
        return await taskStore.createTask(taskParams, request.id, {
          method: request.method,
          params: request.params
        }, sessionId);
      },
      getTask: async (taskId) => {
        const task = await taskStore.getTask(taskId, sessionId);
        if (!task) {
          throw new McpError(ErrorCode.InvalidParams, "Failed to retrieve task: Task not found");
        }
        return task;
      },
      storeTaskResult: async (taskId, status, result) => {
        await taskStore.storeTaskResult(taskId, status, result, sessionId);
        const task = await taskStore.getTask(taskId, sessionId);
        if (task) {
          const notification = TaskStatusNotificationSchema.parse({
            method: "notifications/tasks/status",
            params: task
          });
          await this.notification(notification);
          if (isTerminal(task.status)) {
            this._cleanupTaskProgressHandler(taskId);
          }
        }
      },
      getTaskResult: (taskId) => {
        return taskStore.getTaskResult(taskId, sessionId);
      },
      updateTaskStatus: async (taskId, status, statusMessage) => {
        const task = await taskStore.getTask(taskId, sessionId);
        if (!task) {
          throw new McpError(ErrorCode.InvalidParams, `Task "${taskId}" not found - it may have been cleaned up`);
        }
        if (isTerminal(task.status)) {
          throw new McpError(ErrorCode.InvalidParams, `Cannot update task "${taskId}" from terminal status "${task.status}" to "${status}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);
        }
        await taskStore.updateTaskStatus(taskId, status, statusMessage, sessionId);
        const updatedTask = await taskStore.getTask(taskId, sessionId);
        if (updatedTask) {
          const notification = TaskStatusNotificationSchema.parse({
            method: "notifications/tasks/status",
            params: updatedTask
          });
          await this.notification(notification);
          if (isTerminal(updatedTask.status)) {
            this._cleanupTaskProgressHandler(taskId);
          }
        }
      },
      listTasks: (cursor) => {
        return taskStore.listTasks(cursor, sessionId);
      }
    };
  }
};
function isPlainObject2(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
function mergeCapabilities(base, additional) {
  const result = { ...base };
  for (const key in additional) {
    const k10 = key;
    const addValue = additional[k10];
    if (addValue === void 0)
      continue;
    const baseValue = result[k10];
    if (isPlainObject2(baseValue) && isPlainObject2(addValue)) {
      result[k10] = { ...baseValue, ...addValue };
    } else {
      result[k10] = addValue;
    }
  }
  return result;
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/validation/ajv-provider.js
var import_ajv = __toESM(require_ajv(), 1);
var import_ajv_formats = __toESM(require_dist(), 1);
function createDefaultAjvInstance() {
  const ajv = new import_ajv.default({
    strict: false,
    validateFormats: true,
    validateSchema: false,
    allErrors: true
  });
  const addFormats = import_ajv_formats.default;
  addFormats(ajv);
  return ajv;
}
var AjvJsonSchemaValidator = class {
  /**
   * Create an AJV validator
   *
   * @param ajv - Optional pre-configured AJV instance. If not provided, a default instance will be created.
   *
   * @example
   * ```typescript
   * // Use default configuration (recommended for most cases)
   * import { AjvJsonSchemaValidator } from '@modelcontextprotocol/sdk/validation/ajv';
   * const validator = new AjvJsonSchemaValidator();
   *
   * // Or provide custom AJV instance for advanced configuration
   * import { Ajv } from 'ajv';
   * import addFormats from 'ajv-formats';
   *
   * const ajv = new Ajv({ validateFormats: true });
   * addFormats(ajv);
   * const validator = new AjvJsonSchemaValidator(ajv);
   * ```
   */
  constructor(ajv) {
    this._ajv = ajv != null ? ajv : createDefaultAjvInstance();
  }
  /**
   * Create a validator for the given JSON Schema
   *
   * The validator is compiled once and can be reused multiple times.
   * If the schema has an $id, it will be cached by AJV automatically.
   *
   * @param schema - Standard JSON Schema object
   * @returns A validator function that validates input data
   */
  getValidator(schema) {
    var _a3;
    const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? (_a3 = this._ajv.getSchema(schema.$id)) != null ? _a3 : this._ajv.compile(schema) : this._ajv.compile(schema);
    return (input) => {
      const valid = ajvValidator(input);
      if (valid) {
        return {
          valid: true,
          data: input,
          errorMessage: void 0
        };
      } else {
        return {
          valid: false,
          data: void 0,
          errorMessage: this._ajv.errorsText(ajvValidator.errors)
        };
      }
    };
  }
};

// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/client.js
var ExperimentalClientTasks = class {
  constructor(_client) {
    this._client = _client;
  }
  /**
   * Calls a tool and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * This method provides streaming access to tool execution, allowing you to
   * observe intermediate task status updates for long-running tool calls.
   * Automatically validates structured output if the tool has an outputSchema.
   *
   * @example
   * ```typescript
   * const stream = client.experimental.tasks.callToolStream({ name: 'myTool', arguments: {} });
   * for await (const message of stream) {
   *   switch (message.type) {
   *     case 'taskCreated':
   *       console.log('Tool execution started:', message.task.taskId);
   *       break;
   *     case 'taskStatus':
   *       console.log('Tool status:', message.task.status);
   *       break;
   *     case 'result':
   *       console.log('Tool result:', message.result);
   *       break;
   *     case 'error':
   *       console.error('Tool error:', message.error);
   *       break;
   *   }
   * }
   * ```
   *
   * @param params - Tool call parameters (name and arguments)
   * @param resultSchema - Zod schema for validating the result (defaults to CallToolResultSchema)
   * @param options - Optional request options (timeout, signal, task creation params, etc.)
   * @returns AsyncGenerator that yields ResponseMessage objects
   *
   * @experimental
   */
  async *callToolStream(params, resultSchema = CallToolResultSchema, options) {
    var _a3;
    const clientInternal = this._client;
    const optionsWithTask = {
      ...options,
      // We check if the tool is known to be a task during auto-configuration, but assume
      // the caller knows what they're doing if they pass this explicitly
      task: (_a3 = options == null ? void 0 : options.task) != null ? _a3 : clientInternal.isToolTask(params.name) ? {} : void 0
    };
    const stream = clientInternal.requestStream({ method: "tools/call", params }, resultSchema, optionsWithTask);
    const validator = clientInternal.getToolOutputValidator(params.name);
    for await (const message of stream) {
      if (message.type === "result" && validator) {
        const result = message.result;
        if (!result.structuredContent && !result.isError) {
          yield {
            type: "error",
            error: new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`)
          };
          return;
        }
        if (result.structuredContent) {
          try {
            const validationResult = validator(result.structuredContent);
            if (!validationResult.valid) {
              yield {
                type: "error",
                error: new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`)
              };
              return;
            }
          } catch (error48) {
            if (error48 instanceof McpError) {
              yield { type: "error", error: error48 };
              return;
            }
            yield {
              type: "error",
              error: new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error48 instanceof Error ? error48.message : String(error48)}`)
            };
            return;
          }
        }
      }
      yield message;
    }
  }
  /**
   * Gets the current status of a task.
   *
   * @param taskId - The task identifier
   * @param options - Optional request options
   * @returns The task status
   *
   * @experimental
   */
  async getTask(taskId, options) {
    return this._client.getTask({ taskId }, options);
  }
  /**
   * Retrieves the result of a completed task.
   *
   * @param taskId - The task identifier
   * @param resultSchema - Zod schema for validating the result
   * @param options - Optional request options
   * @returns The task result
   *
   * @experimental
   */
  async getTaskResult(taskId, resultSchema, options) {
    return this._client.getTaskResult({ taskId }, resultSchema, options);
  }
  /**
   * Lists tasks with optional pagination.
   *
   * @param cursor - Optional pagination cursor
   * @param options - Optional request options
   * @returns List of tasks with optional next cursor
   *
   * @experimental
   */
  async listTasks(cursor, options) {
    return this._client.listTasks(cursor ? { cursor } : void 0, options);
  }
  /**
   * Cancels a running task.
   *
   * @param taskId - The task identifier
   * @param options - Optional request options
   *
   * @experimental
   */
  async cancelTask(taskId, options) {
    return this._client.cancelTask({ taskId }, options);
  }
  /**
   * Sends a request and returns an AsyncGenerator that yields response messages.
   * The generator is guaranteed to end with either a 'result' or 'error' message.
   *
   * This method provides streaming access to request processing, allowing you to
   * observe intermediate task status updates for task-augmented requests.
   *
   * @param request - The request to send
   * @param resultSchema - Zod schema for validating the result
   * @param options - Optional request options (timeout, signal, task creation params, etc.)
   * @returns AsyncGenerator that yields ResponseMessage objects
   *
   * @experimental
   */
  requestStream(request, resultSchema, options) {
    return this._client.requestStream(request, resultSchema, options);
  }
};

// node_modules/@modelcontextprotocol/sdk/dist/esm/experimental/tasks/helpers.js
function assertToolsCallTaskCapability(requests, method, entityName) {
  var _a3;
  if (!requests) {
    throw new Error(`${entityName} does not support task creation (required for ${method})`);
  }
  switch (method) {
    case "tools/call":
      if (!((_a3 = requests.tools) == null ? void 0 : _a3.call)) {
        throw new Error(`${entityName} does not support task creation for tools/call (required for ${method})`);
      }
      break;
    default:
      break;
  }
}
function assertClientRequestTaskCapability(requests, method, entityName) {
  var _a3, _b2;
  if (!requests) {
    throw new Error(`${entityName} does not support task creation (required for ${method})`);
  }
  switch (method) {
    case "sampling/createMessage":
      if (!((_a3 = requests.sampling) == null ? void 0 : _a3.createMessage)) {
        throw new Error(`${entityName} does not support task creation for sampling/createMessage (required for ${method})`);
      }
      break;
    case "elicitation/create":
      if (!((_b2 = requests.elicitation) == null ? void 0 : _b2.create)) {
        throw new Error(`${entityName} does not support task creation for elicitation/create (required for ${method})`);
      }
      break;
    default:
      break;
  }
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/index.js
function applyElicitationDefaults(schema, data) {
  if (!schema || data === null || typeof data !== "object")
    return;
  if (schema.type === "object" && schema.properties && typeof schema.properties === "object") {
    const obj = data;
    const props = schema.properties;
    for (const key of Object.keys(props)) {
      const propSchema = props[key];
      if (obj[key] === void 0 && Object.prototype.hasOwnProperty.call(propSchema, "default")) {
        obj[key] = propSchema.default;
      }
      if (obj[key] !== void 0) {
        applyElicitationDefaults(propSchema, obj[key]);
      }
    }
  }
  if (Array.isArray(schema.anyOf)) {
    for (const sub of schema.anyOf) {
      if (typeof sub !== "boolean") {
        applyElicitationDefaults(sub, data);
      }
    }
  }
  if (Array.isArray(schema.oneOf)) {
    for (const sub of schema.oneOf) {
      if (typeof sub !== "boolean") {
        applyElicitationDefaults(sub, data);
      }
    }
  }
}
function getSupportedElicitationModes(capabilities) {
  if (!capabilities) {
    return { supportsFormMode: false, supportsUrlMode: false };
  }
  const hasFormCapability = capabilities.form !== void 0;
  const hasUrlCapability = capabilities.url !== void 0;
  const supportsFormMode = hasFormCapability || !hasFormCapability && !hasUrlCapability;
  const supportsUrlMode = hasUrlCapability;
  return { supportsFormMode, supportsUrlMode };
}
var Client = class extends Protocol {
  /**
   * Initializes this client with the given name and version information.
   */
  constructor(_clientInfo, options) {
    var _a3, _b2;
    super(options);
    this._clientInfo = _clientInfo;
    this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
    this._cachedKnownTaskTools = /* @__PURE__ */ new Set();
    this._cachedRequiredTaskTools = /* @__PURE__ */ new Set();
    this._listChangedDebounceTimers = /* @__PURE__ */ new Map();
    this._capabilities = (_a3 = options == null ? void 0 : options.capabilities) != null ? _a3 : {};
    this._jsonSchemaValidator = (_b2 = options == null ? void 0 : options.jsonSchemaValidator) != null ? _b2 : new AjvJsonSchemaValidator();
    if (options == null ? void 0 : options.listChanged) {
      this._pendingListChangedConfig = options.listChanged;
    }
  }
  /**
   * Set up handlers for list changed notifications based on config and server capabilities.
   * This should only be called after initialization when server capabilities are known.
   * Handlers are silently skipped if the server doesn't advertise the corresponding listChanged capability.
   * @internal
   */
  _setupListChangedHandlers(config2) {
    var _a3, _b2, _c, _d2, _e, _f;
    if (config2.tools && ((_b2 = (_a3 = this._serverCapabilities) == null ? void 0 : _a3.tools) == null ? void 0 : _b2.listChanged)) {
      this._setupListChangedHandler("tools", ToolListChangedNotificationSchema, config2.tools, async () => {
        const result = await this.listTools();
        return result.tools;
      });
    }
    if (config2.prompts && ((_d2 = (_c = this._serverCapabilities) == null ? void 0 : _c.prompts) == null ? void 0 : _d2.listChanged)) {
      this._setupListChangedHandler("prompts", PromptListChangedNotificationSchema, config2.prompts, async () => {
        const result = await this.listPrompts();
        return result.prompts;
      });
    }
    if (config2.resources && ((_f = (_e = this._serverCapabilities) == null ? void 0 : _e.resources) == null ? void 0 : _f.listChanged)) {
      this._setupListChangedHandler("resources", ResourceListChangedNotificationSchema, config2.resources, async () => {
        const result = await this.listResources();
        return result.resources;
      });
    }
  }
  /**
   * Access experimental features.
   *
   * WARNING: These APIs are experimental and may change without notice.
   *
   * @experimental
   */
  get experimental() {
    if (!this._experimental) {
      this._experimental = {
        tasks: new ExperimentalClientTasks(this)
      };
    }
    return this._experimental;
  }
  /**
   * Registers new capabilities. This can only be called before connecting to a transport.
   *
   * The new capabilities will be merged with any existing capabilities previously given (e.g., at initialization).
   */
  registerCapabilities(capabilities) {
    if (this.transport) {
      throw new Error("Cannot register capabilities after connecting to transport");
    }
    this._capabilities = mergeCapabilities(this._capabilities, capabilities);
  }
  /**
   * Override request handler registration to enforce client-side validation for elicitation.
   */
  setRequestHandler(requestSchema, handler) {
    var _a3, _b2, _c;
    const shape = getObjectShape(requestSchema);
    const methodSchema = shape == null ? void 0 : shape.method;
    if (!methodSchema) {
      throw new Error("Schema is missing a method literal");
    }
    let methodValue;
    if (isZ4Schema(methodSchema)) {
      const v4Schema = methodSchema;
      const v4Def = (_a3 = v4Schema._zod) == null ? void 0 : _a3.def;
      methodValue = (_b2 = v4Def == null ? void 0 : v4Def.value) != null ? _b2 : v4Schema.value;
    } else {
      const v3Schema = methodSchema;
      const legacyDef = v3Schema._def;
      methodValue = (_c = legacyDef == null ? void 0 : legacyDef.value) != null ? _c : v3Schema.value;
    }
    if (typeof methodValue !== "string") {
      throw new Error("Schema method literal must be a string");
    }
    const method = methodValue;
    if (method === "elicitation/create") {
      const wrappedHandler = async (request, extra) => {
        var _a4, _b3, _c2;
        const validatedRequest = safeParse2(ElicitRequestSchema, request);
        if (!validatedRequest.success) {
          const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation request: ${errorMessage}`);
        }
        const { params } = validatedRequest.data;
        params.mode = (_a4 = params.mode) != null ? _a4 : "form";
        const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
        if (params.mode === "form" && !supportsFormMode) {
          throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
        }
        if (params.mode === "url" && !supportsUrlMode) {
          throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
        }
        const result = await Promise.resolve(handler(request, extra));
        if (params.task) {
          const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
          if (!taskValidationResult.success) {
            const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
            throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
          }
          return taskValidationResult.data;
        }
        const validationResult = safeParse2(ElicitResultSchema, result);
        if (!validationResult.success) {
          const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid elicitation result: ${errorMessage}`);
        }
        const validatedResult = validationResult.data;
        const requestedSchema = params.mode === "form" ? params.requestedSchema : void 0;
        if (params.mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
          if ((_c2 = (_b3 = this._capabilities.elicitation) == null ? void 0 : _b3.form) == null ? void 0 : _c2.applyDefaults) {
            try {
              applyElicitationDefaults(requestedSchema, validatedResult.content);
            } catch (e2) {
            }
          }
        }
        return validatedResult;
      };
      return super.setRequestHandler(requestSchema, wrappedHandler);
    }
    if (method === "sampling/createMessage") {
      const wrappedHandler = async (request, extra) => {
        const validatedRequest = safeParse2(CreateMessageRequestSchema, request);
        if (!validatedRequest.success) {
          const errorMessage = validatedRequest.error instanceof Error ? validatedRequest.error.message : String(validatedRequest.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid sampling request: ${errorMessage}`);
        }
        const { params } = validatedRequest.data;
        const result = await Promise.resolve(handler(request, extra));
        if (params.task) {
          const taskValidationResult = safeParse2(CreateTaskResultSchema, result);
          if (!taskValidationResult.success) {
            const errorMessage = taskValidationResult.error instanceof Error ? taskValidationResult.error.message : String(taskValidationResult.error);
            throw new McpError(ErrorCode.InvalidParams, `Invalid task creation result: ${errorMessage}`);
          }
          return taskValidationResult.data;
        }
        const hasTools = params.tools || params.toolChoice;
        const resultSchema = hasTools ? CreateMessageResultWithToolsSchema : CreateMessageResultSchema;
        const validationResult = safeParse2(resultSchema, result);
        if (!validationResult.success) {
          const errorMessage = validationResult.error instanceof Error ? validationResult.error.message : String(validationResult.error);
          throw new McpError(ErrorCode.InvalidParams, `Invalid sampling result: ${errorMessage}`);
        }
        return validationResult.data;
      };
      return super.setRequestHandler(requestSchema, wrappedHandler);
    }
    return super.setRequestHandler(requestSchema, handler);
  }
  assertCapability(capability, method) {
    var _a3;
    if (!((_a3 = this._serverCapabilities) == null ? void 0 : _a3[capability])) {
      throw new Error(`Server does not support ${capability} (required for ${method})`);
    }
  }
  async connect(transport, options) {
    await super.connect(transport);
    if (transport.sessionId !== void 0) {
      return;
    }
    try {
      const result = await this.request({
        method: "initialize",
        params: {
          protocolVersion: LATEST_PROTOCOL_VERSION,
          capabilities: this._capabilities,
          clientInfo: this._clientInfo
        }
      }, InitializeResultSchema, options);
      if (result === void 0) {
        throw new Error(`Server sent invalid initialize result: ${result}`);
      }
      if (!SUPPORTED_PROTOCOL_VERSIONS.includes(result.protocolVersion)) {
        throw new Error(`Server's protocol version is not supported: ${result.protocolVersion}`);
      }
      this._serverCapabilities = result.capabilities;
      this._serverVersion = result.serverInfo;
      if (transport.setProtocolVersion) {
        transport.setProtocolVersion(result.protocolVersion);
      }
      this._instructions = result.instructions;
      await this.notification({
        method: "notifications/initialized"
      });
      if (this._pendingListChangedConfig) {
        this._setupListChangedHandlers(this._pendingListChangedConfig);
        this._pendingListChangedConfig = void 0;
      }
    } catch (error48) {
      void this.close();
      throw error48;
    }
  }
  /**
   * After initialization has completed, this will be populated with the server's reported capabilities.
   */
  getServerCapabilities() {
    return this._serverCapabilities;
  }
  /**
   * After initialization has completed, this will be populated with information about the server's name and version.
   */
  getServerVersion() {
    return this._serverVersion;
  }
  /**
   * After initialization has completed, this may be populated with information about the server's instructions.
   */
  getInstructions() {
    return this._instructions;
  }
  assertCapabilityForMethod(method) {
    var _a3, _b2, _c, _d2, _e;
    switch (method) {
      case "logging/setLevel":
        if (!((_a3 = this._serverCapabilities) == null ? void 0 : _a3.logging)) {
          throw new Error(`Server does not support logging (required for ${method})`);
        }
        break;
      case "prompts/get":
      case "prompts/list":
        if (!((_b2 = this._serverCapabilities) == null ? void 0 : _b2.prompts)) {
          throw new Error(`Server does not support prompts (required for ${method})`);
        }
        break;
      case "resources/list":
      case "resources/templates/list":
      case "resources/read":
      case "resources/subscribe":
      case "resources/unsubscribe":
        if (!((_c = this._serverCapabilities) == null ? void 0 : _c.resources)) {
          throw new Error(`Server does not support resources (required for ${method})`);
        }
        if (method === "resources/subscribe" && !this._serverCapabilities.resources.subscribe) {
          throw new Error(`Server does not support resource subscriptions (required for ${method})`);
        }
        break;
      case "tools/call":
      case "tools/list":
        if (!((_d2 = this._serverCapabilities) == null ? void 0 : _d2.tools)) {
          throw new Error(`Server does not support tools (required for ${method})`);
        }
        break;
      case "completion/complete":
        if (!((_e = this._serverCapabilities) == null ? void 0 : _e.completions)) {
          throw new Error(`Server does not support completions (required for ${method})`);
        }
        break;
      case "initialize":
        break;
      case "ping":
        break;
    }
  }
  assertNotificationCapability(method) {
    var _a3;
    switch (method) {
      case "notifications/roots/list_changed":
        if (!((_a3 = this._capabilities.roots) == null ? void 0 : _a3.listChanged)) {
          throw new Error(`Client does not support roots list changed notifications (required for ${method})`);
        }
        break;
      case "notifications/initialized":
        break;
      case "notifications/cancelled":
        break;
      case "notifications/progress":
        break;
    }
  }
  assertRequestHandlerCapability(method) {
    if (!this._capabilities) {
      return;
    }
    switch (method) {
      case "sampling/createMessage":
        if (!this._capabilities.sampling) {
          throw new Error(`Client does not support sampling capability (required for ${method})`);
        }
        break;
      case "elicitation/create":
        if (!this._capabilities.elicitation) {
          throw new Error(`Client does not support elicitation capability (required for ${method})`);
        }
        break;
      case "roots/list":
        if (!this._capabilities.roots) {
          throw new Error(`Client does not support roots capability (required for ${method})`);
        }
        break;
      case "tasks/get":
      case "tasks/list":
      case "tasks/result":
      case "tasks/cancel":
        if (!this._capabilities.tasks) {
          throw new Error(`Client does not support tasks capability (required for ${method})`);
        }
        break;
      case "ping":
        break;
    }
  }
  assertTaskCapability(method) {
    var _a3, _b2;
    assertToolsCallTaskCapability((_b2 = (_a3 = this._serverCapabilities) == null ? void 0 : _a3.tasks) == null ? void 0 : _b2.requests, method, "Server");
  }
  assertTaskHandlerCapability(method) {
    var _a3;
    if (!this._capabilities) {
      return;
    }
    assertClientRequestTaskCapability((_a3 = this._capabilities.tasks) == null ? void 0 : _a3.requests, method, "Client");
  }
  async ping(options) {
    return this.request({ method: "ping" }, EmptyResultSchema, options);
  }
  async complete(params, options) {
    return this.request({ method: "completion/complete", params }, CompleteResultSchema, options);
  }
  async setLoggingLevel(level, options) {
    return this.request({ method: "logging/setLevel", params: { level } }, EmptyResultSchema, options);
  }
  async getPrompt(params, options) {
    return this.request({ method: "prompts/get", params }, GetPromptResultSchema, options);
  }
  async listPrompts(params, options) {
    return this.request({ method: "prompts/list", params }, ListPromptsResultSchema, options);
  }
  async listResources(params, options) {
    return this.request({ method: "resources/list", params }, ListResourcesResultSchema, options);
  }
  async listResourceTemplates(params, options) {
    return this.request({ method: "resources/templates/list", params }, ListResourceTemplatesResultSchema, options);
  }
  async readResource(params, options) {
    return this.request({ method: "resources/read", params }, ReadResourceResultSchema, options);
  }
  async subscribeResource(params, options) {
    return this.request({ method: "resources/subscribe", params }, EmptyResultSchema, options);
  }
  async unsubscribeResource(params, options) {
    return this.request({ method: "resources/unsubscribe", params }, EmptyResultSchema, options);
  }
  /**
   * Calls a tool and waits for the result. Automatically validates structured output if the tool has an outputSchema.
   *
   * For task-based execution with streaming behavior, use client.experimental.tasks.callToolStream() instead.
   */
  async callTool(params, resultSchema = CallToolResultSchema, options) {
    if (this.isToolTaskRequired(params.name)) {
      throw new McpError(ErrorCode.InvalidRequest, `Tool "${params.name}" requires task-based execution. Use client.experimental.tasks.callToolStream() instead.`);
    }
    const result = await this.request({ method: "tools/call", params }, resultSchema, options);
    const validator = this.getToolOutputValidator(params.name);
    if (validator) {
      if (!result.structuredContent && !result.isError) {
        throw new McpError(ErrorCode.InvalidRequest, `Tool ${params.name} has an output schema but did not return structured content`);
      }
      if (result.structuredContent) {
        try {
          const validationResult = validator(result.structuredContent);
          if (!validationResult.valid) {
            throw new McpError(ErrorCode.InvalidParams, `Structured content does not match the tool's output schema: ${validationResult.errorMessage}`);
          }
        } catch (error48) {
          if (error48 instanceof McpError) {
            throw error48;
          }
          throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error48 instanceof Error ? error48.message : String(error48)}`);
        }
      }
    }
    return result;
  }
  isToolTask(toolName) {
    var _a3, _b2, _c, _d2;
    if (!((_d2 = (_c = (_b2 = (_a3 = this._serverCapabilities) == null ? void 0 : _a3.tasks) == null ? void 0 : _b2.requests) == null ? void 0 : _c.tools) == null ? void 0 : _d2.call)) {
      return false;
    }
    return this._cachedKnownTaskTools.has(toolName);
  }
  /**
   * Check if a tool requires task-based execution.
   * Unlike isToolTask which includes 'optional' tools, this only checks for 'required'.
   */
  isToolTaskRequired(toolName) {
    return this._cachedRequiredTaskTools.has(toolName);
  }
  /**
   * Cache validators for tool output schemas.
   * Called after listTools() to pre-compile validators for better performance.
   */
  cacheToolMetadata(tools) {
    var _a3;
    this._cachedToolOutputValidators.clear();
    this._cachedKnownTaskTools.clear();
    this._cachedRequiredTaskTools.clear();
    for (const tool of tools) {
      if (tool.outputSchema) {
        const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
        this._cachedToolOutputValidators.set(tool.name, toolValidator);
      }
      const taskSupport = (_a3 = tool.execution) == null ? void 0 : _a3.taskSupport;
      if (taskSupport === "required" || taskSupport === "optional") {
        this._cachedKnownTaskTools.add(tool.name);
      }
      if (taskSupport === "required") {
        this._cachedRequiredTaskTools.add(tool.name);
      }
    }
  }
  /**
   * Get cached validator for a tool
   */
  getToolOutputValidator(toolName) {
    return this._cachedToolOutputValidators.get(toolName);
  }
  async listTools(params, options) {
    const result = await this.request({ method: "tools/list", params }, ListToolsResultSchema, options);
    this.cacheToolMetadata(result.tools);
    return result;
  }
  /**
   * Set up a single list changed handler.
   * @internal
   */
  _setupListChangedHandler(listType, notificationSchema, options, fetcher) {
    const parseResult = ListChangedOptionsBaseSchema.safeParse(options);
    if (!parseResult.success) {
      throw new Error(`Invalid ${listType} listChanged options: ${parseResult.error.message}`);
    }
    if (typeof options.onChanged !== "function") {
      throw new Error(`Invalid ${listType} listChanged options: onChanged must be a function`);
    }
    const { autoRefresh, debounceMs } = parseResult.data;
    const { onChanged } = options;
    const refresh = async () => {
      if (!autoRefresh) {
        onChanged(null, null);
        return;
      }
      try {
        const items = await fetcher();
        onChanged(null, items);
      } catch (e2) {
        const error48 = e2 instanceof Error ? e2 : new Error(String(e2));
        onChanged(error48, null);
      }
    };
    const handler = () => {
      if (debounceMs) {
        const existingTimer = this._listChangedDebounceTimers.get(listType);
        if (existingTimer) {
          clearTimeout(existingTimer);
        }
        const timer = setTimeout(refresh, debounceMs);
        this._listChangedDebounceTimers.set(listType, timer);
      } else {
        refresh();
      }
    };
    this.setNotificationHandler(notificationSchema, handler);
  }
  async sendRootsListChanged() {
    return this.notification({ method: "notifications/roots/list_changed" });
  }
};

// node_modules/eventsource-parser/dist/index.js
var ParseError = class extends Error {
  constructor(message, options) {
    super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line;
  }
};
function noop(_arg) {
}
function createParser(callbacks) {
  if (typeof callbacks == "function")
    throw new TypeError(
      "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?"
    );
  const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks;
  let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = "";
  function feed(newChunk) {
    const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`);
    for (const line of complete)
      parseLine(line);
    incompleteLine = incomplete, isFirstChunk = false;
  }
  function parseLine(line) {
    if (line === "") {
      dispatchEvent();
      return;
    }
    if (line.startsWith(":")) {
      onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1));
      return;
    }
    const fieldSeparatorIndex = line.indexOf(":");
    if (fieldSeparatorIndex !== -1) {
      const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset);
      processField(field, value, line);
      return;
    }
    processField(line, "", line);
  }
  function processField(field, value, line) {
    switch (field) {
      case "event":
        eventType = value;
        break;
      case "data":
        data = `${data}${value}
`;
        break;
      case "id":
        id = value.includes("\0") ? void 0 : value;
        break;
      case "retry":
        /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError(
          new ParseError(`Invalid \`retry\` value: "${value}"`, {
            type: "invalid-retry",
            value,
            line
          })
        );
        break;
      default:
        onError(
          new ParseError(
            `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`,
            { type: "unknown-field", field, value, line }
          )
        );
        break;
    }
  }
  function dispatchEvent() {
    data.length > 0 && onEvent({
      id,
      event: eventType || void 0,
      // If the data buffer's last character is a U+000A LINE FEED (LF) character,
      // then remove the last character from the data buffer.
      data: data.endsWith(`
`) ? data.slice(0, -1) : data
    }), id = void 0, data = "", eventType = "";
  }
  function reset(options = {}) {
    incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = "";
  }
  return { feed, reset };
}
function splitLines(chunk) {
  const lines = [];
  let incompleteLine = "", searchIndex = 0;
  for (; searchIndex < chunk.length; ) {
    const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(`
`, searchIndex);
    let lineEnd = -1;
    if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) {
      incompleteLine = chunk.slice(searchIndex);
      break;
    } else {
      const line = chunk.slice(searchIndex, lineEnd);
      lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === `
` && searchIndex++;
    }
  }
  return [lines, incompleteLine];
}

// node_modules/eventsource/dist/index.js
var ErrorEvent = class extends Event {
  /**
   * Constructs a new `ErrorEvent` instance. This is typically not called directly,
   * but rather emitted by the `EventSource` object when an error occurs.
   *
   * @param type - The type of the event (should be "error")
   * @param errorEventInitDict - Optional properties to include in the error event
   */
  constructor(type, errorEventInitDict) {
    var _a3, _b2;
    super(type), this.code = (_a3 = errorEventInitDict == null ? void 0 : errorEventInitDict.code) != null ? _a3 : void 0, this.message = (_b2 = errorEventInitDict == null ? void 0 : errorEventInitDict.message) != null ? _b2 : void 0;
  }
  /**
   * Node.js "hides" the `message` and `code` properties of the `ErrorEvent` instance,
   * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
   * we explicitly include the properties in the `inspect` method.
   *
   * This is automatically called by Node.js when you `console.log` an instance of this class.
   *
   * @param _depth - The current depth
   * @param options - The options passed to `util.inspect`
   * @param inspect - The inspect function to use (prevents having to import it from `util`)
   * @returns A string representation of the error
   */
  [/* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom")](_depth, options, inspect) {
    return inspect(inspectableError(this), options);
  }
  /**
   * Deno "hides" the `message` and `code` properties of the `ErrorEvent` instance,
   * when it is `console.log`'ed. This makes it harder to debug errors. To ease debugging,
   * we explicitly include the properties in the `inspect` method.
   *
   * This is automatically called by Deno when you `console.log` an instance of this class.
   *
   * @param inspect - The inspect function to use (prevents having to import it from `util`)
   * @param options - The options passed to `Deno.inspect`
   * @returns A string representation of the error
   */
  [/* @__PURE__ */ Symbol.for("Deno.customInspect")](inspect, options) {
    return inspect(inspectableError(this), options);
  }
};
function syntaxError(message) {
  const DomException = globalThis.DOMException;
  return typeof DomException == "function" ? new DomException(message, "SyntaxError") : new SyntaxError(message);
}
function flattenError2(err) {
  return err instanceof Error ? "errors" in err && Array.isArray(err.errors) ? err.errors.map(flattenError2).join(", ") : "cause" in err && err.cause instanceof Error ? `${err}: ${flattenError2(err.cause)}` : err.message : `${err}`;
}
function inspectableError(err) {
  return {
    type: err.type,
    message: err.message,
    code: err.code,
    defaultPrevented: err.defaultPrevented,
    cancelable: err.cancelable,
    timeStamp: err.timeStamp
  };
}
var __typeError2 = (msg) => {
  throw TypeError(msg);
};
var __accessCheck2 = (obj, member, msg) => member.has(obj) || __typeError2("Cannot " + msg);
var __privateGet2 = (obj, member, getter) => (__accessCheck2(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
var __privateAdd2 = (obj, member, value) => member.has(obj) ? __typeError2("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
var __privateSet2 = (obj, member, value, setter) => (__accessCheck2(obj, member, "write to private field"), member.set(obj, value), value);
var __privateMethod = (obj, member, method) => (__accessCheck2(obj, member, "access private method"), method);
var _readyState;
var _url2;
var _redirectUrl;
var _withCredentials;
var _fetch;
var _reconnectInterval;
var _reconnectTimer;
var _lastEventId;
var _controller;
var _parser;
var _onError;
var _onMessage;
var _onOpen;
var _EventSource_instances;
var connect_fn;
var _onFetchResponse;
var _onFetchError;
var getRequestOptions_fn;
var _onEvent;
var _onRetryChange;
var failConnection_fn;
var scheduleReconnect_fn;
var _reconnect;
var EventSource = class extends EventTarget {
  constructor(url2, eventSourceInitDict) {
    var _a3, _b2;
    super(), __privateAdd2(this, _EventSource_instances), this.CONNECTING = 0, this.OPEN = 1, this.CLOSED = 2, __privateAdd2(this, _readyState), __privateAdd2(this, _url2), __privateAdd2(this, _redirectUrl), __privateAdd2(this, _withCredentials), __privateAdd2(this, _fetch), __privateAdd2(this, _reconnectInterval), __privateAdd2(this, _reconnectTimer), __privateAdd2(this, _lastEventId, null), __privateAdd2(this, _controller), __privateAdd2(this, _parser), __privateAdd2(this, _onError, null), __privateAdd2(this, _onMessage, null), __privateAdd2(this, _onOpen, null), __privateAdd2(this, _onFetchResponse, async (response) => {
      var _a22;
      __privateGet2(this, _parser).reset();
      const { body, redirected, status, headers } = response;
      if (status === 204) {
        __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Server sent HTTP 204, not reconnecting", 204), this.close();
        return;
      }
      if (redirected ? __privateSet2(this, _redirectUrl, new URL(response.url)) : __privateSet2(this, _redirectUrl, void 0), status !== 200) {
        __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, `Non-200 status code (${status})`, status);
        return;
      }
      if (!(headers.get("content-type") || "").startsWith("text/event-stream")) {
        __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, 'Invalid content type, expected "text/event-stream"', status);
        return;
      }
      if (__privateGet2(this, _readyState) === this.CLOSED)
        return;
      __privateSet2(this, _readyState, this.OPEN);
      const openEvent = new Event("open");
      if ((_a22 = __privateGet2(this, _onOpen)) == null || _a22.call(this, openEvent), this.dispatchEvent(openEvent), typeof body != "object" || !body || !("getReader" in body)) {
        __privateMethod(this, _EventSource_instances, failConnection_fn).call(this, "Invalid response body, expected a web ReadableStream", status), this.close();
        return;
      }
      const decoder = new TextDecoder(), reader = body.getReader();
      let open = true;
      do {
        const { done, value } = await reader.read();
        value && __privateGet2(this, _parser).feed(decoder.decode(value, { stream: !done })), done && (open = false, __privateGet2(this, _parser).reset(), __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this));
      } while (open);
    }), __privateAdd2(this, _onFetchError, (err) => {
      __privateSet2(this, _controller, void 0), !(err.name === "AbortError" || err.type === "aborted") && __privateMethod(this, _EventSource_instances, scheduleReconnect_fn).call(this, flattenError2(err));
    }), __privateAdd2(this, _onEvent, (event) => {
      typeof event.id == "string" && __privateSet2(this, _lastEventId, event.id);
      const messageEvent = new MessageEvent(event.event || "message", {
        data: event.data,
        origin: __privateGet2(this, _redirectUrl) ? __privateGet2(this, _redirectUrl).origin : __privateGet2(this, _url2).origin,
        lastEventId: event.id || ""
      });
      __privateGet2(this, _onMessage) && (!event.event || event.event === "message") && __privateGet2(this, _onMessage).call(this, messageEvent), this.dispatchEvent(messageEvent);
    }), __privateAdd2(this, _onRetryChange, (value) => {
      __privateSet2(this, _reconnectInterval, value);
    }), __privateAdd2(this, _reconnect, () => {
      __privateSet2(this, _reconnectTimer, void 0), __privateGet2(this, _readyState) === this.CONNECTING && __privateMethod(this, _EventSource_instances, connect_fn).call(this);
    });
    try {
      if (url2 instanceof URL)
        __privateSet2(this, _url2, url2);
      else if (typeof url2 == "string")
        __privateSet2(this, _url2, new URL(url2, getBaseURL()));
      else
        throw new Error("Invalid URL");
    } catch (e2) {
      throw syntaxError("An invalid or illegal string was specified");
    }
    __privateSet2(this, _parser, createParser({
      onEvent: __privateGet2(this, _onEvent),
      onRetry: __privateGet2(this, _onRetryChange)
    })), __privateSet2(this, _readyState, this.CONNECTING), __privateSet2(this, _reconnectInterval, 3e3), __privateSet2(this, _fetch, (_a3 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.fetch) != null ? _a3 : globalThis.fetch), __privateSet2(this, _withCredentials, (_b2 = eventSourceInitDict == null ? void 0 : eventSourceInitDict.withCredentials) != null ? _b2 : false), __privateMethod(this, _EventSource_instances, connect_fn).call(this);
  }
  /**
   * Returns the state of this EventSource object's connection. It can have the values described below.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/readyState)
   *
   * Note: typed as `number` instead of `0 | 1 | 2` for compatibility with the `EventSource` interface,
   * defined in the TypeScript `dom` library.
   *
   * @public
   */
  get readyState() {
    return __privateGet2(this, _readyState);
  }
  /**
   * Returns the URL providing the event stream.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/url)
   *
   * @public
   */
  get url() {
    return __privateGet2(this, _url2).href;
  }
  /**
   * Returns true if the credentials mode for connection requests to the URL providing the event stream is set to "include", and false otherwise.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/withCredentials)
   */
  get withCredentials() {
    return __privateGet2(this, _withCredentials);
  }
  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/error_event) */
  get onerror() {
    return __privateGet2(this, _onError);
  }
  set onerror(value) {
    __privateSet2(this, _onError, value);
  }
  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/message_event) */
  get onmessage() {
    return __privateGet2(this, _onMessage);
  }
  set onmessage(value) {
    __privateSet2(this, _onMessage, value);
  }
  /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/open_event) */
  get onopen() {
    return __privateGet2(this, _onOpen);
  }
  set onopen(value) {
    __privateSet2(this, _onOpen, value);
  }
  addEventListener(type, listener, options) {
    const listen = listener;
    super.addEventListener(type, listen, options);
  }
  removeEventListener(type, listener, options) {
    const listen = listener;
    super.removeEventListener(type, listen, options);
  }
  /**
   * Aborts any instances of the fetch algorithm started for this EventSource object, and sets the readyState attribute to CLOSED.
   *
   * [MDN Reference](https://developer.mozilla.org/docs/Web/API/EventSource/close)
   *
   * @public
   */
  close() {
    __privateGet2(this, _reconnectTimer) && clearTimeout(__privateGet2(this, _reconnectTimer)), __privateGet2(this, _readyState) !== this.CLOSED && (__privateGet2(this, _controller) && __privateGet2(this, _controller).abort(), __privateSet2(this, _readyState, this.CLOSED), __privateSet2(this, _controller, void 0));
  }
};
_readyState = /* @__PURE__ */ new WeakMap(), _url2 = /* @__PURE__ */ new WeakMap(), _redirectUrl = /* @__PURE__ */ new WeakMap(), _withCredentials = /* @__PURE__ */ new WeakMap(), _fetch = /* @__PURE__ */ new WeakMap(), _reconnectInterval = /* @__PURE__ */ new WeakMap(), _reconnectTimer = /* @__PURE__ */ new WeakMap(), _lastEventId = /* @__PURE__ */ new WeakMap(), _controller = /* @__PURE__ */ new WeakMap(), _parser = /* @__PURE__ */ new WeakMap(), _onError = /* @__PURE__ */ new WeakMap(), _onMessage = /* @__PURE__ */ new WeakMap(), _onOpen = /* @__PURE__ */ new WeakMap(), _EventSource_instances = /* @__PURE__ */ new WeakSet(), /**
* Connect to the given URL and start receiving events
*
* @internal
*/
connect_fn = function() {
  __privateSet2(this, _readyState, this.CONNECTING), __privateSet2(this, _controller, new AbortController()), __privateGet2(this, _fetch)(__privateGet2(this, _url2), __privateMethod(this, _EventSource_instances, getRequestOptions_fn).call(this)).then(__privateGet2(this, _onFetchResponse)).catch(__privateGet2(this, _onFetchError));
}, _onFetchResponse = /* @__PURE__ */ new WeakMap(), _onFetchError = /* @__PURE__ */ new WeakMap(), /**
* Get request options for the `fetch()` request
*
* @returns The request options
* @internal
*/
getRequestOptions_fn = function() {
  var _a3;
  const init = {
    // [spec] Let `corsAttributeState` be `Anonymous`…
    // [spec] …will have their mode set to "cors"…
    mode: "cors",
    redirect: "follow",
    headers: { Accept: "text/event-stream", ...__privateGet2(this, _lastEventId) ? { "Last-Event-ID": __privateGet2(this, _lastEventId) } : void 0 },
    cache: "no-store",
    signal: (_a3 = __privateGet2(this, _controller)) == null ? void 0 : _a3.signal
  };
  return "window" in globalThis && (init.credentials = this.withCredentials ? "include" : "same-origin"), init;
}, _onEvent = /* @__PURE__ */ new WeakMap(), _onRetryChange = /* @__PURE__ */ new WeakMap(), /**
* Handles the process referred to in the EventSource specification as "failing a connection".
*
* @param error - The error causing the connection to fail
* @param code - The HTTP status code, if available
* @internal
*/
failConnection_fn = function(message, code) {
  var _a3;
  __privateGet2(this, _readyState) !== this.CLOSED && __privateSet2(this, _readyState, this.CLOSED);
  const errorEvent = new ErrorEvent("error", { code, message });
  (_a3 = __privateGet2(this, _onError)) == null || _a3.call(this, errorEvent), this.dispatchEvent(errorEvent);
}, /**
* Schedules a reconnection attempt against the EventSource endpoint.
*
* @param message - The error causing the connection to fail
* @param code - The HTTP status code, if available
* @internal
*/
scheduleReconnect_fn = function(message, code) {
  var _a3;
  if (__privateGet2(this, _readyState) === this.CLOSED)
    return;
  __privateSet2(this, _readyState, this.CONNECTING);
  const errorEvent = new ErrorEvent("error", { code, message });
  (_a3 = __privateGet2(this, _onError)) == null || _a3.call(this, errorEvent), this.dispatchEvent(errorEvent), __privateSet2(this, _reconnectTimer, setTimeout(__privateGet2(this, _reconnect), __privateGet2(this, _reconnectInterval)));
}, _reconnect = /* @__PURE__ */ new WeakMap(), /**
* ReadyState representing an EventSource currently trying to connect
*
* @public
*/
EventSource.CONNECTING = 0, /**
* ReadyState representing an EventSource connection that is open (eg connected)
*
* @public
*/
EventSource.OPEN = 1, /**
* ReadyState representing an EventSource connection that is closed (eg disconnected)
*
* @public
*/
EventSource.CLOSED = 2;
function getBaseURL() {
  const doc = "document" in globalThis ? globalThis.document : void 0;
  return doc && typeof doc == "object" && "baseURI" in doc && typeof doc.baseURI == "string" ? doc.baseURI : void 0;
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/transport.js
function normalizeHeaders(headers) {
  if (!headers)
    return {};
  if (headers instanceof Headers) {
    return Object.fromEntries(headers.entries());
  }
  if (Array.isArray(headers)) {
    return Object.fromEntries(headers);
  }
  return { ...headers };
}
function createFetchWithInit(baseFetch = fetch, baseInit) {
  if (!baseInit) {
    return baseFetch;
  }
  return async (url2, init) => {
    const mergedInit = {
      ...baseInit,
      ...init,
      // Headers need special handling - merge instead of replace
      headers: (init == null ? void 0 : init.headers) ? { ...normalizeHeaders(baseInit.headers), ...normalizeHeaders(init.headers) } : baseInit.headers
    };
    return baseFetch(url2, mergedInit);
  };
}

// node_modules/pkce-challenge/dist/index.browser.js
var crypto;
crypto = globalThis.crypto;
async function getRandomValues(size) {
  return (await crypto).getRandomValues(new Uint8Array(size));
}
async function random(size) {
  const mask = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~";
  const evenDistCutoff = Math.pow(2, 8) - Math.pow(2, 8) % mask.length;
  let result = "";
  while (result.length < size) {
    const randomBytes = await getRandomValues(size - result.length);
    for (const randomByte of randomBytes) {
      if (randomByte < evenDistCutoff) {
        result += mask[randomByte % mask.length];
      }
    }
  }
  return result;
}
async function generateVerifier(length) {
  return await random(length);
}
async function generateChallenge(code_verifier) {
  const buffer = await (await crypto).subtle.digest("SHA-256", new TextEncoder().encode(code_verifier));
  return btoa(String.fromCharCode(...new Uint8Array(buffer))).replace(/\//g, "_").replace(/\+/g, "-").replace(/=/g, "");
}
async function pkceChallenge(length) {
  if (!length)
    length = 43;
  if (length < 43 || length > 128) {
    throw `Expected a length between 43 and 128. Received ${length}.`;
  }
  const verifier = await generateVerifier(length);
  const challenge = await generateChallenge(verifier);
  return {
    code_verifier: verifier,
    code_challenge: challenge
  };
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth.js
var SafeUrlSchema = url().superRefine((val, ctx) => {
  if (!URL.canParse(val)) {
    ctx.addIssue({
      code: ZodIssueCode2.custom,
      message: "URL must be parseable",
      fatal: true
    });
    return NEVER;
  }
}).refine((url2) => {
  const u = new URL(url2);
  return u.protocol !== "javascript:" && u.protocol !== "data:" && u.protocol !== "vbscript:";
}, { message: "URL cannot use javascript:, data:, or vbscript: scheme" });
var OAuthProtectedResourceMetadataSchema = looseObject({
  resource: string3().url(),
  authorization_servers: array(SafeUrlSchema).optional(),
  jwks_uri: string3().url().optional(),
  scopes_supported: array(string3()).optional(),
  bearer_methods_supported: array(string3()).optional(),
  resource_signing_alg_values_supported: array(string3()).optional(),
  resource_name: string3().optional(),
  resource_documentation: string3().optional(),
  resource_policy_uri: string3().url().optional(),
  resource_tos_uri: string3().url().optional(),
  tls_client_certificate_bound_access_tokens: boolean3().optional(),
  authorization_details_types_supported: array(string3()).optional(),
  dpop_signing_alg_values_supported: array(string3()).optional(),
  dpop_bound_access_tokens_required: boolean3().optional()
});
var OAuthMetadataSchema = looseObject({
  issuer: string3(),
  authorization_endpoint: SafeUrlSchema,
  token_endpoint: SafeUrlSchema,
  registration_endpoint: SafeUrlSchema.optional(),
  scopes_supported: array(string3()).optional(),
  response_types_supported: array(string3()),
  response_modes_supported: array(string3()).optional(),
  grant_types_supported: array(string3()).optional(),
  token_endpoint_auth_methods_supported: array(string3()).optional(),
  token_endpoint_auth_signing_alg_values_supported: array(string3()).optional(),
  service_documentation: SafeUrlSchema.optional(),
  revocation_endpoint: SafeUrlSchema.optional(),
  revocation_endpoint_auth_methods_supported: array(string3()).optional(),
  revocation_endpoint_auth_signing_alg_values_supported: array(string3()).optional(),
  introspection_endpoint: string3().optional(),
  introspection_endpoint_auth_methods_supported: array(string3()).optional(),
  introspection_endpoint_auth_signing_alg_values_supported: array(string3()).optional(),
  code_challenge_methods_supported: array(string3()).optional(),
  client_id_metadata_document_supported: boolean3().optional()
});
var OpenIdProviderMetadataSchema = looseObject({
  issuer: string3(),
  authorization_endpoint: SafeUrlSchema,
  token_endpoint: SafeUrlSchema,
  userinfo_endpoint: SafeUrlSchema.optional(),
  jwks_uri: SafeUrlSchema,
  registration_endpoint: SafeUrlSchema.optional(),
  scopes_supported: array(string3()).optional(),
  response_types_supported: array(string3()),
  response_modes_supported: array(string3()).optional(),
  grant_types_supported: array(string3()).optional(),
  acr_values_supported: array(string3()).optional(),
  subject_types_supported: array(string3()),
  id_token_signing_alg_values_supported: array(string3()),
  id_token_encryption_alg_values_supported: array(string3()).optional(),
  id_token_encryption_enc_values_supported: array(string3()).optional(),
  userinfo_signing_alg_values_supported: array(string3()).optional(),
  userinfo_encryption_alg_values_supported: array(string3()).optional(),
  userinfo_encryption_enc_values_supported: array(string3()).optional(),
  request_object_signing_alg_values_supported: array(string3()).optional(),
  request_object_encryption_alg_values_supported: array(string3()).optional(),
  request_object_encryption_enc_values_supported: array(string3()).optional(),
  token_endpoint_auth_methods_supported: array(string3()).optional(),
  token_endpoint_auth_signing_alg_values_supported: array(string3()).optional(),
  display_values_supported: array(string3()).optional(),
  claim_types_supported: array(string3()).optional(),
  claims_supported: array(string3()).optional(),
  service_documentation: string3().optional(),
  claims_locales_supported: array(string3()).optional(),
  ui_locales_supported: array(string3()).optional(),
  claims_parameter_supported: boolean3().optional(),
  request_parameter_supported: boolean3().optional(),
  request_uri_parameter_supported: boolean3().optional(),
  require_request_uri_registration: boolean3().optional(),
  op_policy_uri: SafeUrlSchema.optional(),
  op_tos_uri: SafeUrlSchema.optional(),
  client_id_metadata_document_supported: boolean3().optional()
});
var OpenIdProviderDiscoveryMetadataSchema = object2({
  ...OpenIdProviderMetadataSchema.shape,
  ...OAuthMetadataSchema.pick({
    code_challenge_methods_supported: true
  }).shape
});
var OAuthTokensSchema = object2({
  access_token: string3(),
  id_token: string3().optional(),
  // Optional for OAuth 2.1, but necessary in OpenID Connect
  token_type: string3(),
  expires_in: coerce_exports2.number().optional(),
  scope: string3().optional(),
  refresh_token: string3().optional()
}).strip();
var OAuthErrorResponseSchema = object2({
  error: string3(),
  error_description: string3().optional(),
  error_uri: string3().optional()
});
var OptionalSafeUrlSchema = SafeUrlSchema.optional().or(literal("").transform(() => void 0));
var OAuthClientMetadataSchema = object2({
  redirect_uris: array(SafeUrlSchema),
  token_endpoint_auth_method: string3().optional(),
  grant_types: array(string3()).optional(),
  response_types: array(string3()).optional(),
  client_name: string3().optional(),
  client_uri: SafeUrlSchema.optional(),
  logo_uri: OptionalSafeUrlSchema,
  scope: string3().optional(),
  contacts: array(string3()).optional(),
  tos_uri: OptionalSafeUrlSchema,
  policy_uri: string3().optional(),
  jwks_uri: SafeUrlSchema.optional(),
  jwks: any().optional(),
  software_id: string3().optional(),
  software_version: string3().optional(),
  software_statement: string3().optional()
}).strip();
var OAuthClientInformationSchema = object2({
  client_id: string3(),
  client_secret: string3().optional(),
  client_id_issued_at: number3().optional(),
  client_secret_expires_at: number3().optional()
}).strip();
var OAuthClientInformationFullSchema = OAuthClientMetadataSchema.merge(OAuthClientInformationSchema);
var OAuthClientRegistrationErrorSchema = object2({
  error: string3(),
  error_description: string3().optional()
}).strip();
var OAuthTokenRevocationRequestSchema = object2({
  token: string3(),
  token_type_hint: string3().optional()
}).strip();

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/auth-utils.js
function resourceUrlFromServerUrl(url2) {
  const resourceURL = typeof url2 === "string" ? new URL(url2) : new URL(url2.href);
  resourceURL.hash = "";
  return resourceURL;
}
function checkResourceAllowed({ requestedResource, configuredResource }) {
  const requested = typeof requestedResource === "string" ? new URL(requestedResource) : new URL(requestedResource.href);
  const configured = typeof configuredResource === "string" ? new URL(configuredResource) : new URL(configuredResource.href);
  if (requested.origin !== configured.origin) {
    return false;
  }
  if (requested.pathname.length < configured.pathname.length) {
    return false;
  }
  const requestedPath = requested.pathname.endsWith("/") ? requested.pathname : requested.pathname + "/";
  const configuredPath = configured.pathname.endsWith("/") ? configured.pathname : configured.pathname + "/";
  return requestedPath.startsWith(configuredPath);
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/server/auth/errors.js
var OAuthError = class extends Error {
  constructor(message, errorUri) {
    super(message);
    this.errorUri = errorUri;
    this.name = this.constructor.name;
  }
  /**
   * Converts the error to a standard OAuth error response object
   */
  toResponseObject() {
    const response = {
      error: this.errorCode,
      error_description: this.message
    };
    if (this.errorUri) {
      response.error_uri = this.errorUri;
    }
    return response;
  }
  get errorCode() {
    return this.constructor.errorCode;
  }
};
var InvalidRequestError = class extends OAuthError {
};
InvalidRequestError.errorCode = "invalid_request";
var InvalidClientError = class extends OAuthError {
};
InvalidClientError.errorCode = "invalid_client";
var InvalidGrantError = class extends OAuthError {
};
InvalidGrantError.errorCode = "invalid_grant";
var UnauthorizedClientError = class extends OAuthError {
};
UnauthorizedClientError.errorCode = "unauthorized_client";
var UnsupportedGrantTypeError = class extends OAuthError {
};
UnsupportedGrantTypeError.errorCode = "unsupported_grant_type";
var InvalidScopeError = class extends OAuthError {
};
InvalidScopeError.errorCode = "invalid_scope";
var AccessDeniedError = class extends OAuthError {
};
AccessDeniedError.errorCode = "access_denied";
var ServerError = class extends OAuthError {
};
ServerError.errorCode = "server_error";
var TemporarilyUnavailableError = class extends OAuthError {
};
TemporarilyUnavailableError.errorCode = "temporarily_unavailable";
var UnsupportedResponseTypeError = class extends OAuthError {
};
UnsupportedResponseTypeError.errorCode = "unsupported_response_type";
var UnsupportedTokenTypeError = class extends OAuthError {
};
UnsupportedTokenTypeError.errorCode = "unsupported_token_type";
var InvalidTokenError = class extends OAuthError {
};
InvalidTokenError.errorCode = "invalid_token";
var MethodNotAllowedError = class extends OAuthError {
};
MethodNotAllowedError.errorCode = "method_not_allowed";
var TooManyRequestsError = class extends OAuthError {
};
TooManyRequestsError.errorCode = "too_many_requests";
var InvalidClientMetadataError = class extends OAuthError {
};
InvalidClientMetadataError.errorCode = "invalid_client_metadata";
var InsufficientScopeError = class extends OAuthError {
};
InsufficientScopeError.errorCode = "insufficient_scope";
var InvalidTargetError = class extends OAuthError {
};
InvalidTargetError.errorCode = "invalid_target";
var OAUTH_ERRORS = {
  [InvalidRequestError.errorCode]: InvalidRequestError,
  [InvalidClientError.errorCode]: InvalidClientError,
  [InvalidGrantError.errorCode]: InvalidGrantError,
  [UnauthorizedClientError.errorCode]: UnauthorizedClientError,
  [UnsupportedGrantTypeError.errorCode]: UnsupportedGrantTypeError,
  [InvalidScopeError.errorCode]: InvalidScopeError,
  [AccessDeniedError.errorCode]: AccessDeniedError,
  [ServerError.errorCode]: ServerError,
  [TemporarilyUnavailableError.errorCode]: TemporarilyUnavailableError,
  [UnsupportedResponseTypeError.errorCode]: UnsupportedResponseTypeError,
  [UnsupportedTokenTypeError.errorCode]: UnsupportedTokenTypeError,
  [InvalidTokenError.errorCode]: InvalidTokenError,
  [MethodNotAllowedError.errorCode]: MethodNotAllowedError,
  [TooManyRequestsError.errorCode]: TooManyRequestsError,
  [InvalidClientMetadataError.errorCode]: InvalidClientMetadataError,
  [InsufficientScopeError.errorCode]: InsufficientScopeError,
  [InvalidTargetError.errorCode]: InvalidTargetError
};

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/auth.js
var UnauthorizedError = class extends Error {
  constructor(message) {
    super(message != null ? message : "Unauthorized");
  }
};
function isClientAuthMethod(method) {
  return ["client_secret_basic", "client_secret_post", "none"].includes(method);
}
var AUTHORIZATION_CODE_RESPONSE_TYPE = "code";
var AUTHORIZATION_CODE_CHALLENGE_METHOD = "S256";
function selectClientAuthMethod(clientInformation, supportedMethods) {
  const hasClientSecret = clientInformation.client_secret !== void 0;
  if ("token_endpoint_auth_method" in clientInformation && clientInformation.token_endpoint_auth_method && isClientAuthMethod(clientInformation.token_endpoint_auth_method) && (supportedMethods.length === 0 || supportedMethods.includes(clientInformation.token_endpoint_auth_method))) {
    return clientInformation.token_endpoint_auth_method;
  }
  if (supportedMethods.length === 0) {
    return hasClientSecret ? "client_secret_basic" : "none";
  }
  if (hasClientSecret && supportedMethods.includes("client_secret_basic")) {
    return "client_secret_basic";
  }
  if (hasClientSecret && supportedMethods.includes("client_secret_post")) {
    return "client_secret_post";
  }
  if (supportedMethods.includes("none")) {
    return "none";
  }
  return hasClientSecret ? "client_secret_post" : "none";
}
function applyClientAuthentication(method, clientInformation, headers, params) {
  const { client_id, client_secret } = clientInformation;
  switch (method) {
    case "client_secret_basic":
      applyBasicAuth(client_id, client_secret, headers);
      return;
    case "client_secret_post":
      applyPostAuth(client_id, client_secret, params);
      return;
    case "none":
      applyPublicAuth(client_id, params);
      return;
    default:
      throw new Error(`Unsupported client authentication method: ${method}`);
  }
}
function applyBasicAuth(clientId, clientSecret, headers) {
  if (!clientSecret) {
    throw new Error("client_secret_basic authentication requires a client_secret");
  }
  const credentials = btoa(`${clientId}:${clientSecret}`);
  headers.set("Authorization", `Basic ${credentials}`);
}
function applyPostAuth(clientId, clientSecret, params) {
  params.set("client_id", clientId);
  if (clientSecret) {
    params.set("client_secret", clientSecret);
  }
}
function applyPublicAuth(clientId, params) {
  params.set("client_id", clientId);
}
async function parseErrorResponse(input) {
  const statusCode = input instanceof Response ? input.status : void 0;
  const body = input instanceof Response ? await input.text() : input;
  try {
    const result = OAuthErrorResponseSchema.parse(JSON.parse(body));
    const { error: error48, error_description, error_uri } = result;
    const errorClass = OAUTH_ERRORS[error48] || ServerError;
    return new errorClass(error_description || "", error_uri);
  } catch (error48) {
    const errorMessage = `${statusCode ? `HTTP ${statusCode}: ` : ""}Invalid OAuth error response: ${error48}. Raw body: ${body}`;
    return new ServerError(errorMessage);
  }
}
async function auth(provider, options) {
  var _a3, _b2;
  try {
    return await authInternal(provider, options);
  } catch (error48) {
    if (error48 instanceof InvalidClientError || error48 instanceof UnauthorizedClientError) {
      await ((_a3 = provider.invalidateCredentials) == null ? void 0 : _a3.call(provider, "all"));
      return await authInternal(provider, options);
    } else if (error48 instanceof InvalidGrantError) {
      await ((_b2 = provider.invalidateCredentials) == null ? void 0 : _b2.call(provider, "tokens"));
      return await authInternal(provider, options);
    }
    throw error48;
  }
}
async function authInternal(provider, { serverUrl, authorizationCode, scope, resourceMetadataUrl, fetchFn }) {
  var _a3, _b2, _c, _d2, _e, _f;
  const cachedState = await ((_a3 = provider.discoveryState) == null ? void 0 : _a3.call(provider));
  let resourceMetadata;
  let authorizationServerUrl;
  let metadata;
  let effectiveResourceMetadataUrl = resourceMetadataUrl;
  if (!effectiveResourceMetadataUrl && (cachedState == null ? void 0 : cachedState.resourceMetadataUrl)) {
    effectiveResourceMetadataUrl = new URL(cachedState.resourceMetadataUrl);
  }
  if (cachedState == null ? void 0 : cachedState.authorizationServerUrl) {
    authorizationServerUrl = cachedState.authorizationServerUrl;
    resourceMetadata = cachedState.resourceMetadata;
    metadata = (_b2 = cachedState.authorizationServerMetadata) != null ? _b2 : await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn });
    if (!resourceMetadata) {
      try {
        resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl }, fetchFn);
      } catch (e2) {
      }
    }
    if (metadata !== cachedState.authorizationServerMetadata || resourceMetadata !== cachedState.resourceMetadata) {
      await ((_c = provider.saveDiscoveryState) == null ? void 0 : _c.call(provider, {
        authorizationServerUrl: String(authorizationServerUrl),
        resourceMetadataUrl: effectiveResourceMetadataUrl == null ? void 0 : effectiveResourceMetadataUrl.toString(),
        resourceMetadata,
        authorizationServerMetadata: metadata
      }));
    }
  } else {
    const serverInfo = await discoverOAuthServerInfo(serverUrl, { resourceMetadataUrl: effectiveResourceMetadataUrl, fetchFn });
    authorizationServerUrl = serverInfo.authorizationServerUrl;
    metadata = serverInfo.authorizationServerMetadata;
    resourceMetadata = serverInfo.resourceMetadata;
    await ((_d2 = provider.saveDiscoveryState) == null ? void 0 : _d2.call(provider, {
      authorizationServerUrl: String(authorizationServerUrl),
      resourceMetadataUrl: effectiveResourceMetadataUrl == null ? void 0 : effectiveResourceMetadataUrl.toString(),
      resourceMetadata,
      authorizationServerMetadata: metadata
    }));
  }
  const resource = await selectResourceURL(serverUrl, provider, resourceMetadata);
  const resolvedScope = scope || ((_e = resourceMetadata == null ? void 0 : resourceMetadata.scopes_supported) == null ? void 0 : _e.join(" ")) || provider.clientMetadata.scope;
  let clientInformation = await Promise.resolve(provider.clientInformation());
  if (!clientInformation) {
    if (authorizationCode !== void 0) {
      throw new Error("Existing OAuth client information is required when exchanging an authorization code");
    }
    const supportsUrlBasedClientId = (metadata == null ? void 0 : metadata.client_id_metadata_document_supported) === true;
    const clientMetadataUrl = provider.clientMetadataUrl;
    if (clientMetadataUrl && !isHttpsUrl(clientMetadataUrl)) {
      throw new InvalidClientMetadataError(`clientMetadataUrl must be a valid HTTPS URL with a non-root pathname, got: ${clientMetadataUrl}`);
    }
    const shouldUseUrlBasedClientId = supportsUrlBasedClientId && clientMetadataUrl;
    if (shouldUseUrlBasedClientId) {
      clientInformation = {
        client_id: clientMetadataUrl
      };
      await ((_f = provider.saveClientInformation) == null ? void 0 : _f.call(provider, clientInformation));
    } else {
      if (!provider.saveClientInformation) {
        throw new Error("OAuth client information must be saveable for dynamic registration");
      }
      const fullInformation = await registerClient(authorizationServerUrl, {
        metadata,
        clientMetadata: provider.clientMetadata,
        scope: resolvedScope,
        fetchFn
      });
      await provider.saveClientInformation(fullInformation);
      clientInformation = fullInformation;
    }
  }
  const nonInteractiveFlow = !provider.redirectUrl;
  if (authorizationCode !== void 0 || nonInteractiveFlow) {
    const tokens2 = await fetchToken(provider, authorizationServerUrl, {
      metadata,
      resource,
      authorizationCode,
      fetchFn
    });
    await provider.saveTokens(tokens2);
    return "AUTHORIZED";
  }
  const tokens = await provider.tokens();
  if (tokens == null ? void 0 : tokens.refresh_token) {
    try {
      const newTokens = await refreshAuthorization(authorizationServerUrl, {
        metadata,
        clientInformation,
        refreshToken: tokens.refresh_token,
        resource,
        addClientAuthentication: provider.addClientAuthentication,
        fetchFn
      });
      await provider.saveTokens(newTokens);
      return "AUTHORIZED";
    } catch (error48) {
      if (!(error48 instanceof OAuthError) || error48 instanceof ServerError) {
      } else {
        throw error48;
      }
    }
  }
  const state = provider.state ? await provider.state() : void 0;
  const { authorizationUrl, codeVerifier } = await startAuthorization(authorizationServerUrl, {
    metadata,
    clientInformation,
    state,
    redirectUrl: provider.redirectUrl,
    scope: resolvedScope,
    resource
  });
  await provider.saveCodeVerifier(codeVerifier);
  await provider.redirectToAuthorization(authorizationUrl);
  return "REDIRECT";
}
function isHttpsUrl(value) {
  if (!value)
    return false;
  try {
    const url2 = new URL(value);
    return url2.protocol === "https:" && url2.pathname !== "/";
  } catch (e2) {
    return false;
  }
}
async function selectResourceURL(serverUrl, provider, resourceMetadata) {
  const defaultResource = resourceUrlFromServerUrl(serverUrl);
  if (provider.validateResourceURL) {
    return await provider.validateResourceURL(defaultResource, resourceMetadata == null ? void 0 : resourceMetadata.resource);
  }
  if (!resourceMetadata) {
    return void 0;
  }
  if (!checkResourceAllowed({ requestedResource: defaultResource, configuredResource: resourceMetadata.resource })) {
    throw new Error(`Protected resource ${resourceMetadata.resource} does not match expected ${defaultResource} (or origin)`);
  }
  return new URL(resourceMetadata.resource);
}
function extractWWWAuthenticateParams(res) {
  const authenticateHeader = res.headers.get("WWW-Authenticate");
  if (!authenticateHeader) {
    return {};
  }
  const [type, scheme] = authenticateHeader.split(" ");
  if (type.toLowerCase() !== "bearer" || !scheme) {
    return {};
  }
  const resourceMetadataMatch = extractFieldFromWwwAuth(res, "resource_metadata") || void 0;
  let resourceMetadataUrl;
  if (resourceMetadataMatch) {
    try {
      resourceMetadataUrl = new URL(resourceMetadataMatch);
    } catch (e2) {
    }
  }
  const scope = extractFieldFromWwwAuth(res, "scope") || void 0;
  const error48 = extractFieldFromWwwAuth(res, "error") || void 0;
  return {
    resourceMetadataUrl,
    scope,
    error: error48
  };
}
function extractFieldFromWwwAuth(response, fieldName) {
  const wwwAuthHeader = response.headers.get("WWW-Authenticate");
  if (!wwwAuthHeader) {
    return null;
  }
  const pattern = new RegExp(`${fieldName}=(?:"([^"]+)"|([^\\s,]+))`);
  const match = wwwAuthHeader.match(pattern);
  if (match) {
    return match[1] || match[2];
  }
  return null;
}
async function discoverOAuthProtectedResourceMetadata(serverUrl, opts, fetchFn = fetch) {
  var _a3, _b2;
  const response = await discoverMetadataWithFallback(serverUrl, "oauth-protected-resource", fetchFn, {
    protocolVersion: opts == null ? void 0 : opts.protocolVersion,
    metadataUrl: opts == null ? void 0 : opts.resourceMetadataUrl
  });
  if (!response || response.status === 404) {
    await ((_a3 = response == null ? void 0 : response.body) == null ? void 0 : _a3.cancel());
    throw new Error(`Resource server does not implement OAuth 2.0 Protected Resource Metadata.`);
  }
  if (!response.ok) {
    await ((_b2 = response.body) == null ? void 0 : _b2.cancel());
    throw new Error(`HTTP ${response.status} trying to load well-known OAuth protected resource metadata.`);
  }
  return OAuthProtectedResourceMetadataSchema.parse(await response.json());
}
async function fetchWithCorsRetry(url2, headers, fetchFn = fetch) {
  try {
    return await fetchFn(url2, { headers });
  } catch (error48) {
    if (error48 instanceof TypeError) {
      if (headers) {
        return fetchWithCorsRetry(url2, void 0, fetchFn);
      } else {
        return void 0;
      }
    }
    throw error48;
  }
}
function buildWellKnownPath(wellKnownPrefix, pathname = "", options = {}) {
  if (pathname.endsWith("/")) {
    pathname = pathname.slice(0, -1);
  }
  return options.prependPathname ? `${pathname}/.well-known/${wellKnownPrefix}` : `/.well-known/${wellKnownPrefix}${pathname}`;
}
async function tryMetadataDiscovery(url2, protocolVersion, fetchFn = fetch) {
  const headers = {
    "MCP-Protocol-Version": protocolVersion
  };
  return await fetchWithCorsRetry(url2, headers, fetchFn);
}
function shouldAttemptFallback(response, pathname) {
  return !response || response.status >= 400 && response.status < 500 && pathname !== "/";
}
async function discoverMetadataWithFallback(serverUrl, wellKnownType, fetchFn, opts) {
  var _a3, _b2;
  const issuer = new URL(serverUrl);
  const protocolVersion = (_a3 = opts == null ? void 0 : opts.protocolVersion) != null ? _a3 : LATEST_PROTOCOL_VERSION;
  let url2;
  if (opts == null ? void 0 : opts.metadataUrl) {
    url2 = new URL(opts.metadataUrl);
  } else {
    const wellKnownPath = buildWellKnownPath(wellKnownType, issuer.pathname);
    url2 = new URL(wellKnownPath, (_b2 = opts == null ? void 0 : opts.metadataServerUrl) != null ? _b2 : issuer);
    url2.search = issuer.search;
  }
  let response = await tryMetadataDiscovery(url2, protocolVersion, fetchFn);
  if (!(opts == null ? void 0 : opts.metadataUrl) && shouldAttemptFallback(response, issuer.pathname)) {
    const rootUrl = new URL(`/.well-known/${wellKnownType}`, issuer);
    response = await tryMetadataDiscovery(rootUrl, protocolVersion, fetchFn);
  }
  return response;
}
function buildDiscoveryUrls(authorizationServerUrl) {
  const url2 = typeof authorizationServerUrl === "string" ? new URL(authorizationServerUrl) : authorizationServerUrl;
  const hasPath = url2.pathname !== "/";
  const urlsToTry = [];
  if (!hasPath) {
    urlsToTry.push({
      url: new URL("/.well-known/oauth-authorization-server", url2.origin),
      type: "oauth"
    });
    urlsToTry.push({
      url: new URL(`/.well-known/openid-configuration`, url2.origin),
      type: "oidc"
    });
    return urlsToTry;
  }
  let pathname = url2.pathname;
  if (pathname.endsWith("/")) {
    pathname = pathname.slice(0, -1);
  }
  urlsToTry.push({
    url: new URL(`/.well-known/oauth-authorization-server${pathname}`, url2.origin),
    type: "oauth"
  });
  urlsToTry.push({
    url: new URL(`/.well-known/openid-configuration${pathname}`, url2.origin),
    type: "oidc"
  });
  urlsToTry.push({
    url: new URL(`${pathname}/.well-known/openid-configuration`, url2.origin),
    type: "oidc"
  });
  return urlsToTry;
}
async function discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn = fetch, protocolVersion = LATEST_PROTOCOL_VERSION } = {}) {
  var _a3;
  const headers = {
    "MCP-Protocol-Version": protocolVersion,
    Accept: "application/json"
  };
  const urlsToTry = buildDiscoveryUrls(authorizationServerUrl);
  for (const { url: endpointUrl, type } of urlsToTry) {
    const response = await fetchWithCorsRetry(endpointUrl, headers, fetchFn);
    if (!response) {
      continue;
    }
    if (!response.ok) {
      await ((_a3 = response.body) == null ? void 0 : _a3.cancel());
      if (response.status >= 400 && response.status < 500) {
        continue;
      }
      throw new Error(`HTTP ${response.status} trying to load ${type === "oauth" ? "OAuth" : "OpenID provider"} metadata from ${endpointUrl}`);
    }
    if (type === "oauth") {
      return OAuthMetadataSchema.parse(await response.json());
    } else {
      return OpenIdProviderDiscoveryMetadataSchema.parse(await response.json());
    }
  }
  return void 0;
}
async function discoverOAuthServerInfo(serverUrl, opts) {
  let resourceMetadata;
  let authorizationServerUrl;
  try {
    resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, { resourceMetadataUrl: opts == null ? void 0 : opts.resourceMetadataUrl }, opts == null ? void 0 : opts.fetchFn);
    if (resourceMetadata.authorization_servers && resourceMetadata.authorization_servers.length > 0) {
      authorizationServerUrl = resourceMetadata.authorization_servers[0];
    }
  } catch (e2) {
  }
  if (!authorizationServerUrl) {
    authorizationServerUrl = String(new URL("/", serverUrl));
  }
  const authorizationServerMetadata = await discoverAuthorizationServerMetadata(authorizationServerUrl, { fetchFn: opts == null ? void 0 : opts.fetchFn });
  return {
    authorizationServerUrl,
    authorizationServerMetadata,
    resourceMetadata
  };
}
async function startAuthorization(authorizationServerUrl, { metadata, clientInformation, redirectUrl, scope, state, resource }) {
  let authorizationUrl;
  if (metadata) {
    authorizationUrl = new URL(metadata.authorization_endpoint);
    if (!metadata.response_types_supported.includes(AUTHORIZATION_CODE_RESPONSE_TYPE)) {
      throw new Error(`Incompatible auth server: does not support response type ${AUTHORIZATION_CODE_RESPONSE_TYPE}`);
    }
    if (metadata.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(AUTHORIZATION_CODE_CHALLENGE_METHOD)) {
      throw new Error(`Incompatible auth server: does not support code challenge method ${AUTHORIZATION_CODE_CHALLENGE_METHOD}`);
    }
  } else {
    authorizationUrl = new URL("/authorize", authorizationServerUrl);
  }
  const challenge = await pkceChallenge();
  const codeVerifier = challenge.code_verifier;
  const codeChallenge = challenge.code_challenge;
  authorizationUrl.searchParams.set("response_type", AUTHORIZATION_CODE_RESPONSE_TYPE);
  authorizationUrl.searchParams.set("client_id", clientInformation.client_id);
  authorizationUrl.searchParams.set("code_challenge", codeChallenge);
  authorizationUrl.searchParams.set("code_challenge_method", AUTHORIZATION_CODE_CHALLENGE_METHOD);
  authorizationUrl.searchParams.set("redirect_uri", String(redirectUrl));
  if (state) {
    authorizationUrl.searchParams.set("state", state);
  }
  if (scope) {
    authorizationUrl.searchParams.set("scope", scope);
  }
  if (scope == null ? void 0 : scope.includes("offline_access")) {
    authorizationUrl.searchParams.append("prompt", "consent");
  }
  if (resource) {
    authorizationUrl.searchParams.set("resource", resource.href);
  }
  return { authorizationUrl, codeVerifier };
}
function prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, redirectUri) {
  return new URLSearchParams({
    grant_type: "authorization_code",
    code: authorizationCode,
    code_verifier: codeVerifier,
    redirect_uri: String(redirectUri)
  });
}
async function executeTokenRequest(authorizationServerUrl, { metadata, tokenRequestParams, clientInformation, addClientAuthentication, resource, fetchFn }) {
  var _a3;
  const tokenUrl = (metadata == null ? void 0 : metadata.token_endpoint) ? new URL(metadata.token_endpoint) : new URL("/token", authorizationServerUrl);
  const headers = new Headers({
    "Content-Type": "application/x-www-form-urlencoded",
    Accept: "application/json"
  });
  if (resource) {
    tokenRequestParams.set("resource", resource.href);
  }
  if (addClientAuthentication) {
    await addClientAuthentication(headers, tokenRequestParams, tokenUrl, metadata);
  } else if (clientInformation) {
    const supportedMethods = (_a3 = metadata == null ? void 0 : metadata.token_endpoint_auth_methods_supported) != null ? _a3 : [];
    const authMethod = selectClientAuthMethod(clientInformation, supportedMethods);
    applyClientAuthentication(authMethod, clientInformation, headers, tokenRequestParams);
  }
  const response = await (fetchFn != null ? fetchFn : fetch)(tokenUrl, {
    method: "POST",
    headers,
    body: tokenRequestParams
  });
  if (!response.ok) {
    throw await parseErrorResponse(response);
  }
  return OAuthTokensSchema.parse(await response.json());
}
async function refreshAuthorization(authorizationServerUrl, { metadata, clientInformation, refreshToken, resource, addClientAuthentication, fetchFn }) {
  const tokenRequestParams = new URLSearchParams({
    grant_type: "refresh_token",
    refresh_token: refreshToken
  });
  const tokens = await executeTokenRequest(authorizationServerUrl, {
    metadata,
    tokenRequestParams,
    clientInformation,
    addClientAuthentication,
    resource,
    fetchFn
  });
  return { refresh_token: refreshToken, ...tokens };
}
async function fetchToken(provider, authorizationServerUrl, { metadata, resource, authorizationCode, fetchFn } = {}) {
  const scope = provider.clientMetadata.scope;
  let tokenRequestParams;
  if (provider.prepareTokenRequest) {
    tokenRequestParams = await provider.prepareTokenRequest(scope);
  }
  if (!tokenRequestParams) {
    if (!authorizationCode) {
      throw new Error("Either provider.prepareTokenRequest() or authorizationCode is required");
    }
    if (!provider.redirectUrl) {
      throw new Error("redirectUrl is required for authorization_code flow");
    }
    const codeVerifier = await provider.codeVerifier();
    tokenRequestParams = prepareAuthorizationCodeRequest(authorizationCode, codeVerifier, provider.redirectUrl);
  }
  const clientInformation = await provider.clientInformation();
  return executeTokenRequest(authorizationServerUrl, {
    metadata,
    tokenRequestParams,
    clientInformation: clientInformation != null ? clientInformation : void 0,
    addClientAuthentication: provider.addClientAuthentication,
    resource,
    fetchFn
  });
}
async function registerClient(authorizationServerUrl, { metadata, clientMetadata, scope, fetchFn }) {
  let registrationUrl;
  if (metadata) {
    if (!metadata.registration_endpoint) {
      throw new Error("Incompatible auth server: does not support dynamic client registration");
    }
    registrationUrl = new URL(metadata.registration_endpoint);
  } else {
    registrationUrl = new URL("/register", authorizationServerUrl);
  }
  const response = await (fetchFn != null ? fetchFn : fetch)(registrationUrl, {
    method: "POST",
    headers: {
      "Content-Type": "application/json"
    },
    body: JSON.stringify({
      ...clientMetadata,
      ...scope !== void 0 ? { scope } : {}
    })
  });
  if (!response.ok) {
    throw await parseErrorResponse(response);
  }
  return OAuthClientInformationFullSchema.parse(await response.json());
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/sse.js
var SseError = class extends Error {
  constructor(code, message, event) {
    super(`SSE error: ${message}`);
    this.code = code;
    this.event = event;
  }
};
var SSEClientTransport = class {
  constructor(url2, opts) {
    this._url = url2;
    this._resourceMetadataUrl = void 0;
    this._scope = void 0;
    this._eventSourceInit = opts == null ? void 0 : opts.eventSourceInit;
    this._requestInit = opts == null ? void 0 : opts.requestInit;
    this._authProvider = opts == null ? void 0 : opts.authProvider;
    this._fetch = opts == null ? void 0 : opts.fetch;
    this._fetchWithInit = createFetchWithInit(opts == null ? void 0 : opts.fetch, opts == null ? void 0 : opts.requestInit);
  }
  async _authThenStart() {
    var _a3;
    if (!this._authProvider) {
      throw new UnauthorizedError("No auth provider");
    }
    let result;
    try {
      result = await auth(this._authProvider, {
        serverUrl: this._url,
        resourceMetadataUrl: this._resourceMetadataUrl,
        scope: this._scope,
        fetchFn: this._fetchWithInit
      });
    } catch (error48) {
      (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error48);
      throw error48;
    }
    if (result !== "AUTHORIZED") {
      throw new UnauthorizedError();
    }
    return await this._startOrAuth();
  }
  async _commonHeaders() {
    var _a3;
    const headers = {};
    if (this._authProvider) {
      const tokens = await this._authProvider.tokens();
      if (tokens) {
        headers["Authorization"] = `Bearer ${tokens.access_token}`;
      }
    }
    if (this._protocolVersion) {
      headers["mcp-protocol-version"] = this._protocolVersion;
    }
    const extraHeaders = normalizeHeaders((_a3 = this._requestInit) == null ? void 0 : _a3.headers);
    return new Headers({
      ...headers,
      ...extraHeaders
    });
  }
  _startOrAuth() {
    var _a3, _b2, _c;
    const fetchImpl = (_c = (_b2 = (_a3 = this == null ? void 0 : this._eventSourceInit) == null ? void 0 : _a3.fetch) != null ? _b2 : this._fetch) != null ? _c : fetch;
    return new Promise((resolve8, reject) => {
      this._eventSource = new EventSource(this._url.href, {
        ...this._eventSourceInit,
        fetch: async (url2, init) => {
          const headers = await this._commonHeaders();
          headers.set("Accept", "text/event-stream");
          const response = await fetchImpl(url2, {
            ...init,
            headers
          });
          if (response.status === 401 && response.headers.has("www-authenticate")) {
            const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
            this._resourceMetadataUrl = resourceMetadataUrl;
            this._scope = scope;
          }
          return response;
        }
      });
      this._abortController = new AbortController();
      this._eventSource.onerror = (event) => {
        var _a4;
        if (event.code === 401 && this._authProvider) {
          this._authThenStart().then(resolve8, reject);
          return;
        }
        const error48 = new SseError(event.code, event.message, event);
        reject(error48);
        (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48);
      };
      this._eventSource.onopen = () => {
      };
      this._eventSource.addEventListener("endpoint", (event) => {
        var _a4;
        const messageEvent = event;
        try {
          this._endpoint = new URL(messageEvent.data, this._url);
          if (this._endpoint.origin !== this._url.origin) {
            throw new Error(`Endpoint origin does not match connection origin: ${this._endpoint.origin}`);
          }
        } catch (error48) {
          reject(error48);
          (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48);
          void this.close();
          return;
        }
        resolve8();
      });
      this._eventSource.onmessage = (event) => {
        var _a4, _b3;
        const messageEvent = event;
        let message;
        try {
          message = JSONRPCMessageSchema.parse(JSON.parse(messageEvent.data));
        } catch (error48) {
          (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48);
          return;
        }
        (_b3 = this.onmessage) == null ? void 0 : _b3.call(this, message);
      };
    });
  }
  async start() {
    if (this._eventSource) {
      throw new Error("SSEClientTransport already started! If using Client class, note that connect() calls start() automatically.");
    }
    return await this._startOrAuth();
  }
  /**
   * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
   */
  async finishAuth(authorizationCode) {
    if (!this._authProvider) {
      throw new UnauthorizedError("No auth provider");
    }
    const result = await auth(this._authProvider, {
      serverUrl: this._url,
      authorizationCode,
      resourceMetadataUrl: this._resourceMetadataUrl,
      scope: this._scope,
      fetchFn: this._fetchWithInit
    });
    if (result !== "AUTHORIZED") {
      throw new UnauthorizedError("Failed to authorize");
    }
  }
  async close() {
    var _a3, _b2, _c;
    (_a3 = this._abortController) == null ? void 0 : _a3.abort();
    (_b2 = this._eventSource) == null ? void 0 : _b2.close();
    (_c = this.onclose) == null ? void 0 : _c.call(this);
  }
  async send(message) {
    var _a3, _b2, _c, _d2;
    if (!this._endpoint) {
      throw new Error("Not connected");
    }
    try {
      const headers = await this._commonHeaders();
      headers.set("content-type", "application/json");
      const init = {
        ...this._requestInit,
        method: "POST",
        headers,
        body: JSON.stringify(message),
        signal: (_a3 = this._abortController) == null ? void 0 : _a3.signal
      };
      const response = await ((_b2 = this._fetch) != null ? _b2 : fetch)(this._endpoint, init);
      if (!response.ok) {
        const text = await response.text().catch(() => null);
        if (response.status === 401 && this._authProvider) {
          const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
          this._resourceMetadataUrl = resourceMetadataUrl;
          this._scope = scope;
          const result = await auth(this._authProvider, {
            serverUrl: this._url,
            resourceMetadataUrl: this._resourceMetadataUrl,
            scope: this._scope,
            fetchFn: this._fetchWithInit
          });
          if (result !== "AUTHORIZED") {
            throw new UnauthorizedError();
          }
          return this.send(message);
        }
        throw new Error(`Error POSTing to endpoint (HTTP ${response.status}): ${text}`);
      }
      await ((_c = response.body) == null ? void 0 : _c.cancel());
    } catch (error48) {
      (_d2 = this.onerror) == null ? void 0 : _d2.call(this, error48);
      throw error48;
    }
  }
  setProtocolVersion(version2) {
    this._protocolVersion = version2;
  }
};

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
var import_cross_spawn = __toESM(require_cross_spawn(), 1);
var import_node_process = __toESM(require("node:process"), 1);
var import_node_stream = require("node:stream");

// node_modules/@modelcontextprotocol/sdk/dist/esm/shared/stdio.js
var ReadBuffer = class {
  append(chunk) {
    this._buffer = this._buffer ? Buffer.concat([this._buffer, chunk]) : chunk;
  }
  readMessage() {
    if (!this._buffer) {
      return null;
    }
    const index = this._buffer.indexOf("\n");
    if (index === -1) {
      return null;
    }
    const line = this._buffer.toString("utf8", 0, index).replace(/\r$/, "");
    this._buffer = this._buffer.subarray(index + 1);
    return deserializeMessage(line);
  }
  clear() {
    this._buffer = void 0;
  }
};
function deserializeMessage(line) {
  return JSONRPCMessageSchema.parse(JSON.parse(line));
}
function serializeMessage(message) {
  return JSON.stringify(message) + "\n";
}

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/stdio.js
var DEFAULT_INHERITED_ENV_VARS = import_node_process.default.platform === "win32" ? [
  "APPDATA",
  "HOMEDRIVE",
  "HOMEPATH",
  "LOCALAPPDATA",
  "PATH",
  "PROCESSOR_ARCHITECTURE",
  "SYSTEMDRIVE",
  "SYSTEMROOT",
  "TEMP",
  "USERNAME",
  "USERPROFILE",
  "PROGRAMFILES"
] : (
  /* list inspired by the default env inheritance of sudo */
  ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"]
);
function getDefaultEnvironment() {
  const env = {};
  for (const key of DEFAULT_INHERITED_ENV_VARS) {
    const value = import_node_process.default.env[key];
    if (value === void 0) {
      continue;
    }
    if (value.startsWith("()")) {
      continue;
    }
    env[key] = value;
  }
  return env;
}
var StdioClientTransport = class {
  constructor(server) {
    this._readBuffer = new ReadBuffer();
    this._stderrStream = null;
    this._serverParams = server;
    if (server.stderr === "pipe" || server.stderr === "overlapped") {
      this._stderrStream = new import_node_stream.PassThrough();
    }
  }
  /**
   * Starts the server process and prepares to communicate with it.
   */
  async start() {
    if (this._process) {
      throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");
    }
    return new Promise((resolve8, reject) => {
      var _a3, _b2, _c, _d2, _e;
      this._process = (0, import_cross_spawn.default)(this._serverParams.command, (_a3 = this._serverParams.args) != null ? _a3 : [], {
        // merge default env with server env because mcp server needs some env vars
        env: {
          ...getDefaultEnvironment(),
          ...this._serverParams.env
        },
        stdio: ["pipe", "pipe", (_b2 = this._serverParams.stderr) != null ? _b2 : "inherit"],
        shell: false,
        windowsHide: import_node_process.default.platform === "win32",
        cwd: this._serverParams.cwd
      });
      this._process.on("error", (error48) => {
        var _a4;
        reject(error48);
        (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48);
      });
      this._process.on("spawn", () => {
        resolve8();
      });
      this._process.on("close", (_code) => {
        var _a4;
        this._process = void 0;
        (_a4 = this.onclose) == null ? void 0 : _a4.call(this);
      });
      (_c = this._process.stdin) == null ? void 0 : _c.on("error", (error48) => {
        var _a4;
        (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48);
      });
      (_d2 = this._process.stdout) == null ? void 0 : _d2.on("data", (chunk) => {
        this._readBuffer.append(chunk);
        this.processReadBuffer();
      });
      (_e = this._process.stdout) == null ? void 0 : _e.on("error", (error48) => {
        var _a4;
        (_a4 = this.onerror) == null ? void 0 : _a4.call(this, error48);
      });
      if (this._stderrStream && this._process.stderr) {
        this._process.stderr.pipe(this._stderrStream);
      }
    });
  }
  /**
   * The stderr stream of the child process, if `StdioServerParameters.stderr` was set to "pipe" or "overlapped".
   *
   * If stderr piping was requested, a PassThrough stream is returned _immediately_, allowing callers to
   * attach listeners before the start method is invoked. This prevents loss of any early
   * error output emitted by the child process.
   */
  get stderr() {
    var _a3, _b2;
    if (this._stderrStream) {
      return this._stderrStream;
    }
    return (_b2 = (_a3 = this._process) == null ? void 0 : _a3.stderr) != null ? _b2 : null;
  }
  /**
   * The child process pid spawned by this transport.
   *
   * This is only available after the transport has been started.
   */
  get pid() {
    var _a3, _b2;
    return (_b2 = (_a3 = this._process) == null ? void 0 : _a3.pid) != null ? _b2 : null;
  }
  processReadBuffer() {
    var _a3, _b2;
    while (true) {
      try {
        const message = this._readBuffer.readMessage();
        if (message === null) {
          break;
        }
        (_a3 = this.onmessage) == null ? void 0 : _a3.call(this, message);
      } catch (error48) {
        (_b2 = this.onerror) == null ? void 0 : _b2.call(this, error48);
      }
    }
  }
  async close() {
    var _a3;
    if (this._process) {
      const processToClose = this._process;
      this._process = void 0;
      const closePromise = new Promise((resolve8) => {
        processToClose.once("close", () => {
          resolve8();
        });
      });
      try {
        (_a3 = processToClose.stdin) == null ? void 0 : _a3.end();
      } catch (e2) {
      }
      await Promise.race([closePromise, new Promise((resolve8) => {
        const closeTimeout = setTimeout(resolve8, 2e3);
        closeTimeout.unref?.();
      })]);
      if (processToClose.exitCode === null) {
        try {
          processToClose.kill("SIGTERM");
        } catch (e2) {
        }
        await Promise.race([closePromise, new Promise((resolve8) => {
        const closeTimeout = setTimeout(resolve8, 2e3);
        closeTimeout.unref?.();
      })]);
      }
      if (processToClose.exitCode === null) {
        try {
          processToClose.kill("SIGKILL");
        } catch (e2) {
        }
      }
    }
    this._readBuffer.clear();
  }
  send(message) {
    return new Promise((resolve8) => {
      var _a3;
      if (!((_a3 = this._process) == null ? void 0 : _a3.stdin)) {
        throw new Error("Not connected");
      }
      const json2 = serializeMessage(message);
      if (this._process.stdin.write(json2)) {
        resolve8();
      } else {
        this._process.stdin.once("drain", resolve8);
      }
    });
  }
};

// node_modules/eventsource-parser/dist/stream.js
var EventSourceParserStream = class extends TransformStream {
  constructor({ onError, onRetry, onComment } = {}) {
    let parser;
    super({
      start(controller) {
        parser = createParser({
          onEvent: (event) => {
            controller.enqueue(event);
          },
          onError(error48) {
            onError === "terminate" ? controller.error(error48) : typeof onError == "function" && onError(error48);
          },
          onRetry,
          onComment
        });
      },
      transform(chunk) {
        parser.feed(chunk);
      }
    });
  }
};

// node_modules/@modelcontextprotocol/sdk/dist/esm/client/streamableHttp.js
var DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS = {
  initialReconnectionDelay: 1e3,
  maxReconnectionDelay: 3e4,
  reconnectionDelayGrowFactor: 1.5,
  maxRetries: 2
};
var StreamableHTTPError = class extends Error {
  constructor(code, message) {
    super(`Streamable HTTP error: ${message}`);
    this.code = code;
  }
};
var StreamableHTTPClientTransport = class {
  constructor(url2, opts) {
    var _a3;
    this._hasCompletedAuthFlow = false;
    this._url = url2;
    this._resourceMetadataUrl = void 0;
    this._scope = void 0;
    this._requestInit = opts == null ? void 0 : opts.requestInit;
    this._authProvider = opts == null ? void 0 : opts.authProvider;
    this._fetch = opts == null ? void 0 : opts.fetch;
    this._fetchWithInit = createFetchWithInit(opts == null ? void 0 : opts.fetch, opts == null ? void 0 : opts.requestInit);
    this._sessionId = opts == null ? void 0 : opts.sessionId;
    this._reconnectionOptions = (_a3 = opts == null ? void 0 : opts.reconnectionOptions) != null ? _a3 : DEFAULT_STREAMABLE_HTTP_RECONNECTION_OPTIONS;
  }
  async _authThenStart() {
    var _a3;
    if (!this._authProvider) {
      throw new UnauthorizedError("No auth provider");
    }
    let result;
    try {
      result = await auth(this._authProvider, {
        serverUrl: this._url,
        resourceMetadataUrl: this._resourceMetadataUrl,
        scope: this._scope,
        fetchFn: this._fetchWithInit
      });
    } catch (error48) {
      (_a3 = this.onerror) == null ? void 0 : _a3.call(this, error48);
      throw error48;
    }
    if (result !== "AUTHORIZED") {
      throw new UnauthorizedError();
    }
    return await this._startOrAuthSse({ resumptionToken: void 0 });
  }
  async _commonHeaders() {
    var _a3;
    const headers = {};
    if (this._authProvider) {
      const tokens = await this._authProvider.tokens();
      if (tokens) {
        headers["Authorization"] = `Bearer ${tokens.access_token}`;
      }
    }
    if (this._sessionId) {
      headers["mcp-session-id"] = this._sessionId;
    }
    if (this._protocolVersion) {
      headers["mcp-protocol-version"] = this._protocolVersion;
    }
    const extraHeaders = normalizeHeaders((_a3 = this._requestInit) == null ? void 0 : _a3.headers);
    return new Headers({
      ...headers,
      ...extraHeaders
    });
  }
  async _startOrAuthSse(options) {
    var _a3, _b2, _c, _d2;
    const { resumptionToken } = options;
    try {
      const headers = await this._commonHeaders();
      headers.set("Accept", "text/event-stream");
      if (resumptionToken) {
        headers.set("last-event-id", resumptionToken);
      }
      const response = await ((_a3 = this._fetch) != null ? _a3 : fetch)(this._url, {
        method: "GET",
        headers,
        signal: (_b2 = this._abortController) == null ? void 0 : _b2.signal
      });
      if (!response.ok) {
        await ((_c = response.body) == null ? void 0 : _c.cancel());
        if (response.status === 401 && this._authProvider) {
          return await this._authThenStart();
        }
        if (response.status === 405) {
          return;
        }
        throw new StreamableHTTPError(response.status, `Failed to open SSE stream: ${response.statusText}`);
      }
      this._handleSseStream(response.body, options, true);
    } catch (error48) {
      (_d2 = this.onerror) == null ? void 0 : _d2.call(this, error48);
      throw error48;
    }
  }
  /**
   * Calculates the next reconnection delay using  backoff algorithm
   *
   * @param attempt Current reconnection attempt count for the specific stream
   * @returns Time to wait in milliseconds before next reconnection attempt
   */
  _getNextReconnectionDelay(attempt) {
    if (this._serverRetryMs !== void 0) {
      return this._serverRetryMs;
    }
    const initialDelay = this._reconnectionOptions.initialReconnectionDelay;
    const growFactor = this._reconnectionOptions.reconnectionDelayGrowFactor;
    const maxDelay = this._reconnectionOptions.maxReconnectionDelay;
    return Math.min(initialDelay * Math.pow(growFactor, attempt), maxDelay);
  }
  /**
   * Schedule a reconnection attempt using server-provided retry interval or backoff
   *
   * @param lastEventId The ID of the last received event for resumability
   * @param attemptCount Current reconnection attempt count for this specific stream
   */
  _scheduleReconnection(options, attemptCount = 0) {
    var _a3;
    const maxRetries = this._reconnectionOptions.maxRetries;
    if (attemptCount >= maxRetries) {
      (_a3 = this.onerror) == null ? void 0 : _a3.call(this, new Error(`Maximum reconnection attempts (${maxRetries}) exceeded.`));
      return;
    }
    const delay = this._getNextReconnectionDelay(attemptCount);
    this._reconnectionTimeout = setTimeout(() => {
      this._startOrAuthSse(options).catch((error48) => {
        var _a4;
        (_a4 = this.onerror) == null ? void 0 : _a4.call(this, new Error(`Failed to reconnect SSE stream: ${error48 instanceof Error ? error48.message : String(error48)}`));
        this._scheduleReconnection(options, attemptCount + 1);
      });
    }, delay);
  }
  _handleSseStream(stream, options, isReconnectable) {
    if (!stream) {
      return;
    }
    const { onresumptiontoken, replayMessageId } = options;
    let lastEventId;
    let hasPrimingEvent = false;
    let receivedResponse = false;
    const processStream = async () => {
      var _a3, _b2, _c, _d2;
      try {
        const reader = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream({
          onRetry: (retryMs) => {
            this._serverRetryMs = retryMs;
          }
        })).getReader();
        while (true) {
          const { value: event, done } = await reader.read();
          if (done) {
            break;
          }
          if (event.id) {
            lastEventId = event.id;
            hasPrimingEvent = true;
            onresumptiontoken == null ? void 0 : onresumptiontoken(event.id);
          }
          if (!event.data) {
            continue;
          }
          if (!event.event || event.event === "message") {
            try {
              const message = JSONRPCMessageSchema.parse(JSON.parse(event.data));
              if (isJSONRPCResultResponse(message)) {
                receivedResponse = true;
                if (replayMessageId !== void 0) {
                  message.id = replayMessageId;
                }
              }
              (_a3 = this.onmessage) == null ? void 0 : _a3.call(this, message);
            } catch (error48) {
              (_b2 = this.onerror) == null ? void 0 : _b2.call(this, error48);
            }
          }
        }
        const canResume = isReconnectable || hasPrimingEvent;
        const needsReconnect = canResume && !receivedResponse;
        if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
          this._scheduleReconnection({
            resumptionToken: lastEventId,
            onresumptiontoken,
            replayMessageId
          }, 0);
        }
      } catch (error48) {
        (_c = this.onerror) == null ? void 0 : _c.call(this, new Error(`SSE stream disconnected: ${error48}`));
        const canResume = isReconnectable || hasPrimingEvent;
        const needsReconnect = canResume && !receivedResponse;
        if (needsReconnect && this._abortController && !this._abortController.signal.aborted) {
          try {
            this._scheduleReconnection({
              resumptionToken: lastEventId,
              onresumptiontoken,
              replayMessageId
            }, 0);
          } catch (error49) {
            (_d2 = this.onerror) == null ? void 0 : _d2.call(this, new Error(`Failed to reconnect: ${error49 instanceof Error ? error49.message : String(error49)}`));
          }
        }
      }
    };
    processStream();
  }
  async start() {
    if (this._abortController) {
      throw new Error("StreamableHTTPClientTransport already started! If using Client class, note that connect() calls start() automatically.");
    }
    this._abortController = new AbortController();
  }
  /**
   * Call this method after the user has finished authorizing via their user agent and is redirected back to the MCP client application. This will exchange the authorization code for an access token, enabling the next connection attempt to successfully auth.
   */
  async finishAuth(authorizationCode) {
    if (!this._authProvider) {
      throw new UnauthorizedError("No auth provider");
    }
    const result = await auth(this._authProvider, {
      serverUrl: this._url,
      authorizationCode,
      resourceMetadataUrl: this._resourceMetadataUrl,
      scope: this._scope,
      fetchFn: this._fetchWithInit
    });
    if (result !== "AUTHORIZED") {
      throw new UnauthorizedError("Failed to authorize");
    }
  }
  async close() {
    var _a3, _b2;
    if (this._reconnectionTimeout) {
      clearTimeout(this._reconnectionTimeout);
      this._reconnectionTimeout = void 0;
    }
    (_a3 = this._abortController) == null ? void 0 : _a3.abort();
    (_b2 = this.onclose) == null ? void 0 : _b2.call(this);
  }
  async send(message, options) {
    var _a3, _b2, _c, _d2, _e, _f, _g;
    try {
      const { resumptionToken, onresumptiontoken } = options || {};
      if (resumptionToken) {
        this._startOrAuthSse({ resumptionToken, replayMessageId: isJSONRPCRequest(message) ? message.id : void 0 }).catch((err) => {
          var _a4;
          return (_a4 = this.onerror) == null ? void 0 : _a4.call(this, err);
        });
        return;
      }
      const headers = await this._commonHeaders();
      headers.set("content-type", "application/json");
      headers.set("accept", "application/json, text/event-stream");
      const init = {
        ...this._requestInit,
        method: "POST",
        headers,
        body: JSON.stringify(message),
        signal: (_a3 = this._abortController) == null ? void 0 : _a3.signal
      };
      const response = await ((_b2 = this._fetch) != null ? _b2 : fetch)(this._url, init);
      const sessionId = response.headers.get("mcp-session-id");
      if (sessionId) {
        this._sessionId = sessionId;
      }
      if (!response.ok) {
        const text = await response.text().catch(() => null);
        if (response.status === 401 && this._authProvider) {
          if (this._hasCompletedAuthFlow) {
            throw new StreamableHTTPError(401, "Server returned 401 after successful authentication");
          }
          const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
          this._resourceMetadataUrl = resourceMetadataUrl;
          this._scope = scope;
          const result = await auth(this._authProvider, {
            serverUrl: this._url,
            resourceMetadataUrl: this._resourceMetadataUrl,
            scope: this._scope,
            fetchFn: this._fetchWithInit
          });
          if (result !== "AUTHORIZED") {
            throw new UnauthorizedError();
          }
          this._hasCompletedAuthFlow = true;
          return this.send(message);
        }
        if (response.status === 403 && this._authProvider) {
          const { resourceMetadataUrl, scope, error: error48 } = extractWWWAuthenticateParams(response);
          if (error48 === "insufficient_scope") {
            const wwwAuthHeader = response.headers.get("WWW-Authenticate");
            if (this._lastUpscopingHeader === wwwAuthHeader) {
              throw new StreamableHTTPError(403, "Server returned 403 after trying upscoping");
            }
            if (scope) {
              this._scope = scope;
            }
            if (resourceMetadataUrl) {
              this._resourceMetadataUrl = resourceMetadataUrl;
            }
            this._lastUpscopingHeader = wwwAuthHeader != null ? wwwAuthHeader : void 0;
            const result = await auth(this._authProvider, {
              serverUrl: this._url,
              resourceMetadataUrl: this._resourceMetadataUrl,
              scope: this._scope,
              fetchFn: this._fetch
            });
            if (result !== "AUTHORIZED") {
              throw new UnauthorizedError();
            }
            return this.send(message);
          }
        }
        throw new StreamableHTTPError(response.status, `Error POSTing to endpoint: ${text}`);
      }
      this._hasCompletedAuthFlow = false;
      this._lastUpscopingHeader = void 0;
      if (response.status === 202) {
        await ((_c = response.body) == null ? void 0 : _c.cancel());
        if (isInitializedNotification(message)) {
          this._startOrAuthSse({ resumptionToken: void 0 }).catch((err) => {
            var _a4;
            return (_a4 = this.onerror) == null ? void 0 : _a4.call(this, err);
          });
        }
        return;
      }
      const messages = Array.isArray(message) ? message : [message];
      const hasRequests = messages.filter((msg) => "method" in msg && "id" in msg && msg.id !== void 0).length > 0;
      const contentType = response.headers.get("content-type");
      if (hasRequests) {
        if (contentType == null ? void 0 : contentType.includes("text/event-stream")) {
          this._handleSseStream(response.body, { onresumptiontoken }, false);
        } else if (contentType == null ? void 0 : contentType.includes("application/json")) {
          const data = await response.json();
          const responseMessages = Array.isArray(data) ? data.map((msg) => JSONRPCMessageSchema.parse(msg)) : [JSONRPCMessageSchema.parse(data)];
          for (const msg of responseMessages) {
            (_d2 = this.onmessage) == null ? void 0 : _d2.call(this, msg);
          }
        } else {
          await ((_e = response.body) == null ? void 0 : _e.cancel());
          throw new StreamableHTTPError(-1, `Unexpected content type: ${contentType}`);
        }
      } else {
        await ((_f = response.body) == null ? void 0 : _f.cancel());
      }
    } catch (error48) {
      (_g = this.onerror) == null ? void 0 : _g.call(this, error48);
      throw error48;
    }
  }
  get sessionId() {
    return this._sessionId;
  }
  /**
   * Terminates the current session by sending a DELETE request to the server.
   *
   * Clients that no longer need a particular session
   * (e.g., because the user is leaving the client application) SHOULD send an
   * HTTP DELETE to the MCP endpoint with the Mcp-Session-Id header to explicitly
   * terminate the session.
   *
   * The server MAY respond with HTTP 405 Method Not Allowed, indicating that
   * the server does not allow clients to terminate sessions.
   */
  async terminateSession() {
    var _a3, _b2, _c, _d2;
    if (!this._sessionId) {
      return;
    }
    try {
      const headers = await this._commonHeaders();
      const init = {
        ...this._requestInit,
        method: "DELETE",
        headers,
        signal: (_a3 = this._abortController) == null ? void 0 : _a3.signal
      };
      const response = await ((_b2 = this._fetch) != null ? _b2 : fetch)(this._url, init);
      await ((_c = response.body) == null ? void 0 : _c.cancel());
      if (!response.ok && response.status !== 405) {
        throw new StreamableHTTPError(response.status, `Failed to terminate session: ${response.statusText}`);
      }
      this._sessionId = void 0;
    } catch (error48) {
      (_d2 = this.onerror) == null ? void 0 : _d2.call(this, error48);
      throw error48;
    }
  }
  setProtocolVersion(version2) {
    this._protocolVersion = version2;
  }
  get protocolVersion() {
    return this._protocolVersion;
  }
  /**
   * Resume an SSE stream from a previous event ID.
   * Opens a GET SSE connection with Last-Event-ID header to replay missed events.
   *
   * @param lastEventId The event ID to resume from
   * @param options Optional callback to receive new resumption tokens
   */
  async resumeStream(lastEventId, options) {
    await this._startOrAuthSse({
      resumptionToken: lastEventId,
      onresumptiontoken: options == null ? void 0 : options.onresumptiontoken
    });
  }
};

// src/core/mcp/McpTester.ts
var http = __toESM(require("http"));
var https = __toESM(require("https"));
init_env();
function createNodeFetch() {
  return async (input, init) => {
    var _a3, _b2, _c;
    const requestUrl = getRequestUrl(input);
    const method = (_a3 = init == null ? void 0 : init.method) != null ? _a3 : input instanceof Request ? input.method : "GET";
    const headers = mergeHeaders(input, init);
    const signal = (_b2 = init == null ? void 0 : init.signal) != null ? _b2 : input instanceof Request ? input.signal : void 0;
    const body = await getRequestBody((_c = init == null ? void 0 : init.body) != null ? _c : input instanceof Request ? input.body : void 0);
    const transport = requestUrl.protocol === "https:" ? https : http;
    return new Promise((resolve8, reject) => {
      let settled = false;
      const fail = (error48) => {
        if (settled) return;
        settled = true;
        signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
        reject(error48 instanceof Error ? error48 : new Error(String(error48)));
      };
      const onAbort = () => {
        var _a4;
        req.destroy(new Error("Request aborted"));
        fail((_a4 = signal == null ? void 0 : signal.reason) != null ? _a4 : new Error("Request aborted"));
      };
      const requestHeaders = Object.fromEntries(headers.entries());
      if (body) {
        requestHeaders["content-length"] = String(body.byteLength);
      }
      const req = transport.request(
        requestUrl,
        {
          method,
          headers: requestHeaders
        },
        (res) => {
          if (settled) return;
          settled = true;
          signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
          resolve8(createFetchResponse(res));
        }
      );
      req.on("error", (error48) => fail(error48));
      if (signal) {
        if (signal.aborted) {
          onAbort();
          return;
        }
        signal.addEventListener("abort", onAbort, { once: true });
      }
      if (body) {
        req.end(body);
      } else {
        req.end();
      }
    });
  };
}
function createFetchResponse(res) {
  var _a3, _b2, _c, _d2;
  const responseHeaders = new Headers();
  for (const [key, value] of Object.entries(res.headers)) {
    if (value === void 0) continue;
    if (Array.isArray(value)) {
      for (const headerValue of value) {
        responseHeaders.append(key, headerValue);
      }
    } else {
      responseHeaders.append(key, value);
    }
  }
  const body = new ReadableStream({
    start(controller) {
      res.on("data", (chunk) => {
        const buffer = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
        controller.enqueue(new Uint8Array(buffer));
      });
      res.on("end", () => controller.close());
      res.on("error", (error48) => controller.error(error48));
    },
    cancel(reason) {
      res.destroy(reason instanceof Error ? reason : new Error("Response body cancelled"));
    }
  });
  let bodyUsed = false;
  const readAsText = async () => {
    if (bodyUsed) {
      throw new TypeError("Body has already been consumed");
    }
    bodyUsed = true;
    const reader = body.getReader();
    const chunks = [];
    let total = 0;
    let done = false;
    try {
      while (!done) {
        const { value, done: streamDone } = await reader.read();
        done = streamDone;
        if (done) break;
        if (value) {
          chunks.push(value);
          total += value.byteLength;
        }
      }
    } finally {
      reader.releaseLock();
    }
    const merged = new Uint8Array(total);
    let offset = 0;
    for (const chunk of chunks) {
      merged.set(chunk, offset);
      offset += chunk.byteLength;
    }
    return new TextDecoder().decode(merged);
  };
  return {
    ok: ((_a3 = res.statusCode) != null ? _a3 : 500) >= 200 && ((_b2 = res.statusCode) != null ? _b2 : 500) < 300,
    status: (_c = res.statusCode) != null ? _c : 500,
    statusText: (_d2 = res.statusMessage) != null ? _d2 : "",
    headers: responseHeaders,
    body,
    text: readAsText,
    json: async () => JSON.parse(await readAsText())
  };
}
function getRequestUrl(input) {
  if (input instanceof URL) {
    return input;
  }
  if (typeof input === "string") {
    return new URL(input);
  }
  return new URL(input.url);
}
function mergeHeaders(input, init) {
  const headers = new Headers(input instanceof Request ? input.headers : void 0);
  if (init == null ? void 0 : init.headers) {
    const initHeaders = new Headers(init.headers);
    for (const [key, value] of initHeaders.entries()) {
      headers.set(key, value);
    }
  }
  return headers;
}
async function getRequestBody(body) {
  if (body === void 0 || body === null) {
    return void 0;
  }
  const serialized = await new Response(body).arrayBuffer();
  return Buffer.from(serialized);
}
var nodeFetch = createNodeFetch();
async function testMcpServer(server) {
  var _a3;
  const type = getMcpServerType(server.config);
  let transport;
  try {
    if (type === "stdio") {
      const config2 = server.config;
      const { cmd, args } = parseCommand(config2.command, config2.args);
      if (!cmd) {
        return { success: false, tools: [], error: "Missing command" };
      }
      transport = new StdioClientTransport({
        command: cmd,
        args,
        env: { ...process.env, ...config2.env, PATH: getEnhancedPath((_a3 = config2.env) == null ? void 0 : _a3.PATH) },
        stderr: "ignore"
      });
    } else {
      const config2 = server.config;
      const url2 = new URL(config2.url);
      const options = {
        fetch: nodeFetch,
        requestInit: config2.headers ? { headers: config2.headers } : void 0
      };
      transport = type === "sse" ? new SSEClientTransport(url2, options) : new StreamableHTTPClientTransport(url2, options);
    }
  } catch (error48) {
    return {
      success: false,
      tools: [],
      error: error48 instanceof Error ? error48.message : "Invalid server configuration"
    };
  }
  const client = new Client({ name: "claudian-tester", version: "1.0.0" });
  const controller = new AbortController();
  const timeout = setTimeout(() => controller.abort(), 1e4);
  try {
    await client.connect(transport, { signal: controller.signal });
    const serverVersion = client.getServerVersion();
    let tools = [];
    try {
      const result = await client.listTools(void 0, { signal: controller.signal });
      tools = result.tools.map((t2) => ({
        name: t2.name,
        description: t2.description,
        inputSchema: t2.inputSchema
      }));
    } catch (e2) {
    }
    return {
      success: true,
      serverName: serverVersion == null ? void 0 : serverVersion.name,
      serverVersion: serverVersion == null ? void 0 : serverVersion.version,
      tools
    };
  } catch (error48) {
    if (controller.signal.aborted) {
      return { success: false, tools: [], error: "Connection timeout (10s)" };
    }
    return {
      success: false,
      tools: [],
      error: error48 instanceof Error ? error48.message : "Unknown error"
    };
  } finally {
    clearTimeout(timeout);
    try {
      await client.close();
    } catch (e2) {
    }
  }
}

// src/features/settings/ui/McpServerModal.ts
var import_obsidian6 = require("obsidian");
var McpServerModal = class extends import_obsidian6.Modal {
  constructor(app, existingServer, onSave, initialType, prefillConfig) {
    super(app);
    this.serverName = "";
    this.serverType = "stdio";
    this.enabled = DEFAULT_MCP_SERVER.enabled;
    this.contextSaving = DEFAULT_MCP_SERVER.contextSaving;
    this.command = "";
    this.env = "";
    this.url = "";
    this.headers = "";
    this.typeFieldsEl = null;
    this.nameInputEl = null;
    this.existingServer = existingServer;
    this.onSave = onSave;
    if (existingServer) {
      this.serverName = existingServer.name;
      this.serverType = getMcpServerType(existingServer.config);
      this.enabled = existingServer.enabled;
      this.contextSaving = existingServer.contextSaving;
      this.initFromConfig(existingServer.config);
    } else if (prefillConfig) {
      this.serverName = prefillConfig.name;
      this.serverType = getMcpServerType(prefillConfig.config);
      this.initFromConfig(prefillConfig.config);
    } else if (initialType) {
      this.serverType = initialType;
    }
  }
  initFromConfig(config2) {
    const type = getMcpServerType(config2);
    if (type === "stdio") {
      const stdioConfig = config2;
      if (stdioConfig.args && stdioConfig.args.length > 0) {
        this.command = stdioConfig.command + " " + stdioConfig.args.join(" ");
      } else {
        this.command = stdioConfig.command;
      }
      this.env = this.envRecordToString(stdioConfig.env);
    } else {
      const urlConfig = config2;
      this.url = urlConfig.url;
      this.headers = this.envRecordToString(urlConfig.headers);
    }
  }
  onOpen() {
    this.setTitle(this.existingServer ? "Edit MCP Server" : "Add MCP Server");
    this.modalEl.addClass("claudian-mcp-modal");
    const { contentEl } = this;
    new import_obsidian6.Setting(contentEl).setName("Server name").setDesc("Unique identifier for this server").addText((text) => {
      this.nameInputEl = text.inputEl;
      text.setValue(this.serverName);
      text.setPlaceholder("my-mcp-server");
      text.onChange((value) => {
        this.serverName = value;
      });
      text.inputEl.addEventListener("keydown", (e2) => this.handleKeyDown(e2));
    });
    new import_obsidian6.Setting(contentEl).setName("Type").setDesc("Server connection type").addDropdown((dropdown) => {
      dropdown.addOption("stdio", "stdio (local command)");
      dropdown.addOption("sse", "sse (Server-Sent Events)");
      dropdown.addOption("http", "http (HTTP endpoint)");
      dropdown.setValue(this.serverType);
      dropdown.onChange((value) => {
        this.serverType = value;
        this.renderTypeFields();
      });
    });
    this.typeFieldsEl = contentEl.createDiv({ cls: "claudian-mcp-type-fields" });
    this.renderTypeFields();
    new import_obsidian6.Setting(contentEl).setName("Enabled").setDesc("Whether this server is active").addToggle((toggle) => {
      toggle.setValue(this.enabled);
      toggle.onChange((value) => {
        this.enabled = value;
      });
    });
    new import_obsidian6.Setting(contentEl).setName("Context-saving mode").setDesc("Hide tools from agent unless @-mentioned (saves context window)").addToggle((toggle) => {
      toggle.setValue(this.contextSaving);
      toggle.onChange((value) => {
        this.contextSaving = value;
      });
    });
    const buttonContainer = contentEl.createDiv({ cls: "claudian-mcp-buttons" });
    const cancelBtn = buttonContainer.createEl("button", {
      text: "Cancel",
      cls: "claudian-cancel-btn"
    });
    cancelBtn.addEventListener("click", () => this.close());
    const saveBtn = buttonContainer.createEl("button", {
      text: this.existingServer ? "Update" : "Add",
      cls: "claudian-save-btn mod-cta"
    });
    saveBtn.addEventListener("click", () => this.save());
  }
  renderTypeFields() {
    if (!this.typeFieldsEl) return;
    this.typeFieldsEl.empty();
    if (this.serverType === "stdio") {
      this.renderStdioFields();
    } else {
      this.renderUrlFields();
    }
  }
  renderStdioFields() {
    if (!this.typeFieldsEl) return;
    const cmdSetting = new import_obsidian6.Setting(this.typeFieldsEl).setName("Command").setDesc("Full command with arguments");
    cmdSetting.settingEl.addClass("claudian-mcp-cmd-setting");
    const cmdTextarea = cmdSetting.controlEl.createEl("textarea", {
      cls: "claudian-mcp-cmd-textarea"
    });
    cmdTextarea.value = this.command;
    cmdTextarea.placeholder = "docker exec -i mcp-server python -m src.server";
    cmdTextarea.rows = 2;
    cmdTextarea.addEventListener("input", () => {
      this.command = cmdTextarea.value;
    });
    const envSetting = new import_obsidian6.Setting(this.typeFieldsEl).setName("Environment variables").setDesc("KEY=VALUE per line (optional)");
    envSetting.settingEl.addClass("claudian-mcp-env-setting");
    const envTextarea = envSetting.controlEl.createEl("textarea", {
      cls: "claudian-mcp-env-textarea"
    });
    envTextarea.value = this.env;
    envTextarea.placeholder = "API_KEY=your-key";
    envTextarea.rows = 2;
    envTextarea.addEventListener("input", () => {
      this.env = envTextarea.value;
    });
  }
  renderUrlFields() {
    if (!this.typeFieldsEl) return;
    new import_obsidian6.Setting(this.typeFieldsEl).setName("URL").setDesc(this.serverType === "sse" ? "SSE endpoint URL" : "HTTP endpoint URL").addText((text) => {
      text.setValue(this.url);
      text.setPlaceholder("http://localhost:3000/sse");
      text.onChange((value) => {
        this.url = value;
      });
      text.inputEl.addEventListener("keydown", (e2) => this.handleKeyDown(e2));
    });
    const headersSetting = new import_obsidian6.Setting(this.typeFieldsEl).setName("Headers").setDesc("HTTP headers (KEY=VALUE per line)");
    headersSetting.settingEl.addClass("claudian-mcp-env-setting");
    const headersTextarea = headersSetting.controlEl.createEl("textarea", {
      cls: "claudian-mcp-env-textarea"
    });
    headersTextarea.value = this.headers;
    headersTextarea.placeholder = "Authorization=Bearer token\nContent-Type=application/json";
    headersTextarea.rows = 3;
    headersTextarea.addEventListener("input", () => {
      this.headers = headersTextarea.value;
    });
  }
  handleKeyDown(e2) {
    if (e2.key === "Enter" && !e2.shiftKey && !e2.isComposing) {
      e2.preventDefault();
      this.save();
    } else if (e2.key === "Escape" && !e2.isComposing) {
      e2.preventDefault();
      this.close();
    }
  }
  save() {
    var _a3, _b2, _c;
    const name = this.serverName.trim();
    if (!name) {
      new import_obsidian6.Notice("Please enter a server name");
      (_a3 = this.nameInputEl) == null ? void 0 : _a3.focus();
      return;
    }
    if (!/^[a-zA-Z0-9._-]+$/.test(name)) {
      new import_obsidian6.Notice("Server name can only contain letters, numbers, dots, hyphens, and underscores");
      (_b2 = this.nameInputEl) == null ? void 0 : _b2.focus();
      return;
    }
    let config2;
    if (this.serverType === "stdio") {
      const fullCommand = this.command.trim();
      if (!fullCommand) {
        new import_obsidian6.Notice("Please enter a command");
        return;
      }
      const { cmd, args } = parseCommand(fullCommand);
      const stdioConfig = { command: cmd };
      if (args.length > 0) {
        stdioConfig.args = args;
      }
      const env = this.parseEnvString(this.env);
      if (Object.keys(env).length > 0) {
        stdioConfig.env = env;
      }
      config2 = stdioConfig;
    } else {
      const url2 = this.url.trim();
      if (!url2) {
        new import_obsidian6.Notice("Please enter a URL");
        return;
      }
      if (this.serverType === "sse") {
        const sseConfig = { type: "sse", url: url2 };
        const headers = this.parseEnvString(this.headers);
        if (Object.keys(headers).length > 0) {
          sseConfig.headers = headers;
        }
        config2 = sseConfig;
      } else {
        const httpConfig = { type: "http", url: url2 };
        const headers = this.parseEnvString(this.headers);
        if (Object.keys(headers).length > 0) {
          httpConfig.headers = headers;
        }
        config2 = httpConfig;
      }
    }
    const server = {
      name,
      config: config2,
      enabled: this.enabled,
      contextSaving: this.contextSaving,
      disabledTools: (_c = this.existingServer) == null ? void 0 : _c.disabledTools
    };
    this.onSave(server);
    this.close();
  }
  parseEnvString(envStr) {
    const result = {};
    if (!envStr.trim()) return result;
    for (const line of envStr.split("\n")) {
      const trimmed = line.trim();
      if (!trimmed || trimmed.startsWith("#")) continue;
      const eqIndex = trimmed.indexOf("=");
      if (eqIndex === -1) continue;
      const key = trimmed.substring(0, eqIndex).trim();
      const value = trimmed.substring(eqIndex + 1).trim();
      if (key) {
        result[key] = value;
      }
    }
    return result;
  }
  envRecordToString(env) {
    if (!env) return "";
    return Object.entries(env).map(([key, value]) => `${key}=${value}`).join("\n");
  }
  onClose() {
    this.contentEl.empty();
  }
};

// src/features/settings/ui/McpTestModal.ts
var import_obsidian7 = require("obsidian");
function formatToggleError(error48) {
  if (!(error48 instanceof Error)) return "Failed to update tool setting";
  const msg = error48.message.toLowerCase();
  if (msg.includes("permission") || msg.includes("eacces")) {
    return "Permission denied. Check .claude/ folder permissions.";
  }
  if (msg.includes("enospc") || msg.includes("disk full") || msg.includes("no space")) {
    return "Disk full. Free up space and try again.";
  }
  if (msg.includes("json") || msg.includes("syntax")) {
    return "Config file corrupted. Check .claude/mcp.json";
  }
  return error48.message || "Failed to update tool setting";
}
var McpTestModal = class extends import_obsidian7.Modal {
  constructor(app, serverName, initialDisabledTools, onToolToggle, onBulkToggle) {
    super(app);
    this.result = null;
    this.loading = true;
    this.contentEl_ = null;
    this.toolToggles = /* @__PURE__ */ new Map();
    this.toolElements = /* @__PURE__ */ new Map();
    this.toggleAllBtn = null;
    this.pendingToggle = false;
    this.serverName = serverName;
    this.disabledTools = new Set(
      (initialDisabledTools != null ? initialDisabledTools : []).map((tool) => tool.trim()).filter((tool) => tool.length > 0)
    );
    this.onToolToggle = onToolToggle;
    this.onBulkToggle = onBulkToggle;
  }
  onOpen() {
    this.setTitle(`Verify: ${this.serverName}`);
    this.modalEl.addClass("claudian-mcp-test-modal");
    this.contentEl_ = this.contentEl;
    this.renderLoading();
  }
  setResult(result) {
    this.result = result;
    this.loading = false;
    this.render();
  }
  setError(error48) {
    this.result = { success: false, tools: [], error: error48 };
    this.loading = false;
    this.render();
  }
  renderLoading() {
    if (!this.contentEl_) return;
    this.contentEl_.empty();
    const loadingEl = this.contentEl_.createDiv({ cls: "claudian-mcp-test-loading" });
    const spinnerEl = loadingEl.createDiv({ cls: "claudian-mcp-test-spinner" });
    spinnerEl.innerHTML = `<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
      <path d="M12 2v4M12 18v4M4.93 4.93l2.83 2.83M16.24 16.24l2.83 2.83M2 12h4M18 12h4M4.93 19.07l2.83-2.83M16.24 7.76l2.83-2.83"/>
    </svg>`;
    loadingEl.createSpan({ text: "Connecting to MCP server..." });
  }
  render() {
    if (!this.contentEl_) return;
    this.contentEl_.empty();
    if (!this.result) {
      this.renderLoading();
      return;
    }
    const statusEl = this.contentEl_.createDiv({ cls: "claudian-mcp-test-status" });
    const iconEl = statusEl.createSpan({ cls: "claudian-mcp-test-icon" });
    if (this.result.success) {
      (0, import_obsidian7.setIcon)(iconEl, "check-circle");
      iconEl.addClass("success");
    } else {
      (0, import_obsidian7.setIcon)(iconEl, "x-circle");
      iconEl.addClass("error");
    }
    const textEl = statusEl.createSpan({ cls: "claudian-mcp-test-text" });
    if (this.result.success) {
      let statusText = "Connected successfully";
      if (this.result.serverName) {
        statusText += ` to ${this.result.serverName}`;
        if (this.result.serverVersion) {
          statusText += ` v${this.result.serverVersion}`;
        }
      }
      textEl.setText(statusText);
    } else {
      textEl.setText("Connection failed");
    }
    if (this.result.error) {
      const errorEl = this.contentEl_.createDiv({ cls: "claudian-mcp-test-error" });
      errorEl.setText(this.result.error);
    }
    this.toolToggles.clear();
    this.toolElements.clear();
    if (this.result.tools.length > 0) {
      const toolsSection = this.contentEl_.createDiv({ cls: "claudian-mcp-test-tools" });
      const toolsHeader = toolsSection.createDiv({ cls: "claudian-mcp-test-tools-header" });
      toolsHeader.setText(`Available Tools (${this.result.tools.length})`);
      const toolsList = toolsSection.createDiv({ cls: "claudian-mcp-test-tools-list" });
      for (const tool of this.result.tools) {
        this.renderTool(toolsList, tool);
      }
    } else if (this.result.success) {
      const noToolsEl = this.contentEl_.createDiv({ cls: "claudian-mcp-test-no-tools" });
      noToolsEl.setText("No tools information available. Tools will be loaded when used in chat.");
    }
    const buttonContainer = this.contentEl_.createDiv({ cls: "claudian-mcp-test-buttons" });
    if (this.result.tools.length > 0 && this.onToolToggle) {
      this.toggleAllBtn = buttonContainer.createEl("button", {
        cls: "claudian-mcp-toggle-all-btn"
      });
      this.updateToggleAllButton();
      this.toggleAllBtn.addEventListener("click", () => this.handleToggleAll());
    }
    const closeBtn = buttonContainer.createEl("button", {
      text: "Close",
      cls: "mod-cta"
    });
    closeBtn.addEventListener("click", () => this.close());
  }
  renderTool(container, tool) {
    const toolEl = container.createDiv({ cls: "claudian-mcp-test-tool" });
    const headerEl = toolEl.createDiv({ cls: "claudian-mcp-test-tool-header" });
    const iconEl = headerEl.createSpan({ cls: "claudian-mcp-test-tool-icon" });
    (0, import_obsidian7.setIcon)(iconEl, "wrench");
    const nameEl = headerEl.createSpan({ cls: "claudian-mcp-test-tool-name" });
    nameEl.setText(tool.name);
    const toggleEl = headerEl.createDiv({ cls: "claudian-mcp-test-tool-toggle" });
    const toggleContainer = toggleEl.createDiv({ cls: "checkbox-container" });
    const checkbox = toggleContainer.createEl("input", {
      type: "checkbox",
      attr: { tabindex: "0" }
    });
    const isEnabled = !this.disabledTools.has(tool.name);
    checkbox.checked = isEnabled;
    toggleContainer.toggleClass("is-enabled", isEnabled);
    this.updateToolState(toolEl, isEnabled);
    this.toolToggles.set(tool.name, { checkbox, container: toggleContainer });
    this.toolElements.set(tool.name, toolEl);
    if (!this.onToolToggle) {
      checkbox.disabled = true;
    } else {
      toggleContainer.addEventListener("click", (e2) => {
        e2.preventDefault();
        e2.stopPropagation();
        if (checkbox.disabled) return;
        checkbox.checked = !checkbox.checked;
        this.handleToolToggle(tool.name, checkbox, toggleContainer);
      });
    }
    if (tool.description) {
      const descEl = toolEl.createDiv({ cls: "claudian-mcp-test-tool-desc" });
      descEl.setText(tool.description);
    }
  }
  async handleToolToggle(toolName, checkbox, container) {
    var _a3;
    const toolEl = this.toolElements.get(toolName);
    if (!toolEl) return;
    const wasDisabled = this.disabledTools.has(toolName);
    const nextDisabled = !checkbox.checked;
    if (nextDisabled) {
      this.disabledTools.add(toolName);
    } else {
      this.disabledTools.delete(toolName);
    }
    container.toggleClass("is-enabled", !nextDisabled);
    this.updateToolState(toolEl, !nextDisabled);
    this.updateToggleAllButton();
    checkbox.disabled = true;
    try {
      await ((_a3 = this.onToolToggle) == null ? void 0 : _a3.call(this, toolName, !nextDisabled));
    } catch (error48) {
      if (nextDisabled) {
        this.disabledTools.delete(toolName);
      } else {
        this.disabledTools.add(toolName);
      }
      checkbox.checked = !wasDisabled;
      container.toggleClass("is-enabled", !wasDisabled);
      this.updateToolState(toolEl, !wasDisabled);
      this.updateToggleAllButton();
      new import_obsidian7.Notice(formatToggleError(error48));
    } finally {
      checkbox.disabled = false;
    }
  }
  updateToolState(toolEl, enabled) {
    toolEl.toggleClass("claudian-mcp-test-tool-disabled", !enabled);
  }
  updateToggleAllButton() {
    if (!this.toggleAllBtn || !this.result) return;
    const allEnabled = this.disabledTools.size === 0;
    const allDisabled = this.disabledTools.size === this.result.tools.length;
    if (allEnabled) {
      this.toggleAllBtn.setText("Disable All");
      this.toggleAllBtn.toggleClass("is-destructive", true);
    } else {
      this.toggleAllBtn.setText(allDisabled ? "Enable All" : "Enable All");
      this.toggleAllBtn.toggleClass("is-destructive", false);
    }
  }
  async handleToggleAll() {
    if (!this.result || this.pendingToggle || !this.onBulkToggle) return;
    const allEnabled = this.disabledTools.size === 0;
    const previousDisabled = new Set(this.disabledTools);
    const newDisabledTools = allEnabled ? this.result.tools.map((t2) => t2.name) : [];
    this.pendingToggle = true;
    if (this.toggleAllBtn) this.toggleAllBtn.disabled = true;
    for (const { checkbox } of this.toolToggles.values()) {
      checkbox.disabled = true;
    }
    this.disabledTools = new Set(newDisabledTools);
    for (const tool of this.result.tools) {
      const toggle = this.toolToggles.get(tool.name);
      const toolEl = this.toolElements.get(tool.name);
      if (!toggle || !toolEl) continue;
      const isEnabled = !this.disabledTools.has(tool.name);
      toggle.checkbox.checked = isEnabled;
      toggle.container.toggleClass("is-enabled", isEnabled);
      this.updateToolState(toolEl, isEnabled);
    }
    this.updateToggleAllButton();
    try {
      await this.onBulkToggle(newDisabledTools);
    } catch (error48) {
      this.disabledTools = previousDisabled;
      for (const tool of this.result.tools) {
        const toggle = this.toolToggles.get(tool.name);
        const toolEl = this.toolElements.get(tool.name);
        if (!toggle || !toolEl) continue;
        const isEnabled = !this.disabledTools.has(tool.name);
        toggle.checkbox.checked = isEnabled;
        toggle.container.toggleClass("is-enabled", isEnabled);
        this.updateToolState(toolEl, isEnabled);
      }
      this.updateToggleAllButton();
      new import_obsidian7.Notice(formatToggleError(error48));
    }
    for (const { checkbox } of this.toolToggles.values()) {
      checkbox.disabled = false;
    }
    this.pendingToggle = false;
    if (this.toggleAllBtn) this.toggleAllBtn.disabled = false;
  }
  onClose() {
    this.contentEl.empty();
  }
};

// src/features/settings/ui/McpSettingsManager.ts
var McpSettingsManager = class {
  constructor(containerEl, deps) {
    this.servers = [];
    this.app = deps.app;
    this.containerEl = containerEl;
    this.mcpStorage = deps.mcpStorage;
    this.broadcastMcpReload = deps.broadcastMcpReload;
    this.loadAndRender();
  }
  async loadAndRender() {
    this.servers = await this.mcpStorage.load();
    this.render();
  }
  render() {
    this.containerEl.empty();
    const headerEl = this.containerEl.createDiv({ cls: "claudian-mcp-header" });
    headerEl.createSpan({ text: "MCP Servers", cls: "claudian-mcp-label" });
    const addContainer = headerEl.createDiv({ cls: "claudian-mcp-add-container" });
    const addBtn = addContainer.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Add" }
    });
    (0, import_obsidian8.setIcon)(addBtn, "plus");
    const dropdown = addContainer.createDiv({ cls: "claudian-mcp-add-dropdown" });
    const stdioOption = dropdown.createDiv({ cls: "claudian-mcp-add-option" });
    (0, import_obsidian8.setIcon)(stdioOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "terminal");
    stdioOption.createSpan({ text: "stdio (local command)" });
    stdioOption.addEventListener("click", () => {
      dropdown.removeClass("is-visible");
      this.openModal(null, "stdio");
    });
    const httpOption = dropdown.createDiv({ cls: "claudian-mcp-add-option" });
    (0, import_obsidian8.setIcon)(httpOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "globe");
    httpOption.createSpan({ text: "http / sse (remote)" });
    httpOption.addEventListener("click", () => {
      dropdown.removeClass("is-visible");
      this.openModal(null, "http");
    });
    const importOption = dropdown.createDiv({ cls: "claudian-mcp-add-option" });
    (0, import_obsidian8.setIcon)(importOption.createSpan({ cls: "claudian-mcp-add-option-icon" }), "clipboard-paste");
    importOption.createSpan({ text: "Import from clipboard" });
    importOption.addEventListener("click", () => {
      dropdown.removeClass("is-visible");
      this.importFromClipboard();
    });
    addBtn.addEventListener("click", (e2) => {
      e2.stopPropagation();
      dropdown.toggleClass("is-visible", !dropdown.hasClass("is-visible"));
    });
    document.addEventListener("click", () => {
      dropdown.removeClass("is-visible");
    });
    if (this.servers.length === 0) {
      const emptyEl = this.containerEl.createDiv({ cls: "claudian-mcp-empty" });
      emptyEl.setText('No MCP servers configured. Click "Add" to add one.');
      return;
    }
    const listEl = this.containerEl.createDiv({ cls: "claudian-mcp-list" });
    for (const server of this.servers) {
      this.renderServerItem(listEl, server);
    }
  }
  renderServerItem(listEl, server) {
    const itemEl = listEl.createDiv({ cls: "claudian-mcp-item" });
    if (!server.enabled) {
      itemEl.addClass("claudian-mcp-item-disabled");
    }
    const statusEl = itemEl.createDiv({ cls: "claudian-mcp-status" });
    statusEl.addClass(
      server.enabled ? "claudian-mcp-status-enabled" : "claudian-mcp-status-disabled"
    );
    const infoEl = itemEl.createDiv({ cls: "claudian-mcp-info" });
    const nameRow = infoEl.createDiv({ cls: "claudian-mcp-name-row" });
    const nameEl = nameRow.createSpan({ cls: "claudian-mcp-name" });
    nameEl.setText(server.name);
    const serverType = getMcpServerType(server.config);
    const typeEl = nameRow.createSpan({ cls: "claudian-mcp-type-badge" });
    typeEl.setText(serverType);
    if (server.contextSaving) {
      const csEl = nameRow.createSpan({ cls: "claudian-mcp-context-saving-badge" });
      csEl.setText("@");
      csEl.setAttribute("title", "Context-saving: mention with @" + server.name + " to enable");
    }
    const previewEl = infoEl.createDiv({ cls: "claudian-mcp-preview" });
    if (server.description) {
      previewEl.setText(server.description);
    } else {
      previewEl.setText(this.getServerPreview(server, serverType));
    }
    const actionsEl = itemEl.createDiv({ cls: "claudian-mcp-actions" });
    const testBtn = actionsEl.createEl("button", {
      cls: "claudian-mcp-action-btn",
      attr: { "aria-label": "Verify (show tools)" }
    });
    (0, import_obsidian8.setIcon)(testBtn, "zap");
    testBtn.addEventListener("click", () => this.testServer(server));
    const toggleBtn = actionsEl.createEl("button", {
      cls: "claudian-mcp-action-btn",
      attr: { "aria-label": server.enabled ? "Disable" : "Enable" }
    });
    (0, import_obsidian8.setIcon)(toggleBtn, server.enabled ? "toggle-right" : "toggle-left");
    toggleBtn.addEventListener("click", () => this.toggleServer(server));
    const editBtn = actionsEl.createEl("button", {
      cls: "claudian-mcp-action-btn",
      attr: { "aria-label": "Edit" }
    });
    (0, import_obsidian8.setIcon)(editBtn, "pencil");
    editBtn.addEventListener("click", () => this.openModal(server));
    const deleteBtn = actionsEl.createEl("button", {
      cls: "claudian-mcp-action-btn claudian-mcp-delete-btn",
      attr: { "aria-label": "Delete" }
    });
    (0, import_obsidian8.setIcon)(deleteBtn, "trash-2");
    deleteBtn.addEventListener("click", () => this.deleteServer(server));
  }
  async testServer(server) {
    const modal = new McpTestModal(
      this.app,
      server.name,
      server.disabledTools,
      async (toolName, enabled) => {
        await this.updateDisabledTool(server, toolName, enabled);
      },
      async (disabledTools) => {
        await this.updateAllDisabledTools(server, disabledTools);
      }
    );
    modal.open();
    try {
      const result = await testMcpServer(server);
      modal.setResult(result);
    } catch (error48) {
      modal.setError(error48 instanceof Error ? error48.message : "Verification failed");
    }
  }
  /** Rolls back on save failure; warns on reload failure (since save succeeded). */
  async updateServerDisabledTools(server, newDisabledTools) {
    const previous = server.disabledTools ? [...server.disabledTools] : void 0;
    server.disabledTools = newDisabledTools;
    try {
      await this.mcpStorage.save(this.servers);
    } catch (error48) {
      server.disabledTools = previous;
      throw error48;
    }
    try {
      await this.broadcastMcpReload();
    } catch (e2) {
      new import_obsidian8.Notice("Setting saved but reload failed. Changes will apply on next session.");
    }
  }
  async updateDisabledTool(server, toolName, enabled) {
    var _a3;
    const disabledTools = new Set((_a3 = server.disabledTools) != null ? _a3 : []);
    if (enabled) {
      disabledTools.delete(toolName);
    } else {
      disabledTools.add(toolName);
    }
    await this.updateServerDisabledTools(
      server,
      disabledTools.size > 0 ? Array.from(disabledTools) : void 0
    );
  }
  async updateAllDisabledTools(server, disabledTools) {
    await this.updateServerDisabledTools(
      server,
      disabledTools.length > 0 ? disabledTools : void 0
    );
  }
  getServerPreview(server, type) {
    var _a3;
    if (type === "stdio") {
      const config2 = server.config;
      const args = ((_a3 = config2.args) == null ? void 0 : _a3.join(" ")) || "";
      return args ? `${config2.command} ${args}` : config2.command;
    } else {
      const config2 = server.config;
      return config2.url;
    }
  }
  openModal(existing, initialType) {
    const modal = new McpServerModal(
      this.app,
      existing,
      async (server) => {
        await this.saveServer(server, existing);
      },
      initialType
    );
    modal.open();
  }
  async importFromClipboard() {
    try {
      const text = await navigator.clipboard.readText();
      if (!text.trim()) {
        new import_obsidian8.Notice("Clipboard is empty");
        return;
      }
      const parsed = tryParseClipboardConfig(text);
      if (!parsed || parsed.servers.length === 0) {
        new import_obsidian8.Notice("No valid MCP configuration found in clipboard");
        return;
      }
      if (parsed.needsName || parsed.servers.length === 1) {
        const server = parsed.servers[0];
        const type = getMcpServerType(server.config);
        const modal = new McpServerModal(
          this.app,
          null,
          async (savedServer) => {
            await this.saveServer(savedServer, null);
          },
          type,
          server
          // Pre-fill with parsed config
        );
        modal.open();
        if (parsed.needsName) {
          new import_obsidian8.Notice("Enter a name for the server");
        }
        return;
      }
      await this.importServers(parsed.servers);
    } catch (e2) {
      new import_obsidian8.Notice("Failed to read clipboard");
    }
  }
  async saveServer(server, existing) {
    if (existing) {
      const index = this.servers.findIndex((s4) => s4.name === existing.name);
      if (index !== -1) {
        if (server.name !== existing.name) {
          const conflict = this.servers.find((s4) => s4.name === server.name);
          if (conflict) {
            new import_obsidian8.Notice(`Server "${server.name}" already exists`);
            return;
          }
        }
        this.servers[index] = server;
      }
    } else {
      const conflict = this.servers.find((s4) => s4.name === server.name);
      if (conflict) {
        new import_obsidian8.Notice(`Server "${server.name}" already exists`);
        return;
      }
      this.servers.push(server);
    }
    await this.mcpStorage.save(this.servers);
    await this.broadcastMcpReload();
    this.render();
    new import_obsidian8.Notice(existing ? `MCP server "${server.name}" updated` : `MCP server "${server.name}" added`);
  }
  async importServers(servers) {
    const added = [];
    const skipped = [];
    for (const server of servers) {
      const name = server.name.trim();
      if (!name || !/^[a-zA-Z0-9._-]+$/.test(name)) {
        skipped.push(server.name || "<unnamed>");
        continue;
      }
      const conflict = this.servers.find((s4) => s4.name === name);
      if (conflict) {
        skipped.push(name);
        continue;
      }
      this.servers.push({
        name,
        config: server.config,
        enabled: DEFAULT_MCP_SERVER.enabled,
        contextSaving: DEFAULT_MCP_SERVER.contextSaving
      });
      added.push(name);
    }
    if (added.length === 0) {
      new import_obsidian8.Notice("No new MCP servers imported");
      return;
    }
    await this.mcpStorage.save(this.servers);
    await this.broadcastMcpReload();
    this.render();
    let message = `Imported ${added.length} MCP server${added.length > 1 ? "s" : ""}`;
    if (skipped.length > 0) {
      message += ` (${skipped.length} skipped)`;
    }
    new import_obsidian8.Notice(message);
  }
  async toggleServer(server) {
    server.enabled = !server.enabled;
    await this.mcpStorage.save(this.servers);
    await this.broadcastMcpReload();
    this.render();
    new import_obsidian8.Notice(`MCP server "${server.name}" ${server.enabled ? "enabled" : "disabled"}`);
  }
  async deleteServer(server) {
    if (!confirm(`Delete MCP server "${server.name}"?`)) {
      return;
    }
    this.servers = this.servers.filter((s4) => s4.name !== server.name);
    await this.mcpStorage.save(this.servers);
    await this.broadcastMcpReload();
    this.render();
    new import_obsidian8.Notice(`MCP server "${server.name}" deleted`);
  }
  /** Refresh the server list (call after external changes). */
  refresh() {
    this.loadAndRender();
  }
};

// src/providers/claude/ui/ClaudeSettingsTab.ts
init_env();
init_path();

// src/providers/claude/modelLabels.ts
function getFamilyDisplayName(family) {
  return family.charAt(0).toUpperCase() + family.slice(1).toLowerCase();
}
function formatClaudeModelDateTag(date7) {
  if (!date7 || date7.length < 6) {
    return null;
  }
  return `(${date7.slice(2, 6)})`;
}
function getCustomModelLabelSource(modelId) {
  if (!modelId.includes("/")) {
    return modelId;
  }
  return modelId.split("/").pop() || modelId;
}
function formatGenericCustomModelLabel(labelSource) {
  return labelSource.replace(/-/g, " ").replace(/\b\w/g, (letter) => letter.toUpperCase());
}
function formatCustomModelLabel(modelId) {
  const labelSource = getCustomModelLabelSource(modelId);
  const claudeLabel = formatClaudeCustomModelLabel(labelSource);
  if (claudeLabel) {
    return claudeLabel;
  }
  return modelId.includes("/") ? labelSource : formatGenericCustomModelLabel(labelSource);
}
function formatClaudeCustomModelLabel(labelSource) {
  const trimmed = labelSource.trim();
  if (!trimmed) {
    return null;
  }
  const is1M = trimmed.toLowerCase().endsWith("[1m]");
  const without1M = is1M ? trimmed.slice(0, -4) : trimmed;
  const claudePrefixIndex = without1M.toLowerCase().indexOf("claude-");
  const candidate = claudePrefixIndex >= 0 ? without1M.slice(claudePrefixIndex) : without1M;
  const versionedMatch = candidate.match(
    /^claude-(haiku|sonnet|opus)-(\d+)-(\d+)(?:-(\d{8}))?(?:-v\d+:\d+)?$/i
  );
  if (versionedMatch) {
    const [, family, major, minor, date7] = versionedMatch;
    const suffixes = [
      formatClaudeModelDateTag(date7),
      is1M ? "(1M)" : null
    ].filter(Boolean).join(" ");
    return `${getFamilyDisplayName(family)} ${major}.${minor}${suffixes ? ` ${suffixes}` : ""}`;
  }
  const majorOnlyMatch = candidate.match(
    /^claude-(haiku|sonnet|opus)-(\d+)(?:-(\d{8}))?(?:-v\d+:\d+)?$/i
  );
  if (majorOnlyMatch) {
    const [, family, major, date7] = majorOnlyMatch;
    const suffixes = [
      formatClaudeModelDateTag(date7),
      is1M ? "(1M)" : null
    ].filter(Boolean).join(" ");
    return `${getFamilyDisplayName(family)} ${major}${suffixes ? ` ${suffixes}` : ""}`;
  }
  return null;
}

// src/providers/claude/env/claudeModelEnv.ts
var CUSTOM_MODEL_ENV_KEYS = [
  "ANTHROPIC_MODEL",
  "ANTHROPIC_DEFAULT_OPUS_MODEL",
  "ANTHROPIC_DEFAULT_SONNET_MODEL",
  "ANTHROPIC_DEFAULT_HAIKU_MODEL"
];
function getModelTypeFromEnvKey(envKey) {
  if (envKey === "ANTHROPIC_MODEL") return "model";
  const match = envKey.match(/ANTHROPIC_DEFAULT_(\w+)_MODEL/);
  return match ? match[1].toLowerCase() : envKey;
}
function getModelsFromEnvironment(envVars) {
  const modelMap = /* @__PURE__ */ new Map();
  for (const envKey of CUSTOM_MODEL_ENV_KEYS) {
    const type = getModelTypeFromEnvKey(envKey);
    const modelValue = envVars[envKey];
    if (modelValue) {
      const label = formatCustomModelLabel(modelValue);
      if (!modelMap.has(modelValue)) {
        modelMap.set(modelValue, { types: [type], label });
      } else {
        modelMap.get(modelValue).types.push(type);
      }
    }
  }
  const models = [];
  const typePriority = { "model": 4, "haiku": 3, "sonnet": 2, "opus": 1 };
  const sortedEntries = Array.from(modelMap.entries()).sort(([, aInfo], [, bInfo]) => {
    const aPriority = Math.max(...aInfo.types.map((t2) => typePriority[t2] || 0));
    const bPriority = Math.max(...bInfo.types.map((t2) => typePriority[t2] || 0));
    return bPriority - aPriority;
  });
  for (const [modelValue, info] of sortedEntries) {
    const sortedTypes = info.types.sort(
      (a2, b10) => (typePriority[b10] || 0) - (typePriority[a2] || 0)
    );
    models.push({
      value: modelValue,
      label: info.label,
      description: `Custom model (${sortedTypes.join(", ")})`
    });
  }
  return models;
}
function getCustomModelIds(envVars) {
  const modelIds = /* @__PURE__ */ new Set();
  for (const envKey of CUSTOM_MODEL_ENV_KEYS) {
    const modelId = envVars[envKey];
    if (modelId) {
      modelIds.add(modelId);
    }
  }
  return modelIds;
}

// src/providers/claude/types/models.ts
var DEFAULT_CLAUDE_MODELS = [
  { value: "haiku", label: "Haiku", description: "Fast and efficient" },
  { value: "sonnet", label: "Sonnet", description: "Balanced performance" },
  { value: "sonnet[1m]", label: "Sonnet 1M", description: "Balanced performance (1M context window)" },
  { value: "opus", label: "Opus", description: "Most capable" },
  { value: "opus[1m]", label: "Opus 1M", description: "Most capable (1M context window)" }
];
var THINKING_BUDGETS = [
  { value: "off", label: "Off", tokens: 0 },
  { value: "low", label: "Low", tokens: 4e3 },
  { value: "medium", label: "Med", tokens: 8e3 },
  { value: "high", label: "High", tokens: 16e3 },
  { value: "xhigh", label: "Ultra", tokens: 32e3 }
];
var EFFORT_LEVELS = [
  { value: "low", label: "Low" },
  { value: "medium", label: "Med" },
  { value: "high", label: "High" },
  { value: "xhigh", label: "XHigh" },
  { value: "max", label: "Max" }
];
var DEFAULT_EFFORT_LEVEL = {
  "haiku": "high",
  "sonnet": "high",
  "sonnet[1m]": "high",
  "opus": "high",
  "opus[1m]": "high"
};
var DEFAULT_THINKING_BUDGET = {
  "haiku": "off",
  "sonnet": "low",
  "sonnet[1m]": "low",
  "opus": "medium",
  "opus[1m]": "medium"
};
var ONE_M_SUFFIX = "[1m]";
var DEFAULT_MODEL_VALUES = new Set(DEFAULT_CLAUDE_MODELS.map((m2) => m2.value.toLowerCase()));
function normalizeModelId(model) {
  return model.trim().toLowerCase();
}
function has1MContextSuffix(model) {
  return normalizeModelId(model).endsWith(ONE_M_SUFFIX);
}
function isBuiltInFamilyVariant(model, family) {
  const normalized = normalizeModelId(model);
  return normalized === family || normalized === `${family}${ONE_M_SUFFIX}`;
}
function isValidContextLimit(limit) {
  return typeof limit === "number" && limit > 0 && !isNaN(limit) && isFinite(limit);
}
function resolveCustomContextLimit(model, customLimits) {
  if (!customLimits) {
    return null;
  }
  const exactLimit = customLimits[model];
  if (isValidContextLimit(exactLimit)) {
    return exactLimit;
  }
  const normalizedModel = normalizeModelId(model);
  const matchingLimits = Object.entries(customLimits).filter(([key, limit]) => key !== model && normalizeModelId(key) === normalizedModel && isValidContextLimit(limit)).map(([, limit]) => limit);
  return matchingLimits.length === 1 ? matchingLimits[0] : null;
}
function isAdaptiveThinkingModel(model) {
  const normalized = normalizeModelId(model);
  if (DEFAULT_MODEL_VALUES.has(normalized)) return true;
  return /claude-(haiku|sonnet|opus)-/.test(normalized);
}
function isDefaultClaudeModel(model) {
  return DEFAULT_MODEL_VALUES.has(normalizeModelId(model));
}
function supportsXHighEffort(model) {
  const normalized = normalizeModelId(model);
  if (isBuiltInFamilyVariant(normalized, "opus")) return true;
  return /claude-opus-(4-[7-9]|[5-9])/.test(normalized);
}
function normalizeEffortLevel(model, effortLevel) {
  var _a3;
  const allowsXHigh = supportsXHighEffort(model);
  const isSupported = EFFORT_LEVELS.some(
    (level) => level.value === effortLevel && (allowsXHigh || level.value !== "xhigh")
  );
  if (isSupported) {
    return effortLevel;
  }
  return (_a3 = DEFAULT_EFFORT_LEVEL[normalizeModelId(model)]) != null ? _a3 : "high";
}
function resolveThinkingTokens(model, thinkingBudget) {
  var _a3;
  if (isAdaptiveThinkingModel(model)) {
    return null;
  }
  const budgetConfig = THINKING_BUDGETS.find((budget) => budget.value === thinkingBudget);
  const thinkingTokens = (_a3 = budgetConfig == null ? void 0 : budgetConfig.tokens) != null ? _a3 : null;
  return thinkingTokens && thinkingTokens > 0 ? thinkingTokens : null;
}
function resolveAdaptiveEffortLevel(model, effortLevel) {
  if (!isAdaptiveThinkingModel(model)) {
    return null;
  }
  return normalizeEffortLevel(model, effortLevel);
}
var CONTEXT_WINDOW_STANDARD = 2e5;
var CONTEXT_WINDOW_1M = 1e6;
function filterVisibleModelOptions(models, enableOpus1M, enableSonnet1M) {
  return models.filter((model) => {
    if (isBuiltInFamilyVariant(model.value, "opus")) {
      return enableOpus1M ? has1MContextSuffix(model.value) : normalizeModelId(model.value) === "opus";
    }
    if (isBuiltInFamilyVariant(model.value, "sonnet")) {
      return enableSonnet1M ? has1MContextSuffix(model.value) : normalizeModelId(model.value) === "sonnet";
    }
    return true;
  });
}
function normalizeVisibleModelVariant(model, enableOpus1M, enableSonnet1M) {
  if (isBuiltInFamilyVariant(model, "opus")) {
    return enableOpus1M ? "opus[1m]" : "opus";
  }
  if (isBuiltInFamilyVariant(model, "sonnet")) {
    return enableSonnet1M ? "sonnet[1m]" : "sonnet";
  }
  return model;
}
function getContextWindowSize(model, customLimits) {
  const customLimit = resolveCustomContextLimit(model, customLimits);
  if (customLimit !== null) {
    return customLimit;
  }
  if (has1MContextSuffix(model)) {
    return CONTEXT_WINDOW_1M;
  }
  return CONTEXT_WINDOW_STANDARD;
}

// src/providers/claude/modelOptions.ts
function parseConfiguredCustomModelIds(value) {
  const modelIds = [];
  const seen = /* @__PURE__ */ new Set();
  for (const line of value.split(/\r?\n/)) {
    const modelId = line.trim();
    if (!modelId || seen.has(modelId)) {
      continue;
    }
    seen.add(modelId);
    modelIds.push(modelId);
  }
  return modelIds;
}
function getClaudeModelOptions(settings11) {
  const customModels = getModelsFromEnvironment(
    getRuntimeEnvironmentVariables(settings11, "claude")
  );
  if (customModels.length > 0) {
    return customModels;
  }
  const claudeSettings = getClaudeProviderSettings(settings11);
  const models = filterVisibleModelOptions(
    [...DEFAULT_CLAUDE_MODELS],
    claudeSettings.enableOpus1M,
    claudeSettings.enableSonnet1M
  );
  const seenValues = new Set(models.map((model) => model.value));
  for (const modelId of parseConfiguredCustomModelIds(claudeSettings.customModels)) {
    if (seenValues.has(modelId)) {
      continue;
    }
    seenValues.add(modelId);
    models.push({
      value: modelId,
      label: formatCustomModelLabel(modelId),
      description: "Custom model"
    });
  }
  return models;
}
function resolveClaudeModelSelection(settings11, currentModel) {
  var _a3, _b2;
  const modelOptions = getClaudeModelOptions(settings11);
  if (currentModel && modelOptions.some((option) => option.value === currentModel)) {
    return currentModel;
  }
  const lastModel = getClaudeProviderSettings(settings11).lastModel;
  if (lastModel && modelOptions.some((option) => option.value === lastModel)) {
    return lastModel;
  }
  return (_b2 = (_a3 = modelOptions[0]) == null ? void 0 : _a3.value) != null ? _b2 : null;
}

// src/providers/claude/ui/AgentSettings.ts
var import_obsidian10 = require("obsidian");

// src/shared/modals/ConfirmModal.ts
var import_obsidian9 = require("obsidian");
function confirmDelete(app, message) {
  return new Promise((resolve8) => {
    new ConfirmModal(app, message, resolve8).open();
  });
}
function confirm2(app, message, confirmText) {
  return new Promise((resolve8) => {
    new ConfirmModal(app, message, resolve8, confirmText).open();
  });
}
var ConfirmModal = class extends import_obsidian9.Modal {
  constructor(app, message, resolve8, confirmText) {
    super(app);
    this.resolved = false;
    this.message = message;
    this.resolve = resolve8;
    this.confirmText = confirmText != null ? confirmText : t("common.delete");
  }
  onOpen() {
    this.setTitle(t("common.confirm"));
    this.modalEl.addClass("claudian-confirm-modal");
    this.contentEl.createEl("p", { text: this.message });
    new import_obsidian9.Setting(this.contentEl).addButton(
      (btn) => btn.setButtonText(t("common.cancel")).onClick(() => this.close())
    ).addButton(
      (btn) => btn.setButtonText(this.confirmText).setWarning().onClick(() => {
        this.resolved = true;
        this.resolve(true);
        this.close();
      })
    );
  }
  onClose() {
    if (!this.resolved) {
      this.resolve(false);
    }
    this.contentEl.empty();
  }
};

// src/providers/claude/ui/AgentSettings.ts
var MODEL_OPTIONS = [
  { value: "inherit", label: "Inherit" },
  { value: "sonnet", label: "Sonnet" },
  { value: "opus", label: "Opus" },
  { value: "haiku", label: "Haiku" }
];
var AgentModal = class extends import_obsidian10.Modal {
  constructor(app, existingAgent, getAvailableAgents, onSave) {
    super(app);
    this.existingAgent = existingAgent;
    this.getAvailableAgents = getAvailableAgents;
    this.onSave = onSave;
  }
  onOpen() {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2;
    this.setTitle(
      this.existingAgent ? t("settings.subagents.modal.titleEdit") : t("settings.subagents.modal.titleAdd")
    );
    this.modalEl.addClass("claudian-sp-modal");
    const { contentEl } = this;
    let nameInput;
    let descInput;
    let modelValue = (_b2 = (_a3 = this.existingAgent) == null ? void 0 : _a3.model) != null ? _b2 : "inherit";
    let toolsInput;
    let disallowedToolsInput;
    let skillsInput;
    new import_obsidian10.Setting(contentEl).setName(t("settings.subagents.modal.name")).setDesc(t("settings.subagents.modal.nameDesc")).addText((text) => {
      var _a4;
      nameInput = text.inputEl;
      text.setValue(((_a4 = this.existingAgent) == null ? void 0 : _a4.name) || "").setPlaceholder(t("settings.subagents.modal.namePlaceholder"));
    });
    new import_obsidian10.Setting(contentEl).setName(t("settings.subagents.modal.description")).setDesc(t("settings.subagents.modal.descriptionDesc")).addText((text) => {
      var _a4;
      descInput = text.inputEl;
      text.setValue(((_a4 = this.existingAgent) == null ? void 0 : _a4.description) || "").setPlaceholder(t("settings.subagents.modal.descriptionPlaceholder"));
    });
    const details = contentEl.createEl("details", { cls: "claudian-sp-advanced-section" });
    details.createEl("summary", {
      text: t("settings.subagents.modal.advancedOptions"),
      cls: "claudian-sp-advanced-summary"
    });
    if (((_c = this.existingAgent) == null ? void 0 : _c.model) && this.existingAgent.model !== "inherit" || ((_e = (_d2 = this.existingAgent) == null ? void 0 : _d2.tools) == null ? void 0 : _e.length) || ((_g = (_f = this.existingAgent) == null ? void 0 : _f.disallowedTools) == null ? void 0 : _g.length) || ((_i = (_h = this.existingAgent) == null ? void 0 : _h.skills) == null ? void 0 : _i.length)) {
      details.open = true;
    }
    new import_obsidian10.Setting(details).setName(t("settings.subagents.modal.model")).setDesc(t("settings.subagents.modal.modelDesc")).addDropdown((dropdown) => {
      for (const opt of MODEL_OPTIONS) {
        dropdown.addOption(opt.value, opt.label);
      }
      dropdown.setValue(modelValue).onChange((value) => {
        modelValue = value;
      });
    });
    new import_obsidian10.Setting(details).setName(t("settings.subagents.modal.tools")).setDesc(t("settings.subagents.modal.toolsDesc")).addText((text) => {
      var _a4, _b3;
      toolsInput = text.inputEl;
      text.setValue(((_b3 = (_a4 = this.existingAgent) == null ? void 0 : _a4.tools) == null ? void 0 : _b3.join(", ")) || "");
    });
    new import_obsidian10.Setting(details).setName(t("settings.subagents.modal.disallowedTools")).setDesc(t("settings.subagents.modal.disallowedToolsDesc")).addText((text) => {
      var _a4, _b3;
      disallowedToolsInput = text.inputEl;
      text.setValue(((_b3 = (_a4 = this.existingAgent) == null ? void 0 : _a4.disallowedTools) == null ? void 0 : _b3.join(", ")) || "");
    });
    new import_obsidian10.Setting(details).setName(t("settings.subagents.modal.skills")).setDesc(t("settings.subagents.modal.skillsDesc")).addText((text) => {
      var _a4, _b3;
      skillsInput = text.inputEl;
      text.setValue(((_b3 = (_a4 = this.existingAgent) == null ? void 0 : _a4.skills) == null ? void 0 : _b3.join(", ")) || "");
    });
    new import_obsidian10.Setting(contentEl).setName(t("settings.subagents.modal.prompt")).setDesc(t("settings.subagents.modal.promptDesc"));
    const contentArea = contentEl.createEl("textarea", {
      cls: "claudian-sp-content-area",
      attr: {
        rows: "10",
        placeholder: t("settings.subagents.modal.promptPlaceholder")
      }
    });
    contentArea.value = ((_j2 = this.existingAgent) == null ? void 0 : _j2.prompt) || "";
    const buttonContainer = contentEl.createDiv({ cls: "claudian-sp-modal-buttons" });
    const cancelBtn = buttonContainer.createEl("button", {
      text: t("common.cancel"),
      cls: "claudian-cancel-btn"
    });
    cancelBtn.addEventListener("click", () => this.close());
    const saveBtn = buttonContainer.createEl("button", {
      text: t("common.save"),
      cls: "claudian-save-btn"
    });
    saveBtn.addEventListener("click", async () => {
      var _a4, _b3, _c2, _d3;
      const name = nameInput.value.trim();
      const nameError = validateAgentName(name);
      if (nameError) {
        new import_obsidian10.Notice(nameError);
        return;
      }
      const description = descInput.value.trim();
      if (!description) {
        new import_obsidian10.Notice(t("settings.subagents.descriptionRequired"));
        return;
      }
      const prompt = contentArea.value;
      if (!prompt.trim()) {
        new import_obsidian10.Notice(t("settings.subagents.promptRequired"));
        return;
      }
      const allAgents = this.getAvailableAgents();
      const duplicate = allAgents.find(
        (a2) => {
          var _a5;
          return a2.id.toLowerCase() === name.toLowerCase() && a2.id !== ((_a5 = this.existingAgent) == null ? void 0 : _a5.id);
        }
      );
      if (duplicate) {
        new import_obsidian10.Notice(t("settings.subagents.duplicateName", { name }));
        return;
      }
      const parseList = (input) => {
        const val = input.value.trim();
        if (!val) return void 0;
        return val.split(",").map((s4) => s4.trim()).filter(Boolean);
      };
      const agent = {
        id: name,
        name,
        description,
        prompt,
        tools: parseList(toolsInput),
        disallowedTools: parseList(disallowedToolsInput),
        model: modelValue || "inherit",
        source: "vault",
        filePath: (_a4 = this.existingAgent) == null ? void 0 : _a4.filePath,
        skills: parseList(skillsInput),
        permissionMode: (_b3 = this.existingAgent) == null ? void 0 : _b3.permissionMode,
        hooks: (_c2 = this.existingAgent) == null ? void 0 : _c2.hooks,
        extraFrontmatter: (_d3 = this.existingAgent) == null ? void 0 : _d3.extraFrontmatter
      };
      try {
        await this.onSave(agent);
      } catch (err) {
        const message = err instanceof Error ? err.message : "Unknown error";
        new import_obsidian10.Notice(t("settings.subagents.saveFailed", { message }));
        return;
      }
      this.close();
    });
  }
  onClose() {
    this.contentEl.empty();
  }
};
var AgentSettings = class {
  constructor(containerEl, deps) {
    this.app = deps.app;
    this.containerEl = containerEl;
    this.agentManager = deps.agentManager;
    this.agentStorage = deps.agentStorage;
    this.render();
  }
  render() {
    this.containerEl.empty();
    const headerEl = this.containerEl.createDiv({ cls: "claudian-sp-header" });
    headerEl.createSpan({ text: t("settings.subagents.name"), cls: "claudian-sp-label" });
    const actionsEl = headerEl.createDiv({ cls: "claudian-sp-header-actions" });
    const refreshBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": t("common.refresh") }
    });
    (0, import_obsidian10.setIcon)(refreshBtn, "refresh-cw");
    refreshBtn.addEventListener("click", () => {
      void this.refreshAgents();
    });
    const addBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": t("common.add") }
    });
    (0, import_obsidian10.setIcon)(addBtn, "plus");
    addBtn.addEventListener("click", () => {
      void this.openAgentModal(null);
    });
    const allAgents = this.agentManager.getAvailableAgents();
    const vaultAgents = allAgents.filter((a2) => a2.source === "vault");
    if (vaultAgents.length === 0) {
      const emptyEl = this.containerEl.createDiv({ cls: "claudian-sp-empty-state" });
      emptyEl.setText(t("settings.subagents.noAgents"));
      return;
    }
    const listEl = this.containerEl.createDiv({ cls: "claudian-sp-list" });
    for (const agent of vaultAgents) {
      this.renderAgentItem(listEl, agent);
    }
  }
  renderAgentItem(listEl, agent) {
    const itemEl = listEl.createDiv({ cls: "claudian-sp-item" });
    const infoEl = itemEl.createDiv({ cls: "claudian-sp-info" });
    const headerRow = infoEl.createDiv({ cls: "claudian-sp-item-header" });
    const nameEl = headerRow.createSpan({ cls: "claudian-sp-item-name" });
    nameEl.setText(agent.name);
    if (agent.description) {
      const descEl = infoEl.createDiv({ cls: "claudian-sp-item-desc" });
      descEl.setText(agent.description);
    }
    const actionsEl = itemEl.createDiv({ cls: "claudian-sp-item-actions" });
    const editBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": t("common.edit") }
    });
    (0, import_obsidian10.setIcon)(editBtn, "pencil");
    editBtn.addEventListener("click", () => {
      void this.openAgentModal(agent);
    });
    const deleteBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn claudian-settings-delete-btn",
      attr: { "aria-label": t("common.delete") }
    });
    (0, import_obsidian10.setIcon)(deleteBtn, "trash-2");
    deleteBtn.addEventListener("click", async () => {
      const confirmed = await confirmDelete(
        this.app,
        t("settings.subagents.deleteConfirm", { name: agent.name })
      );
      if (!confirmed) return;
      try {
        await this.deleteAgent(agent);
      } catch (err) {
        const message = err instanceof Error ? err.message : "Unknown error";
        new import_obsidian10.Notice(t("settings.subagents.deleteFailed", { message }));
      }
    });
  }
  async refreshAgents() {
    try {
      await this.agentManager.loadAgents();
      this.render();
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      new import_obsidian10.Notice(t("settings.subagents.refreshFailed", { message }));
    }
  }
  async openAgentModal(existingAgent) {
    var _a3;
    let fresh;
    if (existingAgent) {
      try {
        fresh = (_a3 = await this.agentStorage.load(existingAgent)) != null ? _a3 : existingAgent;
      } catch (err) {
        const message = err instanceof Error ? err.message : "Unknown error";
        new import_obsidian10.Notice(`Failed to load subagent "${existingAgent.name}": ${message}`);
        return;
      }
    } else {
      fresh = null;
    }
    new AgentModal(
      this.app,
      fresh,
      () => this.agentManager.getAvailableAgents(),
      (agent) => this.saveAgent(agent, fresh)
    ).open();
  }
  async saveAgent(agent, existing) {
    if (existing && existing.name !== agent.name) {
      await this.agentStorage.save({ ...agent, filePath: void 0 });
      try {
        await this.agentStorage.delete(existing);
      } catch (e2) {
        new import_obsidian10.Notice(t("settings.subagents.renameCleanupFailed", { name: existing.name }));
      }
    } else {
      await this.agentStorage.save(agent);
    }
    try {
      await this.agentManager.loadAgents();
    } catch (e2) {
    }
    this.render();
    new import_obsidian10.Notice(
      existing ? t("settings.subagents.updated", { name: agent.name }) : t("settings.subagents.created", { name: agent.name })
    );
  }
  async deleteAgent(agent) {
    await this.agentStorage.delete(agent);
    try {
      await this.agentManager.loadAgents();
    } catch (e2) {
    }
    this.render();
    new import_obsidian10.Notice(t("settings.subagents.deleted", { name: agent.name }));
  }
};

// src/shared/icons.ts
var MCP_ICON_SVG = `<svg fill="currentColor" fill-rule="evenodd" height="1em" viewBox="0 0 24 24" width="1em" xmlns="http://www.w3.org/2000/svg"><title>MCP</title><path d="M15.688 2.343a2.588 2.588 0 00-3.61 0l-9.626 9.44a.863.863 0 01-1.203 0 .823.823 0 010-1.18l9.626-9.44a4.313 4.313 0 016.016 0 4.116 4.116 0 011.204 3.54 4.3 4.3 0 013.609 1.18l.05.05a4.115 4.115 0 010 5.9l-8.706 8.537a.274.274 0 000 .393l1.788 1.754a.823.823 0 010 1.18.863.863 0 01-1.203 0l-1.788-1.753a1.92 1.92 0 010-2.754l8.706-8.538a2.47 2.47 0 000-3.54l-.05-.049a2.588 2.588 0 00-3.607-.003l-7.172 7.034-.002.002-.098.097a.863.863 0 01-1.204 0 .823.823 0 010-1.18l7.273-7.133a2.47 2.47 0 00-.003-3.537z"></path><path d="M14.485 4.703a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a4.115 4.115 0 000 5.9 4.314 4.314 0 006.016 0l7.12-6.982a.823.823 0 000-1.18.863.863 0 00-1.204 0l-7.119 6.982a2.588 2.588 0 01-3.61 0 2.47 2.47 0 010-3.54l7.12-6.982z"></path></svg>`;
var CHECK_ICON_SVG = `<svg xmlns="http://www.w3.org/2000/svg" width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>`;
var OPENAI_PROVIDER_ICON = {
  viewBox: "-1 -.1 949.1 959.8",
  path: "m925.8 456.3c10.4 23.2 17 48 19.7 73.3 2.6 25.3 1.3 50.9-4.1 75.8-5.3 24.9-14.5 48.8-27.3 70.8-8.4 14.7-18.3 28.5-29.7 41.2-11.3 12.6-23.9 24-37.6 34-13.8 10-28.5 18.4-44.1 25.3-15.5 6.8-31.7 12-48.3 15.4-7.8 24.2-19.4 47.1-34.4 67.7-14.9 20.6-33 38.7-53.6 53.6-20.6 15-43.4 26.6-67.6 34.4-24.2 7.9-49.5 11.8-75 11.8-16.9.1-33.9-1.7-50.5-5.1-16.5-3.5-32.7-8.8-48.2-15.7s-30.2-15.5-43.9-25.5c-13.6-10-26.2-21.5-37.4-34.2-25 5.4-50.6 6.7-75.9 4.1-25.3-2.7-50.1-9.3-73.4-19.7-23.2-10.3-44.7-24.3-63.6-41.4s-35-37.1-47.7-59.1c-8.5-14.7-15.5-30.2-20.8-46.3s-8.8-32.7-10.6-49.6c-1.8-16.8-1.7-33.8.1-50.7 1.8-16.8 5.5-33.4 10.8-49.5-17-18.9-31-40.4-41.4-63.6-10.3-23.3-17-48-19.6-73.3-2.7-25.3-1.3-50.9 4-75.8s14.5-48.8 27.3-70.8c8.4-14.7 18.3-28.6 29.6-41.2s24-24 37.7-34 28.5-18.5 44-25.3c15.6-6.9 31.8-12 48.4-15.4 7.8-24.3 19.4-47.1 34.3-67.7 15-20.6 33.1-38.7 53.7-53.7 20.6-14.9 43.4-26.5 67.6-34.4 24.2-7.8 49.5-11.8 75-11.7 16.9-.1 33.9 1.6 50.5 5.1s32.8 8.7 48.3 15.6c15.5 7 30.2 15.5 43.9 25.5 13.7 10.1 26.3 21.5 37.5 34.2 24.9-5.3 50.5-6.6 75.8-4s50 9.3 73.3 19.6c23.2 10.4 44.7 24.3 63.6 41.4 18.9 17 35 36.9 47.7 59 8.5 14.6 15.5 30.1 20.8 46.3 5.3 16.1 8.9 32.7 10.6 49.6 1.8 16.9 1.8 33.9-.1 50.8-1.8 16.9-5.5 33.5-10.8 49.6 17.1 18.9 31 40.3 41.4 63.6zm-333.2 426.9c21.8-9 41.6-22.3 58.3-39s30-36.5 39-58.4c9-21.8 13.7-45.2 13.7-68.8v-223q-.1-.3-.2-.7-.1-.3-.3-.6-.2-.3-.5-.5-.3-.3-.6-.4l-80.7-46.6v269.4c0 2.7-.4 5.5-1.1 8.1-.7 2.7-1.7 5.2-3.1 7.6s-3 4.6-5 6.5a32.1 32.1 0 0 1-6.5 5l-191.1 110.3c-1.6 1-4.3 2.4-5.7 3.2 7.9 6.7 16.5 12.6 25.5 17.8 9.1 5.2 18.5 9.6 28.3 13.2 9.8 3.5 19.9 6.2 30.1 8 10.3 1.8 20.7 2.7 31.1 2.7 23.6 0 47-4.7 68.8-13.8zm-455.1-151.4c11.9 20.5 27.6 38.3 46.3 52.7 18.8 14.4 40.1 24.9 62.9 31s46.6 7.7 70 4.6 45.9-10.7 66.4-22.5l193.2-111.5.5-.5q.2-.2.3-.6.2-.3.3-.6v-94l-233.2 134.9c-2.4 1.4-4.9 2.4-7.5 3.2-2.7.7-5.4 1-8.2 1-2.7 0-5.4-.3-8.1-1-2.6-.8-5.2-1.8-7.6-3.2l-191.1-110.4c-1.7-1-4.2-2.5-5.6-3.4-1.8 10.3-2.7 20.7-2.7 31.1s1 20.8 2.8 31.1c1.8 10.2 4.6 20.3 8.1 30.1 3.6 9.8 8 19.2 13.2 28.2zm-50.2-417c-11.8 20.5-19.4 43.1-22.5 66.5s-1.5 47.1 4.6 70c6.1 22.8 16.6 44.1 31 62.9 14.4 18.7 32.3 34.4 52.7 46.2l193.1 111.6q.3.1.7.2h.7q.4 0 .7-.2.3-.1.6-.3l81-46.8-233.2-134.6c-2.3-1.4-4.5-3.1-6.5-5a32.1 32.1 0 0 1-5-6.5c-1.3-2.4-2.4-4.9-3.1-7.6-.7-2.6-1.1-5.3-1-8.1v-227.1c-9.8 3.6-19.3 8-28.3 13.2-9 5.3-17.5 11.3-25.5 18-7.9 6.7-15.3 14.1-22 22.1-6.7 7.9-12.6 16.5-17.8 25.5zm663.3 154.4c2.4 1.4 4.6 3 6.6 5 1.9 1.9 3.6 4.1 5 6.5 1.3 2.4 2.4 5 3.1 7.6.6 2.7 1 5.4.9 8.2v227.1c32.1-11.8 60.1-32.5 80.8-59.7 20.8-27.2 33.3-59.7 36.2-93.7s-3.9-68.2-19.7-98.5-39.9-55.5-69.5-72.5l-193.1-111.6q-.3-.1-.7-.2h-.7q-.3.1-.7.2-.3.1-.6.3l-80.6 46.6 233.2 134.7zm80.5-121h-.1v.1zm-.1-.1c5.8-33.6 1.9-68.2-11.3-99.7-13.1-31.5-35-58.6-63-78.2-28-19.5-61-30.7-95.1-32.2-34.2-1.4-68 6.9-97.6 23.9l-193.1 111.5q-.3.2-.5.5l-.4.6q-.1.3-.2.7-.1.3-.1.7v93.2l233.2-134.7c2.4-1.4 5-2.4 7.6-3.2 2.7-.7 5.4-1 8.1-1 2.8 0 5.5.3 8.2 1 2.6.8 5.1 1.8 7.5 3.2l191.1 110.4c1.7 1 4.2 2.4 5.6 3.3zm-505.3-103.2c0-2.7.4-5.4 1.1-8.1.7-2.6 1.7-5.2 3.1-7.6 1.4-2.3 3-4.5 5-6.5 1.9-1.9 4.1-3.6 6.5-4.9l191.1-110.3c1.8-1.1 4.3-2.5 5.7-3.2-26.2-21.9-58.2-35.9-92.1-40.2-33.9-4.4-68.3 1-99.2 15.5-31 14.5-57.2 37.6-75.5 66.4-18.3 28.9-28 62.3-28 96.5v223q.1.4.2.7.1.3.3.6.2.3.5.6.2.2.6.4l80.7 46.6zm43.8 294.7 103.9 60 103.9-60v-119.9l-103.8-60-103.9 60z"
};
var CLAUDE_PROVIDER_ICON = {
  viewBox: "0 -.01 39.5 39.53",
  path: "m7.75 26.27 7.77-4.36.13-.38-.13-.21h-.38l-1.3-.08-4.44-.12-3.85-.16-3.73-.2-.94-.2-.88-1.16.09-.58.79-.53 1.13.1 2.5.17 3.75.26 2.72.16 4.03.42h.64l.09-.26-.22-.16-.17-.16-3.88-2.63-4.2-2.78-2.2-1.6-1.19-.81-.6-.76-.26-1.66 1.08-1.19 1.45.1.37.1 1.47 1.13 3.14 2.43 4.1 3.02.6.5.24-.17.03-.12-.27-.45-2.23-4.03-2.38-4.1-1.06-1.7-.28-1.02c-.1-.42-.17-.77-.17-1.2l1.23-1.67.68-.22 1.64.22.69.6 1.02 2.33 1.65 3.67 2.56 4.99.75 1.48.4 1.37.15.42h.26v-.24l.21-2.81.39-3.45.38-4.44.13-1.25.62-1.5 1.23-.81.96.46.79 1.13-.11.73-.47 3.05-.92 4.78-.6 3.2h.35l.4-.4 1.62-2.15 2.72-3.4 1.2-1.35 1.4-1.49.9-.71h1.7l1.25 1.86-.56 1.92-1.75 2.22-1.45 1.88-2.08 2.8-1.3 2.24.12.18.31-.03 4.7-1 2.54-.46 3.03-.52 1.37.64.15.65-.54 1.33-3.24.8-3.8.76-5.66 1.34-.07.05.08.1 2.55.24 1.09.06h2.67l4.97.37 1.3.86.78 1.05-.13.8-2 1.02-2.7-.64-6.3-1.5-2.16-.54h-.3v.18l1.8 1.76 3.3 2.98 4.13 3.84.21.95-.53.75-.56-.08-3.63-2.73-1.4-1.23-3.17-2.67h-.21v.28l.73 1.07 3.86 5.8.2 1.78-.28.58-1 .35-1.1-.2-2.26-3.17-2.33-3.57-1.88-3.2-.23.13-1.11 11.95-.52.61-1.2.46-1-.76-.53-1.23.53-2.43.64-3.17.52-2.52.47-3.13.28-1.04-.02-.07-.23.03-2.36 3.24-3.59 4.85-2.84 3.04-.68.27-1.18-.61.11-1.09.66-.97 3.93-5 2.37-3.1 1.53-1.79-.01-.26h-.09l-10.44 6.78-1.86.24-.8-.75.1-1.23.38-.4 3.14-2.16z"
};
var OPENCODE_PROVIDER_ICON = {
  kind: "markup",
  viewBox: "0 0 300 300",
  markup: `
    <g class="claudian-provider-icon-variant claudian-provider-icon-variant--light" transform="translate(30 0)">
      <path d="M180 240H60V120H180V240Z" fill="#CFCECD"></path>
      <path d="M180 60H60V240H180V60ZM240 300H0V0H240V300Z" fill="#211E1E"></path>
    </g>
    <g class="claudian-provider-icon-variant claudian-provider-icon-variant--dark" transform="translate(30 0)">
      <path d="M180 240H60V120H180V240Z" fill="#4B4646"></path>
      <path d="M180 60H60V240H180V60ZM240 300H0V0H240V300Z" fill="#F1ECEC"></path>
    </g>
  `
};
function createProviderIconSvg(icon, options = {}) {
  const NS = "http://www.w3.org/2000/svg";
  const svg = document.createElementNS(NS, "svg");
  svg.setAttribute("viewBox", icon.viewBox);
  svg.setAttribute("fill", "none");
  svg.setAttribute("aria-hidden", "true");
  svg.classList.add("claudian-provider-icon");
  if (options.width !== void 0) {
    svg.setAttribute("width", String(options.width));
  }
  if (options.height !== void 0) {
    svg.setAttribute("height", String(options.height));
  }
  if (options.className) {
    svg.classList.add(...options.className.split(/\s+/).filter(Boolean));
  }
  if (options.dataProvider) {
    svg.setAttribute("data-provider", options.dataProvider);
  }
  if (icon.kind === "markup") {
    svg.innerHTML = icon.markup.trim();
    return svg;
  }
  const path24 = document.createElementNS(NS, "path");
  path24.setAttribute("d", icon.path);
  path24.setAttribute("fill", "currentColor");
  svg.appendChild(path24);
  return svg;
}

// src/providers/claude/ui/ClaudeChatUIConfig.ts
var CLAUDE_PERMISSION_MODE_TOGGLE = {
  inactiveValue: "normal",
  inactiveLabel: "Safe",
  activeValue: "yolo",
  activeLabel: "YOLO",
  planValue: "plan",
  planLabel: "PLAN"
};
var claudeChatUIConfig = {
  getModelOptions(settings11) {
    return getClaudeModelOptions(settings11);
  },
  ownsModel(model, settings11) {
    return this.getModelOptions(settings11).some((option) => option.value === model);
  },
  isAdaptiveReasoningModel(model, _settings) {
    return isAdaptiveThinkingModel(model);
  },
  getReasoningOptions(model, _settings) {
    if (isAdaptiveThinkingModel(model)) {
      const levels = supportsXHighEffort(model) ? EFFORT_LEVELS : EFFORT_LEVELS.filter((e2) => e2.value !== "xhigh");
      return levels.map((e2) => ({ value: e2.value, label: e2.label }));
    }
    return THINKING_BUDGETS.map((b10) => ({ value: b10.value, label: b10.label, tokens: b10.tokens }));
  },
  getDefaultReasoningValue(model, _settings) {
    var _a3, _b2;
    if (isAdaptiveThinkingModel(model)) {
      return (_a3 = DEFAULT_EFFORT_LEVEL[model]) != null ? _a3 : "high";
    }
    return (_b2 = DEFAULT_THINKING_BUDGET[model]) != null ? _b2 : "off";
  },
  getContextWindowSize(model, customLimits) {
    return getContextWindowSize(model, customLimits);
  },
  isDefaultModel(model) {
    return DEFAULT_CLAUDE_MODELS.some((m2) => m2.value === model);
  },
  applyModelDefaults(model, settings11) {
    var _a3;
    const target = settings11;
    if (DEFAULT_CLAUDE_MODELS.some((m2) => m2.value === model)) {
      target.thinkingBudget = DEFAULT_THINKING_BUDGET[model];
      if (isAdaptiveThinkingModel(model)) {
        target.effortLevel = (_a3 = DEFAULT_EFFORT_LEVEL[model]) != null ? _a3 : "high";
      }
      updateClaudeProviderSettings(target, { lastModel: model });
    } else {
      target.lastCustomModel = model;
      if (isAdaptiveThinkingModel(model)) {
        target.effortLevel = normalizeEffortLevel(model, target.effortLevel);
      }
    }
  },
  normalizeModelVariant(model, settings11) {
    const claudeSettings = getClaudeProviderSettings(settings11);
    return normalizeVisibleModelVariant(
      model,
      claudeSettings.enableOpus1M,
      claudeSettings.enableSonnet1M
    );
  },
  getCustomModelIds(envVars) {
    return getCustomModelIds(envVars);
  },
  getPermissionModeToggle() {
    return CLAUDE_PERMISSION_MODE_TOGGLE;
  },
  isBangBashEnabled(settings11) {
    return getClaudeProviderSettings(settings11).enableBangBash;
  },
  getProviderIcon() {
    return CLAUDE_PROVIDER_ICON;
  }
};

// src/providers/claude/ui/PluginSettingsManager.ts
var import_obsidian11 = require("obsidian");
var PluginSettingsManager = class {
  constructor(containerEl, deps) {
    this.containerEl = containerEl;
    this.pluginManager = deps.pluginManager;
    this.agentManager = deps.agentManager;
    this.restartTabs = deps.restartTabs;
    this.render();
  }
  render() {
    this.containerEl.empty();
    const headerEl = this.containerEl.createDiv({ cls: "claudian-plugin-header" });
    headerEl.createSpan({ text: "Claude Code Plugins", cls: "claudian-plugin-label" });
    const refreshBtn = headerEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Refresh" }
    });
    (0, import_obsidian11.setIcon)(refreshBtn, "refresh-cw");
    refreshBtn.addEventListener("click", () => this.refreshPlugins());
    const plugins = this.pluginManager.getPlugins();
    if (plugins.length === 0) {
      const emptyEl = this.containerEl.createDiv({ cls: "claudian-plugin-empty" });
      emptyEl.setText("No Claude Code plugins found. Enable plugins via the Claude CLI.");
      return;
    }
    const projectPlugins = plugins.filter((p) => p.scope === "project");
    const userPlugins = plugins.filter((p) => p.scope === "user");
    const listEl = this.containerEl.createDiv({ cls: "claudian-plugin-list" });
    if (projectPlugins.length > 0) {
      const sectionHeader = listEl.createDiv({ cls: "claudian-plugin-section-header" });
      sectionHeader.setText("Project Plugins");
      for (const plugin of projectPlugins) {
        this.renderPluginItem(listEl, plugin);
      }
    }
    if (userPlugins.length > 0) {
      const sectionHeader = listEl.createDiv({ cls: "claudian-plugin-section-header" });
      sectionHeader.setText("User Plugins");
      for (const plugin of userPlugins) {
        this.renderPluginItem(listEl, plugin);
      }
    }
  }
  renderPluginItem(listEl, plugin) {
    const itemEl = listEl.createDiv({ cls: "claudian-plugin-item" });
    if (!plugin.enabled) {
      itemEl.addClass("claudian-plugin-item-disabled");
    }
    const statusEl = itemEl.createDiv({ cls: "claudian-plugin-status" });
    if (plugin.enabled) {
      statusEl.addClass("claudian-plugin-status-enabled");
    } else {
      statusEl.addClass("claudian-plugin-status-disabled");
    }
    const infoEl = itemEl.createDiv({ cls: "claudian-plugin-info" });
    const nameRow = infoEl.createDiv({ cls: "claudian-plugin-name-row" });
    const nameEl = nameRow.createSpan({ cls: "claudian-plugin-name" });
    nameEl.setText(plugin.name);
    const actionsEl = itemEl.createDiv({ cls: "claudian-plugin-actions" });
    const toggleBtn = actionsEl.createEl("button", {
      cls: "claudian-plugin-action-btn",
      attr: { "aria-label": plugin.enabled ? "Disable" : "Enable" }
    });
    (0, import_obsidian11.setIcon)(toggleBtn, plugin.enabled ? "toggle-right" : "toggle-left");
    toggleBtn.addEventListener("click", () => this.togglePlugin(plugin.id));
  }
  async togglePlugin(pluginId) {
    var _a3;
    const plugin = this.pluginManager.getPlugins().find((p) => p.id === pluginId);
    const wasEnabled = (_a3 = plugin == null ? void 0 : plugin.enabled) != null ? _a3 : false;
    try {
      await this.pluginManager.togglePlugin(pluginId);
      await this.agentManager.loadAgents();
      try {
        await this.restartTabs();
      } catch (e2) {
        new import_obsidian11.Notice("Plugin toggled, but some tabs failed to restart.");
      }
      new import_obsidian11.Notice(`Plugin "${pluginId}" ${wasEnabled ? "disabled" : "enabled"}`);
    } catch (err) {
      await this.pluginManager.togglePlugin(pluginId);
      const message = err instanceof Error ? err.message : "Unknown error";
      new import_obsidian11.Notice(`Failed to toggle plugin: ${message}`);
    } finally {
      this.render();
    }
  }
  async refreshPlugins() {
    try {
      await this.pluginManager.loadPlugins();
      await this.agentManager.loadAgents();
      new import_obsidian11.Notice("Plugin list refreshed");
    } catch (err) {
      const message = err instanceof Error ? err.message : "Unknown error";
      new import_obsidian11.Notice(`Failed to refresh plugins: ${message}`);
    } finally {
      this.render();
    }
  }
  refresh() {
    this.render();
  }
};

// src/providers/claude/ui/SlashCommandSettings.ts
var import_obsidian12 = require("obsidian");
function resolveAllowedTools(inputValue, parsedTools) {
  const trimmed = inputValue.trim();
  if (trimmed) {
    return trimmed.split(",").map((s4) => s4.trim()).filter(Boolean);
  }
  if (parsedTools && parsedTools.length > 0) {
    return parsedTools;
  }
  return void 0;
}
function isSkillEntry(entry) {
  return entry.kind === "skill";
}
var SlashCommandModal = class extends import_obsidian12.Modal {
  constructor(app, entries, existingEntry, onSave) {
    super(app);
    this.entries = entries;
    this.existingEntry = existingEntry;
    this.onSave = onSave;
  }
  onOpen() {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l, _m;
    const existingIsSkill = this.existingEntry ? isSkillEntry(this.existingEntry) : false;
    let selectedType = existingIsSkill ? "skill" : "command";
    const typeLabel = () => selectedType === "skill" ? "Skill" : "Slash Command";
    this.setTitle(this.existingEntry ? `Edit ${typeLabel()}` : `Add ${typeLabel()}`);
    this.modalEl.addClass("claudian-sp-modal");
    const { contentEl } = this;
    let nameInput;
    let descInput;
    let hintInput;
    let modelInput;
    let toolsInput;
    let disableModelToggle = (_b2 = (_a3 = this.existingEntry) == null ? void 0 : _a3.disableModelInvocation) != null ? _b2 : false;
    let disableUserInvocation = ((_c = this.existingEntry) == null ? void 0 : _c.userInvocable) === false;
    let contextValue = (_e = (_d2 = this.existingEntry) == null ? void 0 : _d2.context) != null ? _e : "";
    let agentInput;
    let disableUserSetting;
    let disableUserToggle;
    const updateSkillOnlyFields = () => {
      const isSkillType = selectedType === "skill";
      disableUserSetting.settingEl.style.display = isSkillType ? "" : "none";
      if (!isSkillType) {
        disableUserInvocation = false;
        disableUserToggle.setValue(false);
      }
    };
    new import_obsidian12.Setting(contentEl).setName("Type").setDesc("Command or skill").addDropdown((dropdown) => {
      dropdown.addOption("command", "Command").addOption("skill", "Skill").setValue(selectedType).onChange((value) => {
        selectedType = value;
        this.setTitle(this.existingEntry ? `Edit ${typeLabel()}` : `Add ${typeLabel()}`);
        updateSkillOnlyFields();
      });
      if (this.existingEntry) {
        dropdown.setDisabled(true);
      }
    });
    new import_obsidian12.Setting(contentEl).setName("Command name").setDesc('The name used after / (e.g., "review" for /review)').addText((text) => {
      var _a4;
      nameInput = text.inputEl;
      text.setValue(((_a4 = this.existingEntry) == null ? void 0 : _a4.name) || "").setPlaceholder("review-code");
    });
    new import_obsidian12.Setting(contentEl).setName("Description").setDesc("Optional description shown in dropdown").addText((text) => {
      var _a4;
      descInput = text.inputEl;
      text.setValue(((_a4 = this.existingEntry) == null ? void 0 : _a4.description) || "");
    });
    const details = contentEl.createEl("details", { cls: "claudian-sp-advanced-section" });
    details.createEl("summary", {
      text: "Advanced options",
      cls: "claudian-sp-advanced-summary"
    });
    if (((_f = this.existingEntry) == null ? void 0 : _f.argumentHint) || ((_g = this.existingEntry) == null ? void 0 : _g.model) || ((_i = (_h = this.existingEntry) == null ? void 0 : _h.allowedTools) == null ? void 0 : _i.length) || ((_j2 = this.existingEntry) == null ? void 0 : _j2.disableModelInvocation) || ((_k = this.existingEntry) == null ? void 0 : _k.userInvocable) === false || ((_l = this.existingEntry) == null ? void 0 : _l.context) || ((_m = this.existingEntry) == null ? void 0 : _m.agent)) {
      details.open = true;
    }
    new import_obsidian12.Setting(details).setName("Argument hint").setDesc('Placeholder text for arguments (e.g., "[file] [focus]")').addText((text) => {
      var _a4;
      hintInput = text.inputEl;
      text.setValue(((_a4 = this.existingEntry) == null ? void 0 : _a4.argumentHint) || "");
    });
    new import_obsidian12.Setting(details).setName("Model override").setDesc("Optional model to use for this command").addText((text) => {
      var _a4;
      modelInput = text.inputEl;
      text.setValue(((_a4 = this.existingEntry) == null ? void 0 : _a4.model) || "").setPlaceholder("claude-sonnet-4-5");
    });
    new import_obsidian12.Setting(details).setName("Allowed tools").setDesc("Comma-separated list of tools to allow (empty = all)").addText((text) => {
      var _a4, _b3;
      toolsInput = text.inputEl;
      text.setValue(((_b3 = (_a4 = this.existingEntry) == null ? void 0 : _a4.allowedTools) == null ? void 0 : _b3.join(", ")) || "");
    });
    new import_obsidian12.Setting(details).setName("Disable model invocation").setDesc("Prevent the model from invoking this command itself").addToggle((toggle) => {
      toggle.setValue(disableModelToggle).onChange((value) => {
        disableModelToggle = value;
      });
    });
    disableUserSetting = new import_obsidian12.Setting(details).setName("Disable user invocation").setDesc("Prevent the user from invoking this skill directly").addToggle((toggle) => {
      disableUserToggle = toggle;
      toggle.setValue(disableUserInvocation).onChange((value) => {
        disableUserInvocation = value;
      });
    });
    updateSkillOnlyFields();
    new import_obsidian12.Setting(details).setName("Context").setDesc("Run in a subagent (fork)").addToggle((toggle) => {
      toggle.setValue(contextValue === "fork").onChange((value) => {
        contextValue = value ? "fork" : "";
        agentSetting.settingEl.style.display = value ? "" : "none";
      });
    });
    const agentSetting = new import_obsidian12.Setting(details).setName("Agent").setDesc("Subagent type when context is fork").addText((text) => {
      var _a4;
      agentInput = text.inputEl;
      text.setValue(((_a4 = this.existingEntry) == null ? void 0 : _a4.agent) || "").setPlaceholder("code-reviewer");
    });
    agentSetting.settingEl.style.display = contextValue === "fork" ? "" : "none";
    new import_obsidian12.Setting(contentEl).setName("Prompt template").setDesc("Use $ARGUMENTS, $1, $2, @file, !`bash`");
    const contentArea = contentEl.createEl("textarea", {
      cls: "claudian-sp-content-area",
      attr: {
        rows: "10",
        placeholder: "Review this code for:\n$ARGUMENTS\n\n@$1"
      }
    });
    const initialContent = this.existingEntry ? parseSlashCommandContent(this.existingEntry.content).promptContent : "";
    contentArea.value = initialContent;
    const buttonContainer = contentEl.createDiv({ cls: "claudian-sp-modal-buttons" });
    const cancelBtn = buttonContainer.createEl("button", {
      text: "Cancel",
      cls: "claudian-cancel-btn"
    });
    cancelBtn.addEventListener("click", () => this.close());
    const saveBtn = buttonContainer.createEl("button", {
      text: "Save",
      cls: "claudian-save-btn"
    });
    saveBtn.addEventListener("click", async () => {
      var _a4, _b3, _c2, _d3, _e2, _f2;
      const name = nameInput.value.trim();
      const nameError = validateCommandName(name);
      if (nameError) {
        new import_obsidian12.Notice(nameError);
        return;
      }
      const content = contentArea.value;
      if (!content.trim()) {
        new import_obsidian12.Notice("Prompt template is required");
        return;
      }
      const existing = this.entries.find(
        (entry2) => {
          var _a5;
          return entry2.name.toLowerCase() === name.toLowerCase() && entry2.id !== ((_a5 = this.existingEntry) == null ? void 0 : _a5.id);
        }
      );
      if (existing) {
        new import_obsidian12.Notice(`A command named "/${name}" already exists`);
        return;
      }
      const parsed = parseSlashCommandContent(content);
      const promptContent = parsed.promptContent;
      const isSkillType = selectedType === "skill";
      const entry = {
        id: ((_a4 = this.existingEntry) == null ? void 0 : _a4.id) || (isSkillType ? `skill-${name}` : `cmd-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`),
        providerId: "claude",
        kind: isSkillType ? "skill" : "command",
        name,
        description: descInput.value.trim() || parsed.description || void 0,
        argumentHint: normalizeArgumentHint(hintInput.value.trim()) || parsed.argumentHint || void 0,
        allowedTools: resolveAllowedTools(toolsInput.value, parsed.allowedTools),
        model: modelInput.value.trim() || parsed.model || void 0,
        content: promptContent,
        disableModelInvocation: disableModelToggle || void 0,
        userInvocable: disableUserInvocation ? false : void 0,
        context: contextValue || void 0,
        agent: contextValue === "fork" ? agentInput.value.trim() || void 0 : void 0,
        hooks: (_c2 = parsed.hooks) != null ? _c2 : (_b3 = this.existingEntry) == null ? void 0 : _b3.hooks,
        scope: "vault",
        source: (_e2 = (_d3 = this.existingEntry) == null ? void 0 : _d3.source) != null ? _e2 : "user",
        isEditable: true,
        isDeletable: true,
        displayPrefix: "/",
        insertPrefix: "/",
        persistenceKey: (_f2 = this.existingEntry) == null ? void 0 : _f2.persistenceKey
      };
      try {
        await this.onSave(entry);
      } catch (e2) {
        const label = isSkillType ? "skill" : "slash command";
        new import_obsidian12.Notice(`Failed to save ${label}`);
        return;
      }
      this.close();
    });
    const handleKeyDown = (e2) => {
      if (e2.key === "Escape") {
        e2.preventDefault();
        this.close();
      }
    };
    contentEl.addEventListener("keydown", handleKeyDown);
  }
  onClose() {
    this.contentEl.empty();
  }
};
var SlashCommandSettings = class {
  constructor(containerEl, app, catalog) {
    this.commands = [];
    this.app = app;
    this.containerEl = containerEl;
    this.catalog = catalog;
    void this.loadAndRender();
  }
  async loadAndRender() {
    if (!this.catalog) {
      this.renderUnavailable();
      return;
    }
    this.commands = await this.catalog.listVaultEntries();
    this.render();
  }
  renderUnavailable() {
    this.containerEl.empty();
    const emptyEl = this.containerEl.createDiv({ cls: "claudian-sp-empty-state" });
    emptyEl.setText("Claude command catalog is unavailable.");
  }
  render() {
    this.containerEl.empty();
    const headerEl = this.containerEl.createDiv({ cls: "claudian-sp-header" });
    headerEl.createSpan({ text: t("settings.slashCommands.name"), cls: "claudian-sp-label" });
    const actionsEl = headerEl.createDiv({ cls: "claudian-sp-header-actions" });
    const addBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Add" }
    });
    (0, import_obsidian12.setIcon)(addBtn, "plus");
    addBtn.addEventListener("click", () => this.openCommandModal(null));
    if (this.commands.length === 0) {
      const emptyEl = this.containerEl.createDiv({ cls: "claudian-sp-empty-state" });
      emptyEl.setText("No commands or skills configured. Click + to create one.");
      return;
    }
    const listEl = this.containerEl.createDiv({ cls: "claudian-sp-list" });
    for (const cmd of this.commands) {
      this.renderCommandItem(listEl, cmd);
    }
  }
  renderCommandItem(listEl, cmd) {
    const itemEl = listEl.createDiv({ cls: "claudian-sp-item" });
    const infoEl = itemEl.createDiv({ cls: "claudian-sp-info" });
    const headerRow = infoEl.createDiv({ cls: "claudian-sp-item-header" });
    const nameEl = headerRow.createSpan({ cls: "claudian-sp-item-name" });
    nameEl.setText(`/${cmd.name}`);
    if (isSkillEntry(cmd)) {
      headerRow.createSpan({ text: "skill", cls: "claudian-slash-item-badge" });
    }
    if (cmd.argumentHint) {
      const hintEl = headerRow.createSpan({ cls: "claudian-slash-item-hint" });
      hintEl.setText(cmd.argumentHint);
    }
    if (cmd.description) {
      const descEl = infoEl.createDiv({ cls: "claudian-sp-item-desc" });
      descEl.setText(cmd.description);
    }
    const actionsEl = itemEl.createDiv({ cls: "claudian-sp-item-actions" });
    if (cmd.isEditable) {
      const editBtn = actionsEl.createEl("button", {
        cls: "claudian-settings-action-btn",
        attr: { "aria-label": "Edit" }
      });
      (0, import_obsidian12.setIcon)(editBtn, "pencil");
      editBtn.addEventListener("click", () => this.openCommandModal(cmd));
    }
    if (!isSkillEntry(cmd) && cmd.isEditable) {
      const convertBtn = actionsEl.createEl("button", {
        cls: "claudian-settings-action-btn",
        attr: { "aria-label": "Convert to skill" }
      });
      (0, import_obsidian12.setIcon)(convertBtn, "package");
      convertBtn.addEventListener("click", async () => {
        try {
          await this.transformToSkill(cmd);
        } catch (e2) {
          new import_obsidian12.Notice("Failed to convert to skill");
        }
      });
    }
    if (cmd.isDeletable) {
      const deleteBtn = actionsEl.createEl("button", {
        cls: "claudian-settings-action-btn claudian-settings-delete-btn",
        attr: { "aria-label": "Delete" }
      });
      (0, import_obsidian12.setIcon)(deleteBtn, "trash-2");
      deleteBtn.addEventListener("click", async () => {
        try {
          await this.deleteCommand(cmd);
        } catch (e2) {
          const label = isSkillEntry(cmd) ? "skill" : "slash command";
          new import_obsidian12.Notice(`Failed to delete ${label}`);
        }
      });
    }
  }
  openCommandModal(existingCmd) {
    const modal = new SlashCommandModal(
      this.app,
      this.commands,
      existingCmd,
      async (cmd) => {
        await this.saveCommand(cmd, existingCmd);
      }
    );
    modal.open();
  }
  async saveCommand(cmd, existing) {
    if (!this.catalog) {
      return;
    }
    await this.catalog.saveVaultEntry(cmd);
    if (existing && existing.name !== cmd.name) {
      await this.catalog.deleteVaultEntry(existing);
    }
    await this.reloadCommands();
    this.render();
    const label = isSkillEntry(cmd) ? "Skill" : "Slash command";
    new import_obsidian12.Notice(`${label} "/${cmd.name}" ${existing ? "updated" : "created"}`);
  }
  async deleteCommand(cmd) {
    if (!this.catalog) {
      return;
    }
    await this.catalog.deleteVaultEntry(cmd);
    await this.reloadCommands();
    this.render();
    const label = isSkillEntry(cmd) ? "Skill" : "Slash command";
    new import_obsidian12.Notice(`${label} "/${cmd.name}" deleted`);
  }
  async transformToSkill(cmd) {
    if (!this.catalog) {
      return;
    }
    const skillName = cmd.name.toLowerCase().replace(/[^a-z0-9-]/g, "-").slice(0, 64);
    const existingSkill = this.commands.find(
      (entry) => isSkillEntry(entry) && entry.name === skillName
    );
    if (existingSkill) {
      new import_obsidian12.Notice(`A skill named "/${skillName}" already exists`);
      return;
    }
    const skill = {
      ...cmd,
      id: `skill-${skillName}`,
      kind: "skill",
      name: skillName,
      description: cmd.description || extractFirstParagraph(cmd.content),
      source: "user",
      scope: "vault",
      isEditable: true,
      isDeletable: true,
      displayPrefix: "/",
      insertPrefix: "/"
    };
    await this.catalog.saveVaultEntry(skill);
    await this.catalog.deleteVaultEntry(cmd);
    await this.reloadCommands();
    this.render();
    new import_obsidian12.Notice(`Converted "/${cmd.name}" to skill`);
  }
  async reloadCommands() {
    if (!this.catalog) {
      this.commands = [];
      return;
    }
    this.commands = await this.catalog.listVaultEntries();
  }
  refresh() {
    void this.loadAndRender();
  }
};

// src/providers/claude/ui/ClaudeSettingsTab.ts
var claudeSettingsTabRenderer = {
  render(container, context) {
    const claudeWorkspace = getClaudeWorkspaceServices();
    const settingsBag = context.plugin.settings;
    const claudeSettings = getClaudeProviderSettings(settingsBag);
    const reconcileActiveClaudeModelSelection = () => {
      const activeProvider = settingsBag.settingsProvider;
      if (activeProvider !== void 0 && activeProvider !== "claude") {
        return;
      }
      const currentModel = typeof settingsBag.model === "string" ? settingsBag.model : "";
      const nextModel = resolveClaudeModelSelection(settingsBag, currentModel);
      if (!nextModel || nextModel === currentModel) {
        return;
      }
      settingsBag.model = nextModel;
      claudeChatUIConfig.applyModelDefaults(nextModel, settingsBag);
    };
    new import_obsidian13.Setting(container).setName(t("settings.setup")).setHeading();
    const hostnameKey = getHostnameKey();
    const platformDesc = process.platform === "win32" ? t("settings.cliPath.descWindows") : t("settings.cliPath.descUnix");
    const cliPathDescription = `${t("settings.cliPath.desc")} ${platformDesc}`;
    const cliPathSetting = new import_obsidian13.Setting(container).setName(`${t("settings.cliPath.name")} (${hostnameKey})`).setDesc(cliPathDescription);
    const validationEl = container.createDiv({ cls: "claudian-cli-path-validation" });
    validationEl.style.color = "var(--text-error)";
    validationEl.style.fontSize = "0.85em";
    validationEl.style.marginTop = "-0.5em";
    validationEl.style.marginBottom = "0.5em";
    validationEl.style.display = "none";
    const validatePath = (value) => {
      const trimmed = value.trim();
      if (!trimmed) return null;
      const expandedPath = expandHomePath(trimmed);
      if (!fs8.existsSync(expandedPath)) {
        return t("settings.cliPath.validation.notExist");
      }
      const stat = fs8.statSync(expandedPath);
      if (!stat.isFile()) {
        return t("settings.cliPath.validation.isDirectory");
      }
      return null;
    };
    const updateCliPathValidation = (value, inputEl) => {
      const error48 = validatePath(value);
      if (error48) {
        validationEl.setText(error48);
        validationEl.style.display = "block";
        if (inputEl) {
          inputEl.style.borderColor = "var(--text-error)";
        }
        return false;
      }
      validationEl.style.display = "none";
      if (inputEl) {
        inputEl.style.borderColor = "";
      }
      return true;
    };
    const currentValue = claudeSettings.cliPathsByHost[hostnameKey] || "";
    const cliPathsByHost = { ...claudeSettings.cliPathsByHost };
    let cliPathInputEl = null;
    const persistCliPath = async (value) => {
      var _a3;
      const isValid2 = updateCliPathValidation(value, cliPathInputEl != null ? cliPathInputEl : void 0);
      if (!isValid2) {
        return false;
      }
      const trimmed = value.trim();
      if (trimmed) {
        cliPathsByHost[hostnameKey] = trimmed;
      } else {
        delete cliPathsByHost[hostnameKey];
      }
      updateClaudeProviderSettings(settingsBag, { cliPathsByHost: { ...cliPathsByHost } });
      await context.plugin.saveSettings();
      claudeWorkspace.cliResolver.reset();
      const view = context.plugin.getView();
      await ((_a3 = view == null ? void 0 : view.getTabManager()) == null ? void 0 : _a3.broadcastToAllTabs(
        (service) => Promise.resolve(service.cleanup())
      ));
      return true;
    };
    cliPathSetting.addText((text) => {
      const placeholder = process.platform === "win32" ? "D:\\nodejs\\node_global\\node_modules\\@anthropic-ai\\claude-code\\cli.js" : "/usr/local/lib/node_modules/@anthropic-ai/claude-code/cli.js";
      text.setPlaceholder(placeholder).setValue(currentValue).onChange(async (value) => {
        await persistCliPath(value);
      });
      text.inputEl.addClass("claudian-settings-cli-path-input");
      text.inputEl.style.width = "100%";
      cliPathInputEl = text.inputEl;
      updateCliPathValidation(currentValue, text.inputEl);
    });
    new import_obsidian13.Setting(container).setName(t("settings.safety")).setHeading();
    new import_obsidian13.Setting(container).setName(t("settings.claudeSafeMode.name")).setDesc(t("settings.claudeSafeMode.desc")).addDropdown((dropdown) => {
      for (const mode of CLAUDE_SAFE_MODES) {
        dropdown.addOption(mode, mode);
      }
      dropdown.setValue(claudeSettings.safeMode).onChange(async (value) => {
        updateClaudeProviderSettings(
          settingsBag,
          { safeMode: value }
        );
        await context.plugin.saveSettings();
      });
    });
    new import_obsidian13.Setting(container).setName(t("settings.loadUserSettings.name")).setDesc(t("settings.loadUserSettings.desc")).addToggle(
      (toggle) => toggle.setValue(claudeSettings.loadUserSettings).onChange(async (value) => {
        updateClaudeProviderSettings(settingsBag, { loadUserSettings: value });
        await context.plugin.saveSettings();
      })
    );
    new import_obsidian13.Setting(container).setName(t("settings.models")).setHeading();
    new import_obsidian13.Setting(container).setName(t("settings.enableOpus1M.name")).setDesc(t("settings.enableOpus1M.desc")).addToggle(
      (toggle) => toggle.setValue(claudeSettings.enableOpus1M).onChange(async (value) => {
        updateClaudeProviderSettings(settingsBag, { enableOpus1M: value });
        context.plugin.normalizeModelVariantSettings();
        await context.plugin.saveSettings();
        context.refreshModelSelectors();
      })
    );
    new import_obsidian13.Setting(container).setName(t("settings.enableSonnet1M.name")).setDesc(t("settings.enableSonnet1M.desc")).addToggle(
      (toggle) => toggle.setValue(claudeSettings.enableSonnet1M).onChange(async (value) => {
        updateClaudeProviderSettings(settingsBag, { enableSonnet1M: value });
        context.plugin.normalizeModelVariantSettings();
        await context.plugin.saveSettings();
        context.refreshModelSelectors();
      })
    );
    new import_obsidian13.Setting(container).setName(t("settings.customModels.name")).setDesc(t("settings.customModels.desc")).addTextArea((text) => {
      let pendingCustomModels = claudeSettings.customModels;
      let savedCustomModels = claudeSettings.customModels;
      const commitCustomModels = async () => {
        const previousCustomModels = savedCustomModels;
        const previousModel = typeof settingsBag.model === "string" ? settingsBag.model : "";
        const previousTitleModel = typeof settingsBag.titleGenerationModel === "string" ? settingsBag.titleGenerationModel : "";
        if (pendingCustomModels !== savedCustomModels) {
          updateClaudeProviderSettings(settingsBag, { customModels: pendingCustomModels });
          savedCustomModels = pendingCustomModels;
        }
        reconcileActiveClaudeModelSelection();
        const didReconcileTitleModel = ProviderSettingsCoordinator.reconcileTitleGenerationModelSelection(settingsBag);
        const nextModel = typeof settingsBag.model === "string" ? settingsBag.model : "";
        const nextTitleModel = typeof settingsBag.titleGenerationModel === "string" ? settingsBag.titleGenerationModel : "";
        const didModelSelectionChange = previousModel !== nextModel;
        const didCustomModelsChange = previousCustomModels !== savedCustomModels;
        if (!didCustomModelsChange && !didModelSelectionChange && !didReconcileTitleModel && previousTitleModel === nextTitleModel) {
          return;
        }
        await context.plugin.saveSettings();
        context.refreshModelSelectors();
      };
      text.setPlaceholder(t("settings.customModels.placeholder")).setValue(claudeSettings.customModels).onChange((value) => {
        pendingCustomModels = value;
      });
      text.inputEl.rows = 6;
      text.inputEl.cols = 40;
      text.inputEl.addEventListener("blur", () => {
        void commitCustomModels();
      });
    });
    new import_obsidian13.Setting(container).setName(t("settings.slashCommands.name")).setHeading();
    const slashCommandsDesc = container.createDiv({ cls: "claudian-sp-settings-desc" });
    const descP = slashCommandsDesc.createEl("p", { cls: "setting-item-description" });
    descP.appendText(t("settings.slashCommands.desc") + " ");
    descP.createEl("a", {
      text: "Learn more",
      href: "https://code.claude.com/docs/en/skills"
    });
    const slashCommandsContainer = container.createDiv({ cls: "claudian-slash-commands-container" });
    new SlashCommandSettings(
      slashCommandsContainer,
      context.plugin.app,
      claudeWorkspace.commandCatalog
    );
    context.renderHiddenProviderCommandSetting(container, "claude", {
      name: t("settings.hiddenSlashCommands.name"),
      desc: t("settings.hiddenSlashCommands.desc"),
      placeholder: t("settings.hiddenSlashCommands.placeholder")
    });
    new import_obsidian13.Setting(container).setName(t("settings.subagents.name")).setHeading();
    const agentsDesc = container.createDiv({ cls: "claudian-sp-settings-desc" });
    agentsDesc.createEl("p", {
      text: t("settings.subagents.desc"),
      cls: "setting-item-description"
    });
    const agentsContainer = container.createDiv({ cls: "claudian-agents-container" });
    new AgentSettings(agentsContainer, {
      app: context.plugin.app,
      agentManager: claudeWorkspace.agentManager,
      agentStorage: claudeWorkspace.agentStorage
    });
    new import_obsidian13.Setting(container).setName(t("settings.mcpServers.name")).setHeading();
    const mcpDesc = container.createDiv({ cls: "claudian-mcp-settings-desc" });
    mcpDesc.createEl("p", {
      text: t("settings.mcpServers.desc"),
      cls: "setting-item-description"
    });
    const mcpContainer = container.createDiv({ cls: "claudian-mcp-container" });
    new McpSettingsManager(mcpContainer, {
      app: context.plugin.app,
      mcpStorage: claudeWorkspace.mcpStorage,
      broadcastMcpReload: async () => {
        var _a3;
        for (const view of context.plugin.getAllViews()) {
          await ((_a3 = view.getTabManager()) == null ? void 0 : _a3.broadcastToAllTabs(
            (service) => service.reloadMcpServers()
          ));
        }
      }
    });
    new import_obsidian13.Setting(container).setName(t("settings.plugins.name")).setHeading();
    const pluginsDesc = container.createDiv({ cls: "claudian-plugin-settings-desc" });
    pluginsDesc.createEl("p", {
      text: t("settings.plugins.desc"),
      cls: "setting-item-description"
    });
    const pluginsContainer = container.createDiv({ cls: "claudian-plugins-container" });
    new PluginSettingsManager(pluginsContainer, {
      pluginManager: claudeWorkspace.pluginManager,
      agentManager: claudeWorkspace.agentManager,
      restartTabs: async () => {
        const view = context.plugin.getView();
        const tabManager = view == null ? void 0 : view.getTabManager();
        if (!tabManager) {
          return;
        }
        await tabManager.broadcastToAllTabs(
          async (service) => {
            await service.ensureReady({ force: true });
          }
        );
      }
    });
    renderEnvironmentSettingsSection({
      container,
      plugin: context.plugin,
      scope: "provider:claude",
      heading: t("settings.environment"),
      name: t("settings.customVariables.name"),
      desc: "Claude-owned runtime variables only. Use this for ANTHROPIC_* and Claude-specific toggles.",
      placeholder: "ANTHROPIC_API_KEY=your-key\nANTHROPIC_BASE_URL=https://api.example.com\nANTHROPIC_MODEL=custom-model\nCLAUDE_CODE_USE_BEDROCK=1",
      renderCustomContextLimits: (target) => context.renderCustomContextLimits(target, "claude")
    });
    new import_obsidian13.Setting(container).setName(t("settings.experimental")).setHeading();
    new import_obsidian13.Setting(container).setName(t("settings.enableChrome.name")).setDesc(t("settings.enableChrome.desc")).addToggle(
      (toggle) => toggle.setValue(claudeSettings.enableChrome).onChange(async (value) => {
        updateClaudeProviderSettings(settingsBag, { enableChrome: value });
        await context.plugin.saveSettings();
      })
    );
    new import_obsidian13.Setting(container).setName(t("settings.enableBangBash.name")).setDesc(t("settings.enableBangBash.desc")).addToggle(
      (toggle) => toggle.setValue(claudeSettings.enableBangBash).onChange(async (value) => {
        bangBashValidationEl.style.display = "none";
        if (value) {
          const { findNodeExecutable: findNodeExecutable2, getEnhancedPath: getEnhancedPath2 } = await Promise.resolve().then(() => (init_env(), env_exports));
          const nodePath2 = findNodeExecutable2(getEnhancedPath2());
          if (!nodePath2) {
            bangBashValidationEl.setText(t("settings.enableBangBash.validation.noNode"));
            bangBashValidationEl.style.display = "block";
            toggle.setValue(false);
            return;
          }
        }
        updateClaudeProviderSettings(settingsBag, { enableBangBash: value });
        await context.plugin.saveSettings();
      })
    );
    const bangBashValidationEl = container.createDiv({ cls: "claudian-bang-bash-validation" });
    bangBashValidationEl.style.color = "var(--text-error)";
    bangBashValidationEl.style.fontSize = "0.85em";
    bangBashValidationEl.style.marginTop = "-0.5em";
    bangBashValidationEl.style.marginBottom = "0.5em";
    bangBashValidationEl.style.display = "none";
  }
};

// src/providers/claude/app/ClaudeWorkspaceServices.ts
async function createClaudeWorkspaceServices(plugin, adapter) {
  var _a3;
  const claudeStorage = new StorageService(plugin, adapter);
  await claudeStorage.ensureDirectories();
  const cliResolver = new ClaudeCliResolver();
  const mcpStorage = claudeStorage.mcp;
  const mcpManager = new McpServerManager(mcpStorage);
  await mcpManager.loadServers();
  const vaultPath = (_a3 = getVaultPath(plugin.app)) != null ? _a3 : "";
  const pluginManager = new PluginManager(vaultPath, claudeStorage.ccSettings);
  await pluginManager.loadPlugins();
  const agentStorage = claudeStorage.agents;
  const agentManager = new AgentManager(vaultPath, pluginManager);
  await agentManager.loadAgents();
  const commandCatalog = new ClaudeCommandCatalog(
    claudeStorage.commands,
    claudeStorage.skills,
    () => probeRuntimeCommands(plugin)
  );
  return {
    claudeStorage,
    cliResolver,
    mcpStorage,
    mcpServerManager: mcpManager,
    mcpManager,
    pluginManager,
    agentStorage,
    agentManager,
    commandCatalog,
    agentMentionProvider: agentManager,
    settingsTabRenderer: claudeSettingsTabRenderer,
    refreshAgentMentions: async () => {
      await agentManager.loadAgents();
    }
  };
}
var claudeWorkspaceRegistration = {
  initialize: async ({ plugin, vaultAdapter }) => createClaudeWorkspaceServices(plugin, vaultAdapter)
};
function getClaudeWorkspaceServices() {
  return ProviderWorkspaceRegistry.requireServices("claude");
}

// src/utils/context.ts
var CURRENT_NOTE_PREFIX_REGEX = /^<current_note>\n[\s\S]*?<\/current_note>\n\n/;
var CURRENT_NOTE_SUFFIX_REGEX = /\n\n<current_note>\n[\s\S]*?<\/current_note>$/;
var XML_CONTEXT_PATTERN = /\n\n<(?:current_note|editor_selection|editor_cursor|context_files|canvas_selection|browser_selection)[\s>]/;
function formatCurrentNote(notePath) {
  return `<current_note>
${notePath}
</current_note>`;
}
function appendCurrentNote(prompt, notePath) {
  return `${prompt}

${formatCurrentNote(notePath)}`;
}
function stripCurrentNoteContext(prompt) {
  const strippedPrefix = prompt.replace(CURRENT_NOTE_PREFIX_REGEX, "");
  if (strippedPrefix !== prompt) {
    return strippedPrefix;
  }
  return prompt.replace(CURRENT_NOTE_SUFFIX_REGEX, "");
}
function extractContentBeforeXmlContext(text) {
  if (!text) return void 0;
  const queryMatch = text.match(/<query>\n?([\s\S]*?)\n?<\/query>/);
  if (queryMatch) {
    return queryMatch[1].trim();
  }
  const xmlMatch = text.match(XML_CONTEXT_PATTERN);
  if ((xmlMatch == null ? void 0 : xmlMatch.index) !== void 0) {
    return text.substring(0, xmlMatch.index).trim();
  }
  return void 0;
}
function extractUserQuery(prompt) {
  if (!prompt) return "";
  const extracted = extractContentBeforeXmlContext(prompt);
  if (extracted !== void 0) {
    return extracted;
  }
  return prompt.replace(/<current_note>[\s\S]*?<\/current_note>\s*/g, "").replace(/<editor_selection[\s\S]*?<\/editor_selection>\s*/g, "").replace(/<editor_cursor[\s\S]*?<\/editor_cursor>\s*/g, "").replace(/<context_files>[\s\S]*?<\/context_files>\s*/g, "").replace(/<canvas_selection[\s\S]*?<\/canvas_selection>\s*/g, "").replace(/<browser_selection[\s\S]*?<\/browser_selection>\s*/g, "").trim();
}
function formatContextFilesLine(files) {
  return `<context_files>
${files.join(", ")}
</context_files>`;
}
function appendContextFiles(prompt, files) {
  return `${prompt}

${formatContextFilesLine(files)}`;
}

// src/utils/date.ts
function getTodayDate() {
  const now = /* @__PURE__ */ new Date();
  const readable = now.toLocaleDateString("en-US", {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric"
  });
  const iso = now.toISOString().split("T")[0];
  return `${readable} (${iso})`;
}
function formatDurationMmSs(seconds) {
  if (!Number.isFinite(seconds) || seconds < 0) {
    return "0s";
  }
  const mins = Math.floor(seconds / 60);
  const secs = seconds % 60;
  if (mins === 0) {
    return `${secs}s`;
  }
  return `${mins}m ${secs}s`;
}

// src/core/prompt/inlineEdit.ts
function parseInlineEditResponse(responseText) {
  const replacementMatch = responseText.match(/<replacement>([\s\S]*?)<\/replacement>/);
  if (replacementMatch) {
    return { success: true, editedText: replacementMatch[1] };
  }
  const insertionMatch = responseText.match(/<insertion>([\s\S]*?)<\/insertion>/);
  if (insertionMatch) {
    return { success: true, insertedText: insertionMatch[1] };
  }
  const trimmed = responseText.trim();
  if (trimmed) {
    return { success: true, clarification: trimmed };
  }
  return { success: false, error: "Empty response" };
}
function buildCursorPrompt(request) {
  const ctx = request.cursorContext;
  const lineAttr = ` line="${ctx.line + 1}"`;
  let cursorContent;
  if (ctx.isInbetween) {
    const parts = [];
    if (ctx.beforeCursor) parts.push(ctx.beforeCursor);
    parts.push("| #inbetween");
    if (ctx.afterCursor) parts.push(ctx.afterCursor);
    cursorContent = parts.join("\n");
  } else {
    cursorContent = `${ctx.beforeCursor}|${ctx.afterCursor} #inline`;
  }
  return [
    request.instruction,
    "",
    `<editor_cursor path="${request.notePath}"${lineAttr}>`,
    cursorContent,
    "</editor_cursor>"
  ].join("\n");
}
function buildInlineEditPrompt(request) {
  let prompt;
  if (request.mode === "cursor") {
    prompt = buildCursorPrompt(request);
  } else {
    const lineAttr = request.startLine && request.lineCount ? ` lines="${request.startLine}-${request.startLine + request.lineCount - 1}"` : "";
    prompt = [
      request.instruction,
      "",
      `<editor_selection path="${request.notePath}"${lineAttr}>`,
      request.selectedText,
      "</editor_selection>"
    ].join("\n");
  }
  if (request.contextFiles && request.contextFiles.length > 0) {
    prompt = appendContextFiles(prompt, request.contextFiles);
  }
  return prompt;
}
function getInlineEditSystemPrompt() {
  const pathRules = '- **Paths**: Must be RELATIVE to vault root (e.g., "notes/file.md").';
  return `Today is ${getTodayDate()}.

You are **Claudian**, an expert editor and writing assistant embedded in Obsidian. You help users refine their text, answer questions, and generate content with high precision.

## Core Directives

1.  **Style Matching**: Mimic the user's tone, voice, and formatting style (indentation, bullet points, capitalization).
2.  **Context Awareness**: Always Read the full file (or significant context) to understand the broader topic before editing. Do not rely solely on the selection.
3.  **Silent Execution**: Use tools (Read, WebSearch) silently. Your final output must be ONLY the result.
4.  **No Fluff**: No pleasantries, no "Here is the text", no "I have updated...". Just the content.

## Input Format

User messages have the instruction first, followed by XML context tags:

### Selection Mode
\`\`\`
user's instruction

<editor_selection path="path/to/file.md">
selected text here
</editor_selection>
\`\`\`
Use \`<replacement>\` tags for edits.

### Cursor Mode
\`\`\`
user's instruction

<editor_cursor path="path/to/file.md">
text before|text after #inline
</editor_cursor>
\`\`\`
Or between paragraphs:
\`\`\`
user's instruction

<editor_cursor path="path/to/file.md">
Previous paragraph
| #inbetween
Next paragraph
</editor_cursor>
\`\`\`
Use \`<insertion>\` tags to insert new content at the cursor position (\`|\`).

## Tools & Path Rules

- **Tools**: Read, Grep, Glob, LS, WebSearch, WebFetch. (All read-only).
${pathRules}

## Thinking Process

Before generating the final output, mentally check:
1.  **Context**: Have I read enough of the file to understand the *topic* and *structure*?
2.  **Style**: What is the user's indentation (2 vs 4 spaces, tabs)? What is their tone?
3.  **Type**: Is this **Prose** (flow, grammar, clarity) or **Code** (syntax, logic, variable names)?
    - *Prose*: Ensure smooth transitions.
    - *Code*: Preserve syntax validity; do not break surrounding brackets/indentation.

## Output Rules - CRITICAL

**ABSOLUTE RULE**: Your text output must contain ONLY the final answer, replacement, or insertion. NEVER output:
- "I'll read the file..." / "Let me check..." / "I will..."
- "I'm asked about..." / "The user wants..."
- "Based on my analysis..." / "After reading..."
- "Here's..." / "The answer is..."
- ANY announcement of what you're about to do or did

Use tools silently. Your text output = final result only.

### When Replacing Selected Text (Selection Mode)

If the user wants to MODIFY or REPLACE the selected text, wrap the replacement in <replacement> tags:

<replacement>your replacement text here</replacement>

The content inside the tags should be ONLY the replacement text - no explanation.

### When Inserting at Cursor (Cursor Mode)

If the user wants to INSERT new content at the cursor position, wrap the insertion in <insertion> tags:

<insertion>your inserted text here</insertion>

The content inside the tags should be ONLY the text to insert - no explanation.

### When Answering Questions or Providing Information

If the user is asking a QUESTION, respond WITHOUT tags. Output the answer directly.

WRONG: "I'll read the full context of this file to give you a better explanation. This is a guide about..."
CORRECT: "This is a guide about..."

### When Clarification is Needed

If the request is ambiguous, ask a clarifying question. Keep questions concise and specific.

## Examples

### Selection Mode
Input:
\`\`\`
translate to French

<editor_selection path="notes/readme.md">
Hello world
</editor_selection>
\`\`\`

CORRECT (replacement):
<replacement>Bonjour le monde</replacement>

Input:
\`\`\`
what does this do?

<editor_selection path="notes/code.md">
const x = arr.reduce((a, b) => a + b, 0);
</editor_selection>
\`\`\`

CORRECT (question - no tags):
This code sums all numbers in the array \`arr\`. It uses \`reduce\` to iterate through the array, accumulating the total starting from 0.

### Cursor Mode

Input:
\`\`\`
what animal?

<editor_cursor path="notes/draft.md">
The quick brown | jumps over the lazy dog. #inline
</editor_cursor>
\`\`\`

CORRECT (insertion):
<insertion>fox</insertion>

### Q&A
Input:
\`\`\`
add a brief description section

<editor_cursor path="notes/readme.md">
# Introduction
This is my project.
| #inbetween
## Features
</editor_cursor>
\`\`\`

CORRECT (insertion):
<insertion>
## Description

This project provides tools for managing your notes efficiently.
</insertion>

Input:
\`\`\`
translate to Spanish

<editor_selection path="notes/draft.md">
The bank was steep.
</editor_selection>
\`\`\`

CORRECT (asking for clarification):
"Bank" can mean a financial institution (banco) or a river bank (orilla). Which meaning should I use?

Then after user clarifies "river bank":
<replacement>La orilla era empinada.</replacement>`;
}

// src/core/tools/toolNames.ts
var TOOL_AGENT_OUTPUT = "TaskOutput";
var TOOL_ASK_USER_QUESTION = "AskUserQuestion";
var TOOL_BASH = "Bash";
var TOOL_BASH_OUTPUT = "BashOutput";
var TOOL_EDIT = "Edit";
var TOOL_GLOB = "Glob";
var TOOL_GREP = "Grep";
var TOOL_KILL_SHELL = "KillShell";
var TOOL_LS = "LS";
var TOOL_LIST_MCP_RESOURCES = "ListMcpResources";
var TOOL_MCP = "Mcp";
var TOOL_NOTEBOOK_EDIT = "NotebookEdit";
var TOOL_READ = "Read";
var TOOL_READ_MCP_RESOURCE = "ReadMcpResource";
var TOOL_SKILL = "Skill";
var TOOL_SUBAGENT = "Agent";
var TOOL_SUBAGENT_LEGACY = "Task";
var TOOL_TASK = TOOL_SUBAGENT;
var TOOL_TODO_WRITE = "TodoWrite";
var TOOL_TOOL_SEARCH = "ToolSearch";
var TOOL_WEB_FETCH = "WebFetch";
var TOOL_WEB_SEARCH = "WebSearch";
var TOOL_WRITE = "Write";
var TOOL_ENTER_PLAN_MODE = "EnterPlanMode";
var TOOL_EXIT_PLAN_MODE = "ExitPlanMode";
var TOOL_APPLY_PATCH = "apply_patch";
var TOOL_WRITE_STDIN = "write_stdin";
var TOOL_SPAWN_AGENT = "spawn_agent";
var TOOL_SEND_INPUT = "send_input";
var TOOL_WAIT = "wait";
var TOOL_WAIT_AGENT = "wait_agent";
var TOOL_RESUME_AGENT = "resume_agent";
var TOOL_CLOSE_AGENT = "close_agent";
var AGENT_LIFECYCLE_TOOLS = [
  TOOL_SPAWN_AGENT,
  TOOL_SEND_INPUT,
  TOOL_WAIT,
  TOOL_WAIT_AGENT,
  TOOL_RESUME_AGENT,
  TOOL_CLOSE_AGENT
];
function isAgentLifecycleTool(name) {
  return AGENT_LIFECYCLE_TOOLS.includes(name);
}
var TOOLS_SKIP_BLOCKED_DETECTION = [
  TOOL_ENTER_PLAN_MODE,
  TOOL_EXIT_PLAN_MODE,
  TOOL_ASK_USER_QUESTION
];
var SUBAGENT_TOOL_NAMES = [
  TOOL_SUBAGENT,
  TOOL_SUBAGENT_LEGACY
];
function skipsBlockedDetection(name) {
  return TOOLS_SKIP_BLOCKED_DETECTION.includes(name);
}
function isSubagentToolName(name) {
  return SUBAGENT_TOOL_NAMES.includes(name);
}
var EDIT_TOOLS = [TOOL_WRITE, TOOL_EDIT, TOOL_NOTEBOOK_EDIT];
var WRITE_EDIT_TOOLS = [TOOL_WRITE, TOOL_EDIT];
var READ_ONLY_TOOLS = [
  TOOL_READ,
  TOOL_GREP,
  TOOL_GLOB,
  TOOL_LS,
  TOOL_WEB_SEARCH,
  TOOL_WEB_FETCH
];
function isEditTool(toolName) {
  return EDIT_TOOLS.includes(toolName);
}
function isWriteEditTool(toolName) {
  return WRITE_EDIT_TOOLS.includes(toolName);
}
function isReadOnlyTool(toolName) {
  return READ_ONLY_TOOLS.includes(toolName);
}

// src/providers/claude/runtime/claudeColdStartQuery.ts
init_env();
init_path();

// src/providers/claude/auxiliary/extractAssistantText.ts
function extractAssistantText(message) {
  var _a3;
  const content = (_a3 = message.message) == null ? void 0 : _a3.content;
  if (message.type !== "assistant" || !Array.isArray(content)) {
    return "";
  }
  return content.filter(
    (block) => !!block && typeof block === "object" && "type" in block && "text" in block && block.type === "text" && typeof block.text === "string"
  ).map((block) => block.text).join("");
}

// src/providers/claude/runtime/claudeColdStartQuery.ts
async function runColdStartQuery(config2, prompt) {
  var _a3, _b2, _c, _d2, _e;
  const vaultPath = getVaultPath(config2.plugin.app);
  if (!vaultPath) {
    throw new Error("Could not determine vault path");
  }
  const resolvedClaudePath = config2.plugin.getResolvedProviderCliPath("claude");
  if (!resolvedClaudePath) {
    throw new Error("Claude CLI not found");
  }
  const customEnv = parseEnvironmentVariables(
    config2.plugin.getActiveEnvironmentVariables("claude")
  );
  const enhancedPath = getEnhancedPath(customEnv.PATH, resolvedClaudePath);
  const missingNodeError = getMissingNodeError(resolvedClaudePath, enhancedPath);
  if (missingNodeError) {
    throw new Error(missingNodeError);
  }
  const settings11 = (_a3 = config2.providerSettings) != null ? _a3 : ProviderSettingsCoordinator.getProviderSettingsSnapshot(
    config2.plugin.settings,
    "claude"
  );
  const claudeSettings = getClaudeProviderSettings(settings11);
  const selectedModel = (_b2 = config2.model) != null ? _b2 : settings11.model;
  const options = {
    cwd: vaultPath,
    systemPrompt: config2.systemPrompt,
    model: selectedModel,
    abortController: config2.abortController,
    pathToClaudeCodeExecutable: resolvedClaudePath,
    env: {
      ...process.env,
      ...customEnv,
      PATH: enhancedPath
    },
    permissionMode: "bypassPermissions",
    allowDangerouslySkipPermissions: true,
    settingSources: claudeSettings.loadUserSettings ? ["user", "project"] : ["project"],
    spawnClaudeCodeProcess: createCustomSpawnFunction(enhancedPath)
  };
  if (config2.tools !== void 0) {
    options.tools = config2.tools;
  }
  if (config2.hooks) {
    options.hooks = config2.hooks;
  }
  if (config2.persistSession === false) {
    options.persistSession = false;
  }
  if (config2.resumeSessionId) {
    options.resume = config2.resumeSessionId;
  }
  if (claudeSettings.safeMode === "auto") {
    options.extraArgs = { ...options.extraArgs, "enable-auto-mode": null };
  }
  if (!((_c = config2.thinking) == null ? void 0 : _c.disabled)) {
    const effortLevel = resolveAdaptiveEffortLevel(selectedModel, settings11.effortLevel);
    if (effortLevel !== null) {
      options.thinking = { type: "adaptive" };
      options.effort = effortLevel;
    } else {
      const thinkingTokens = resolveThinkingTokens(selectedModel, settings11.thinkingBudget);
      if (thinkingTokens !== null) {
        options.maxThinkingTokens = thinkingTokens;
      }
    }
  }
  const response = E$$({ prompt, options });
  let responseText = "";
  let sessionId = null;
  for await (const message of response) {
    if ((_d2 = config2.abortController) == null ? void 0 : _d2.signal.aborted) {
      await response.interrupt();
      throw new Error("Cancelled");
    }
    if (message.type === "system" && message.subtype === "init" && message.session_id) {
      sessionId = message.session_id;
    }
    const text = extractAssistantText(message);
    if (text) {
      responseText += text;
      (_e = config2.onTextChunk) == null ? void 0 : _e.call(config2, responseText);
    }
  }
  return { text: responseText, sessionId };
}

// src/providers/claude/auxiliary/ClaudeInlineEditService.ts
function createReadOnlyHook() {
  return {
    hooks: [
      async (hookInput) => {
        const input = hookInput;
        const toolName = input.tool_name;
        if (isReadOnlyTool(toolName)) {
          return { continue: true };
        }
        return {
          continue: false,
          hookSpecificOutput: {
            hookEventName: "PreToolUse",
            permissionDecision: "deny",
            permissionDecisionReason: `Inline edit mode: tool "${toolName}" is not allowed (read-only)`
          }
        };
      }
    ]
  };
}
var InlineEditService = class {
  constructor(plugin) {
    this.abortController = null;
    this.sessionId = null;
    this.plugin = plugin;
  }
  getScopedSettings() {
    return ProviderSettingsCoordinator.getProviderSettingsSnapshot(
      this.plugin.settings,
      "claude"
    );
  }
  resetConversation() {
    this.sessionId = null;
  }
  async editText(request) {
    this.sessionId = null;
    const prompt = buildInlineEditPrompt(request);
    return this.sendMessage(prompt);
  }
  async continueConversation(message, contextFiles) {
    if (!this.sessionId) {
      return { success: false, error: "No active conversation to continue" };
    }
    let prompt = message;
    if (contextFiles && contextFiles.length > 0) {
      prompt = appendContextFiles(message, contextFiles);
    }
    return this.sendMessage(prompt);
  }
  async sendMessage(prompt) {
    var _a3;
    const settings11 = this.getScopedSettings();
    this.abortController = new AbortController();
    const hooks = {
      PreToolUse: [createReadOnlyHook()]
    };
    try {
      const result = await runColdStartQuery({
        plugin: this.plugin,
        systemPrompt: getInlineEditSystemPrompt(),
        tools: [...READ_ONLY_TOOLS],
        hooks,
        resumeSessionId: (_a3 = this.sessionId) != null ? _a3 : void 0,
        abortController: this.abortController,
        providerSettings: settings11
      }, prompt);
      this.sessionId = result.sessionId;
      return parseInlineEditResponse(result.text);
    } catch (error48) {
      const msg = error48 instanceof Error ? error48.message : "Unknown error";
      return { success: false, error: msg };
    } finally {
      this.abortController = null;
    }
  }
  cancel() {
    if (this.abortController) {
      this.abortController.abort();
    }
  }
};

// src/core/prompt/instructionRefine.ts
function buildRefineSystemPrompt(existingInstructions) {
  const existingSection = existingInstructions.trim() ? `

EXISTING INSTRUCTIONS (already in the user's system prompt):
\`\`\`
${existingInstructions.trim()}
\`\`\`

When refining the new instruction:
- Consider how it fits with existing instructions
- Avoid duplicating existing instructions
- If the new instruction conflicts with an existing one, refine it to be complementary or note the conflict
- Match the format of existing instructions (section, heading, bullet points, style, etc.)` : "";
  return `You are an expert Prompt Engineer. You help users craft precise, effective system instructions for their AI assistant.

**Your Goal**: Transform vague or simple user requests into **high-quality, actionable, and non-conflicting** system prompt instructions.

**Process**:
1.  **Analyze Intent**: What behavior does the user want to enforce or change?
2.  **Check Context**: Does this conflict with existing instructions?
    - *No Conflict*: Add as new.
    - *Conflict*: Propose a **merged instruction** that resolves the contradiction (or ask if unsure).
3.  **Refine**: Draft a clear, positive instruction (e.g., "Do X" instead of "Don't do Y").
4.  **Format**: Return *only* the Markdown snippet wrapped in \`<instruction>\` tags.

**Guidelines**:
- **Clarity**: Use precise language. Avoid ambiguity.
- **Scope**: Keep it focused. Don't add unrelated rules.
- **Format**: Valid Markdown (bullets \`-\` or sections \`##\`).
- **No Header**: Do NOT include a top-level header like \`# Custom Instructions\`.
- **Conflict Handling**: If the new rule directly contradicts an existing one, rewrite the *new* one to override specific cases or ask for clarification.

**Output Format**:
- **Success**: \`<instruction>...markdown content...</instruction>\`
- **Ambiguity**: Plain text question.

${existingSection}

**Examples**:

Input: "typescript for code"
Output: <instruction>- **Code Language**: Always use TypeScript for code examples. Include proper type annotations and interfaces.</instruction>

Input: "be concise"
Output: <instruction>- **Conciseness**: Provide brief, direct responses. Omit conversational filler and unnecessary explanations.</instruction>

Input: "organize coding style rules"
Output: <instruction>## Coding Standards

- **Language**: Use TypeScript.
- **Style**: Prefer functional patterns.
- **Review**: Keep diffs small.</instruction>

Input: "use that thing from before"
Output: I'm not sure what you're referring to. Could you please clarify?`;
}
function parseInstructionRefineResponse(responseText) {
  const instructionMatch = responseText.match(/<instruction>([\s\S]*?)<\/instruction>/);
  if (instructionMatch) {
    return { success: true, refinedInstruction: instructionMatch[1].trim() };
  }
  const trimmed = responseText.trim();
  if (trimmed) {
    return { success: true, clarification: trimmed };
  }
  return { success: false, error: "Empty response" };
}

// src/providers/claude/auxiliary/ClaudeInstructionRefineService.ts
var InstructionRefineService = class {
  constructor(plugin) {
    this.abortController = null;
    this.sessionId = null;
    this.existingInstructions = "";
    this.plugin = plugin;
  }
  resetConversation() {
    this.sessionId = null;
  }
  async refineInstruction(rawInstruction, existingInstructions, onProgress) {
    this.sessionId = null;
    this.existingInstructions = existingInstructions;
    const prompt = `Please refine this instruction: "${rawInstruction}"`;
    return this.sendMessage(prompt, onProgress);
  }
  async continueConversation(message, onProgress) {
    if (!this.sessionId) {
      return { success: false, error: "No active conversation to continue" };
    }
    return this.sendMessage(message, onProgress);
  }
  cancel() {
    if (this.abortController) {
      this.abortController.abort();
      this.abortController = null;
    }
  }
  async sendMessage(prompt, onProgress) {
    var _a3;
    this.abortController = new AbortController();
    try {
      const result = await runColdStartQuery({
        plugin: this.plugin,
        systemPrompt: buildRefineSystemPrompt(this.existingInstructions),
        tools: [],
        resumeSessionId: (_a3 = this.sessionId) != null ? _a3 : void 0,
        abortController: this.abortController,
        onTextChunk: onProgress ? (accumulatedText) => onProgress(this.parseResponse(accumulatedText)) : void 0
      }, prompt);
      this.sessionId = result.sessionId;
      return this.parseResponse(result.text);
    } catch (error48) {
      const msg = error48 instanceof Error ? error48.message : "Unknown error";
      return { success: false, error: msg };
    } finally {
      this.abortController = null;
    }
  }
  parseResponse(responseText) {
    const instructionMatch = responseText.match(/<instruction>([\s\S]*?)<\/instruction>/);
    if (instructionMatch) {
      return { success: true, refinedInstruction: instructionMatch[1].trim() };
    }
    const trimmed = responseText.trim();
    if (trimmed) {
      return { success: true, clarification: trimmed };
    }
    return { success: false, error: "Empty response" };
  }
};

// src/core/prompt/titleGeneration.ts
var MAX_TITLE_INPUT_LENGTH = 500;
var MAX_TITLE_LENGTH = 50;
var TITLE_GENERATION_SYSTEM_PROMPT = `You are a specialist in summarizing user intent.

**Task**: Generate a **concise, descriptive title** (max 50 chars) summarizing the user's task/request.

**Rules**:
1.  **Format**: Sentence case. No periods/quotes.
2.  **Structure**: Start with a **strong verb** (e.g., Create, Fix, Debug, Explain, Analyze).
3.  **Forbidden**: "Conversation with...", "Help me...", "Question about...", "I need...".
4.  **Tech Context**: Detect and include the primary language/framework if code is present (e.g., "Debug Python script", "Refactor React hook").

**Output**: Return ONLY the raw title text.`;
function buildTitleGenerationPrompt(userMessage) {
  const truncated = userMessage.length > MAX_TITLE_INPUT_LENGTH ? `${userMessage.slice(0, MAX_TITLE_INPUT_LENGTH)}...` : userMessage;
  return `User's request:
"""
${truncated}
"""

Generate a title for this conversation:`;
}
function parseTitleGenerationResponse(responseText) {
  const trimmed = responseText.trim();
  if (!trimmed) {
    return null;
  }
  let title = trimmed;
  if (title.startsWith('"') && title.endsWith('"') || title.startsWith("'") && title.endsWith("'")) {
    title = title.slice(1, -1);
  }
  title = title.replace(/[.!?:;,]+$/, "");
  if (title.length > MAX_TITLE_LENGTH) {
    title = `${title.slice(0, MAX_TITLE_LENGTH - 3)}...`;
  }
  return title || null;
}

// src/providers/claude/auxiliary/ClaudeTitleGenerationService.ts
init_env();
var TitleGenerationService = class {
  constructor(plugin) {
    this.activeGenerations = /* @__PURE__ */ new Map();
    this.plugin = plugin;
  }
  async generateTitle(conversationId, userMessage, callback) {
    const existingController = this.activeGenerations.get(conversationId);
    if (existingController) {
      existingController.abort();
    }
    const abortController = new AbortController();
    this.activeGenerations.set(conversationId, abortController);
    const truncatedUser = this.truncateText(userMessage, 500);
    const prompt = `User's request:
"""
${truncatedUser}
"""

Generate a title for this conversation:`;
    try {
      const result = await runColdStartQuery({
        plugin: this.plugin,
        systemPrompt: TITLE_GENERATION_SYSTEM_PROMPT,
        tools: [],
        model: this.resolveTitleModel(),
        thinking: { disabled: true },
        persistSession: false,
        abortController
      }, prompt);
      const title = this.parseTitle(result.text);
      if (title) {
        await this.safeCallback(callback, conversationId, { success: true, title });
      } else {
        await this.safeCallback(callback, conversationId, {
          success: false,
          error: "Failed to parse title from response"
        });
      }
    } catch (error48) {
      const msg = error48 instanceof Error ? error48.message : "Unknown error";
      await this.safeCallback(callback, conversationId, { success: false, error: msg });
    } finally {
      this.activeGenerations.delete(conversationId);
    }
  }
  cancel() {
    for (const controller of this.activeGenerations.values()) {
      controller.abort();
    }
    this.activeGenerations.clear();
  }
  resolveTitleModel() {
    const envVars = parseEnvironmentVariables(
      this.plugin.getActiveEnvironmentVariables("claude")
    );
    return this.plugin.settings.titleGenerationModel || envVars.ANTHROPIC_DEFAULT_HAIKU_MODEL || "claude-haiku-4-5";
  }
  truncateText(text, maxLength) {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + "...";
  }
  parseTitle(responseText) {
    const trimmed = responseText.trim();
    if (!trimmed) return null;
    let title = trimmed;
    if (title.startsWith('"') && title.endsWith('"') || title.startsWith("'") && title.endsWith("'")) {
      title = title.slice(1, -1);
    }
    title = title.replace(/[.!?:;,]+$/, "");
    if (title.length > 50) {
      title = title.substring(0, 47) + "...";
    }
    return title || null;
  }
  async safeCallback(callback, conversationId, result) {
    try {
      await callback(conversationId, result);
    } catch (e2) {
    }
  }
};

// src/providers/claude/capabilities.ts
var CLAUDE_PROVIDER_CAPABILITIES = Object.freeze({
  providerId: "claude",
  supportsPersistentRuntime: true,
  supportsNativeHistory: true,
  supportsPlanMode: true,
  supportsRewind: true,
  supportsFork: true,
  supportsProviderCommands: true,
  supportsImageAttachments: true,
  supportsInstructionMode: true,
  supportsMcpTools: true,
  supportsTurnSteer: false,
  reasoningControl: "effort",
  planPathPrefix: "/.claude/plans/"
});

// src/providers/claude/env/ClaudeSettingsReconciler.ts
init_env();
var ENV_HASH_MODEL_KEYS = [
  "ANTHROPIC_MODEL",
  "ANTHROPIC_DEFAULT_OPUS_MODEL",
  "ANTHROPIC_DEFAULT_SONNET_MODEL",
  "ANTHROPIC_DEFAULT_HAIKU_MODEL"
];
var ENV_HASH_PROVIDER_KEYS = ["ANTHROPIC_BASE_URL"];
function computeEnvHash(envText) {
  const envVars = parseEnvironmentVariables(envText || "");
  const allKeys = [...ENV_HASH_MODEL_KEYS, ...ENV_HASH_PROVIDER_KEYS];
  return allKeys.filter((key) => envVars[key]).map((key) => `${key}=${envVars[key]}`).sort().join("|");
}
var claudeSettingsReconciler = {
  reconcileModelWithEnvironment(settings11, conversations) {
    const envText = getRuntimeEnvironmentText(settings11, "claude");
    const currentHash = computeEnvHash(envText);
    const savedHash = getClaudeProviderSettings(settings11).environmentHash;
    if (currentHash === savedHash) {
      return { changed: false, invalidatedConversations: [] };
    }
    const invalidatedConversations = [];
    for (const conv of conversations) {
      if (conv.sessionId) {
        conv.sessionId = null;
        invalidatedConversations.push(conv);
      }
    }
    const currentModel = typeof settings11.model === "string" ? settings11.model : "";
    const nextModel = resolveClaudeModelSelection(settings11, currentModel);
    if (nextModel) {
      settings11.model = nextModel;
    }
    updateClaudeProviderSettings(settings11, { environmentHash: currentHash });
    return { changed: true, invalidatedConversations };
  },
  normalizeModelVariantSettings(settings11) {
    const claudeSettings = getClaudeProviderSettings(settings11);
    let changed = false;
    const normalize3 = (model2) => normalizeVisibleModelVariant(
      model2,
      claudeSettings.enableOpus1M,
      claudeSettings.enableSonnet1M
    );
    const model = settings11.model;
    const normalizedModel = normalize3(model);
    if (model !== normalizedModel) {
      settings11.model = normalizedModel;
      changed = true;
    }
    const titleModel = settings11.titleGenerationModel;
    if (titleModel) {
      const normalizedTitleModel = normalize3(titleModel);
      if (titleModel !== normalizedTitleModel) {
        settings11.titleGenerationModel = normalizedTitleModel;
        changed = true;
      }
    }
    const lastClaudeModel = claudeSettings.lastModel;
    if (lastClaudeModel) {
      const normalizedLastClaudeModel = normalize3(lastClaudeModel);
      if (lastClaudeModel !== normalizedLastClaudeModel) {
        updateClaudeProviderSettings(settings11, { lastModel: normalizedLastClaudeModel });
        changed = true;
      }
    }
    return changed;
  }
};

// src/providers/claude/types/providerState.ts
function getClaudeState(providerState) {
  return providerState != null ? providerState : {};
}

// src/providers/claude/history/sdkAsyncSubagent.ts
function extractAgentIdFromToolUseResult(toolUseResult) {
  var _a3, _b2;
  if (!toolUseResult || typeof toolUseResult !== "object") {
    return null;
  }
  const record2 = toolUseResult;
  const directAgentId = (_a3 = record2.agentId) != null ? _a3 : record2.agent_id;
  if (typeof directAgentId === "string" && directAgentId.length > 0) {
    return directAgentId;
  }
  const data = record2.data;
  if (data && typeof data === "object") {
    const nested = data;
    const nestedAgentId = (_b2 = nested.agent_id) != null ? _b2 : nested.agentId;
    if (typeof nestedAgentId === "string" && nestedAgentId.length > 0) {
      return nestedAgentId;
    }
  }
  return null;
}
function resolveToolUseResultStatus(toolUseResult, fallbackStatus) {
  var _a3;
  if (!toolUseResult || typeof toolUseResult !== "object") {
    return fallbackStatus;
  }
  const record2 = toolUseResult;
  const rawStatus = (_a3 = record2.retrieval_status) != null ? _a3 : record2.status;
  const status = typeof rawStatus === "string" ? rawStatus.toLowerCase() : "";
  if (status === "error") {
    return "error";
  }
  if (status === "completed" || status === "success") {
    return "completed";
  }
  if (record2.isAsync === true || status === "async_launched") {
    return "running";
  }
  return fallbackStatus;
}
function buildAsyncSubagentInfo(toolCall, toolUseResult, asyncResults) {
  var _a3, _b2, _c;
  const agentId = extractAgentIdFromToolUseResult(toolUseResult);
  if (!agentId) {
    return null;
  }
  const queueResult = asyncResults.get(agentId);
  const description = ((_a3 = toolCall.input) == null ? void 0 : _a3.description) || "Background task";
  const prompt = ((_b2 = toolCall.input) == null ? void 0 : _b2.prompt) || "";
  const finalResult = (_c = queueResult == null ? void 0 : queueResult.result) != null ? _c : toolCall.result;
  let toolCallFallback = "running";
  if (toolCall.status === "error") {
    toolCallFallback = "error";
  } else if (toolCall.status === "completed") {
    toolCallFallback = "completed";
  }
  const status = queueResult ? resolveToolUseResultStatus({ status: queueResult.status }, "completed") : resolveToolUseResultStatus(toolUseResult, toolCallFallback);
  const taskStatus = status === "orphaned" ? "error" : status;
  return {
    id: toolCall.id,
    description,
    prompt,
    mode: "async",
    isExpanded: false,
    status: taskStatus,
    toolCalls: [],
    asyncStatus: status,
    agentId,
    result: finalResult
  };
}

// src/providers/claude/history/sdkBranchFilter.ts
function filterActiveBranch(entries, resumeAtMessageId) {
  var _a3, _b2;
  if (entries.length === 0) {
    return [];
  }
  function isRealUserBranchChild(entry) {
    return !!entry && entry.type === "user" && !("toolUseResult" in entry) && !entry.isMeta && !("sourceToolUseID" in entry);
  }
  function isDirectRealUserBranchChild(parentUuid, entry) {
    return !!entry && entry.parentUuid === parentUuid && isRealUserBranchChild(entry);
  }
  const seen = /* @__PURE__ */ new Set();
  const deduped = [];
  for (const entry of entries) {
    if (entry.uuid) {
      if (seen.has(entry.uuid)) {
        continue;
      }
      seen.add(entry.uuid);
    }
    deduped.push(entry);
  }
  const progressUuids = /* @__PURE__ */ new Set();
  const progressParentOf = /* @__PURE__ */ new Map();
  for (const entry of deduped) {
    if (entry.type === "progress" && entry.uuid) {
      progressUuids.add(entry.uuid);
      progressParentOf.set(entry.uuid, (_a3 = entry.parentUuid) != null ? _a3 : null);
    }
  }
  function resolveParent(parentUuid) {
    var _a4;
    if (!parentUuid) {
      return parentUuid;
    }
    let current2 = parentUuid;
    let guard = progressUuids.size + 1;
    while (current2 && progressUuids.has(current2)) {
      if (--guard < 0) {
        break;
      }
      current2 = (_a4 = progressParentOf.get(current2)) != null ? _a4 : null;
    }
    return current2;
  }
  const conversationEntries = deduped.filter((entry) => entry.type !== "progress");
  const byUuid = /* @__PURE__ */ new Map();
  const childrenOf = /* @__PURE__ */ new Map();
  for (const entry of conversationEntries) {
    if (entry.uuid) {
      byUuid.set(entry.uuid, entry);
    }
    const effectiveParent = (_b2 = resolveParent(entry.parentUuid)) != null ? _b2 : null;
    if (effectiveParent && entry.uuid) {
      let children = childrenOf.get(effectiveParent);
      if (!children) {
        children = /* @__PURE__ */ new Set();
        childrenOf.set(effectiveParent, children);
      }
      children.add(entry.uuid);
    }
  }
  function findLatestLeaf() {
    for (let i2 = conversationEntries.length - 1; i2 >= 0; i2--) {
      const uuid3 = conversationEntries[i2].uuid;
      if (uuid3 && !childrenOf.has(uuid3)) {
        return conversationEntries[i2];
      }
    }
    return void 0;
  }
  const latestLeaf = findLatestLeaf();
  const latestBranchUuids = /* @__PURE__ */ new Set();
  const activeChildOf = /* @__PURE__ */ new Map();
  let latestCurrent = latestLeaf;
  while (latestCurrent == null ? void 0 : latestCurrent.uuid) {
    latestBranchUuids.add(latestCurrent.uuid);
    const parent = resolveParent(latestCurrent.parentUuid);
    if (parent) {
      activeChildOf.set(parent, latestCurrent.uuid);
    }
    latestCurrent = parent ? byUuid.get(parent) : void 0;
  }
  const conversationContentCache = /* @__PURE__ */ new Map();
  function hasConversationContent(uuid3) {
    const cached2 = conversationContentCache.get(uuid3);
    if (cached2 !== void 0) {
      return cached2;
    }
    const entry = byUuid.get(uuid3);
    let result = false;
    if ((entry == null ? void 0 : entry.type) === "assistant") {
      result = true;
    } else if ((entry == null ? void 0 : entry.type) === "user" && !entry.isMeta && !("sourceToolUseID" in entry)) {
      result = true;
    } else {
      const children = childrenOf.get(uuid3);
      if (children) {
        for (const childUuid of children) {
          if (hasConversationContent(childUuid)) {
            result = true;
            break;
          }
        }
      }
    }
    conversationContentCache.set(uuid3, result);
    return result;
  }
  const hasBranching = [...latestBranchUuids].some((uuid3) => {
    const children = childrenOf.get(uuid3);
    if (!children || children.size <= 1) {
      return false;
    }
    const activeChildUuid = activeChildOf.get(uuid3);
    let sawRealUserChild = false;
    let sawAlternateConversationChild = false;
    for (const childUuid of children) {
      const child = byUuid.get(childUuid);
      if (isDirectRealUserBranchChild(uuid3, child)) {
        sawRealUserChild = true;
      }
      if (childUuid !== activeChildUuid && hasConversationContent(childUuid)) {
        sawAlternateConversationChild = true;
      }
      if (sawRealUserChild && sawAlternateConversationChild) {
        return true;
      }
    }
    return false;
  });
  let leaf;
  if (hasBranching) {
    leaf = latestLeaf;
    if (resumeAtMessageId && (leaf == null ? void 0 : leaf.uuid) && byUuid.has(resumeAtMessageId)) {
      let current2 = leaf;
      while (current2 == null ? void 0 : current2.uuid) {
        if (current2.uuid === resumeAtMessageId) {
          leaf = current2;
          break;
        }
        const parent = resolveParent(current2.parentUuid);
        current2 = parent ? byUuid.get(parent) : void 0;
      }
    }
  } else if (resumeAtMessageId) {
    leaf = byUuid.get(resumeAtMessageId);
  } else {
    return conversationEntries;
  }
  if (!(leaf == null ? void 0 : leaf.uuid)) {
    return conversationEntries;
  }
  const activeUuids = /* @__PURE__ */ new Set();
  let current = leaf;
  while (current == null ? void 0 : current.uuid) {
    activeUuids.add(current.uuid);
    const parent = resolveParent(current.parentUuid);
    current = parent ? byUuid.get(parent) : void 0;
  }
  if (hasBranching) {
    const ancestorUuids = [...activeUuids];
    const pending = [];
    for (const uuid3 of ancestorUuids) {
      const children = childrenOf.get(uuid3);
      if (!children || children.size <= 1) {
        continue;
      }
      const activeChildUuid = activeChildOf.get(uuid3);
      if (activeChildUuid && isDirectRealUserBranchChild(uuid3, byUuid.get(activeChildUuid))) {
        continue;
      }
      for (const childUuid of children) {
        if (activeUuids.has(childUuid)) {
          continue;
        }
        const child = byUuid.get(childUuid);
        if (!child || isRealUserBranchChild(child)) {
          continue;
        }
        activeUuids.add(childUuid);
        pending.push(childUuid);
      }
    }
    while (pending.length > 0) {
      const parentUuid = pending.pop();
      const children = childrenOf.get(parentUuid);
      if (!children) {
        continue;
      }
      for (const childUuid of children) {
        if (activeUuids.has(childUuid)) {
          continue;
        }
        const child = byUuid.get(childUuid);
        if (!child || isRealUserBranchChild(child)) {
          continue;
        }
        activeUuids.add(childUuid);
        pending.push(childUuid);
      }
    }
  }
  const entryCount = conversationEntries.length;
  const prevIsActive = new Array(entryCount);
  const nextIsActive = new Array(entryCount);
  let lastPrevActive = false;
  for (let i2 = 0; i2 < entryCount; i2++) {
    if (conversationEntries[i2].uuid) {
      lastPrevActive = activeUuids.has(conversationEntries[i2].uuid);
    }
    prevIsActive[i2] = lastPrevActive;
  }
  let lastNextActive = false;
  for (let i2 = entryCount - 1; i2 >= 0; i2--) {
    if (conversationEntries[i2].uuid) {
      lastNextActive = activeUuids.has(conversationEntries[i2].uuid);
    }
    nextIsActive[i2] = lastNextActive;
  }
  return conversationEntries.filter((entry, idx) => {
    if (entry.uuid) {
      return activeUuids.has(entry.uuid);
    }
    return prevIsActive[idx] && nextIsActive[idx];
  });
}

// src/core/tools/toolInput.ts
function extractResolvedAnswers(toolUseResult) {
  if (typeof toolUseResult !== "object" || toolUseResult === null) return void 0;
  const r2 = toolUseResult;
  return normalizeAnswersObject(r2.answers);
}
function normalizeAnswerValue(value) {
  if (typeof value === "string") return value;
  if (Array.isArray(value)) {
    const normalized = value.map((item) => typeof item === "string" ? item : String(item)).filter(Boolean).filter((item) => item.length > 0);
    if (normalized.length === 0) return void 0;
    return normalized.length === 1 ? normalized[0] : normalized;
  }
  if (typeof value === "object" && value !== null) {
    const record2 = value;
    if ("answers" in record2) return normalizeAnswerValue(record2.answers);
    if ("answer" in record2) return normalizeAnswerValue(record2.answer);
    if ("value" in record2) return normalizeAnswerValue(record2.value);
  }
  if (typeof value === "number" || typeof value === "boolean") return String(value);
  return void 0;
}
function normalizeAnswersObject(value) {
  if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
  const answers = {};
  for (const [question, rawValue] of Object.entries(value)) {
    const normalized = normalizeAnswerValue(rawValue);
    if (normalized) {
      answers[question] = normalized;
    }
  }
  return Object.keys(answers).length > 0 ? answers : void 0;
}
function parseAnswersFromJsonObject(resultText) {
  var _a3;
  const start = resultText.indexOf("{");
  const end = resultText.lastIndexOf("}");
  if (start < 0 || end <= start) return void 0;
  try {
    const parsed = JSON.parse(resultText.slice(start, end + 1));
    if (typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)) {
      const record2 = parsed;
      return (_a3 = normalizeAnswersObject(record2.answers)) != null ? _a3 : normalizeAnswersObject(parsed);
    }
    return normalizeAnswersObject(parsed);
  } catch (e2) {
    return void 0;
  }
}
function parseAnswersFromQuotedPairs(resultText) {
  var _a3, _b2;
  const answers = {};
  const pattern = /"([^"]+)"="([^"]*)"/g;
  for (const match of resultText.matchAll(pattern)) {
    const question = (_a3 = match[1]) == null ? void 0 : _a3.trim();
    if (!question) continue;
    answers[question] = (_b2 = match[2]) != null ? _b2 : "";
  }
  return Object.keys(answers).length > 0 ? answers : void 0;
}
function extractResolvedAnswersFromResultText(result) {
  var _a3;
  if (typeof result !== "string") return void 0;
  const trimmed = result.trim();
  if (!trimmed) return void 0;
  return (_a3 = parseAnswersFromJsonObject(trimmed)) != null ? _a3 : parseAnswersFromQuotedPairs(trimmed);
}

// src/utils/diff.ts
function structuredPatchToDiffLines(hunks) {
  const result = [];
  for (const hunk of hunks) {
    let oldLineNum = hunk.oldStart;
    let newLineNum = hunk.newStart;
    for (const line of hunk.lines) {
      const prefix = line[0];
      const text = line.slice(1);
      if (prefix === "+") {
        result.push({ type: "insert", text, newLineNum: newLineNum++ });
      } else if (prefix === "-") {
        result.push({ type: "delete", text, oldLineNum: oldLineNum++ });
      } else {
        result.push({ type: "equal", text, oldLineNum: oldLineNum++, newLineNum: newLineNum++ });
      }
    }
  }
  return result;
}
function countLineChanges(diffLines) {
  let added = 0;
  let removed = 0;
  for (const line of diffLines) {
    if (line.type === "insert") added++;
    else if (line.type === "delete") removed++;
  }
  return { added, removed };
}
function parseApplyPatchDiffs(patchText) {
  if (!patchText.trim()) return [];
  const fileDiffs = [];
  const lines = patchText.split(/\r?\n/);
  let current = null;
  const flushCurrent = () => {
    if (!current) return;
    fileDiffs.push(buildApplyPatchFileDiff(current));
    current = null;
  };
  for (const line of lines) {
    if (line.startsWith("*** Begin Patch") || line.startsWith("*** End Patch")) {
      continue;
    }
    if (line.startsWith("*** Add File: ")) {
      flushCurrent();
      current = {
        filePath: line.slice("*** Add File: ".length).trim(),
        operation: "add",
        rawLines: []
      };
      continue;
    }
    if (line.startsWith("*** Update File: ")) {
      flushCurrent();
      current = {
        filePath: line.slice("*** Update File: ".length).trim(),
        operation: "update",
        rawLines: []
      };
      continue;
    }
    if (line.startsWith("*** Delete File: ")) {
      flushCurrent();
      fileDiffs.push({
        filePath: line.slice("*** Delete File: ".length).trim(),
        operation: "delete",
        diffLines: [],
        stats: { added: 0, removed: 0 }
      });
      continue;
    }
    if (!current) continue;
    if (line.startsWith("*** Move to: ")) {
      current.movedTo = line.slice("*** Move to: ".length).trim();
      continue;
    }
    if (line === "*** End of File" || line.startsWith("@@") || line.startsWith("--- ") || line.startsWith("+++ ")) {
      continue;
    }
    const prefix = line[0];
    if (prefix === "+" || prefix === "-" || prefix === " ") {
      current.rawLines.push(line);
    }
  }
  flushCurrent();
  return fileDiffs;
}
function extractDiffData(toolUseResult, toolCall) {
  const filePath = toolCall.input.file_path || "file";
  if (toolUseResult && typeof toolUseResult === "object") {
    const result = toolUseResult;
    if (Array.isArray(result.structuredPatch) && result.structuredPatch.length > 0) {
      const resultFilePath = (typeof result.filePath === "string" ? result.filePath : null) || filePath;
      const hunks = result.structuredPatch;
      const diffLines = structuredPatchToDiffLines(hunks);
      const stats = countLineChanges(diffLines);
      return { filePath: resultFilePath, diffLines, stats };
    }
  }
  return diffFromToolInput(toolCall, filePath);
}
function diffFromToolInput(toolCall, filePath) {
  if (toolCall.name === "Edit") {
    const oldStr = toolCall.input.old_string;
    const newStr = toolCall.input.new_string;
    if (typeof oldStr === "string" && typeof newStr === "string") {
      const diffLines = [];
      const oldLines = oldStr.split("\n");
      const newLines = newStr.split("\n");
      let oldLineNum = 1;
      for (const line of oldLines) {
        diffLines.push({ type: "delete", text: line, oldLineNum: oldLineNum++ });
      }
      let newLineNum = 1;
      for (const line of newLines) {
        diffLines.push({ type: "insert", text: line, newLineNum: newLineNum++ });
      }
      return { filePath, diffLines, stats: countLineChanges(diffLines) };
    }
  }
  if (toolCall.name === "Write") {
    const content = toolCall.input.content;
    if (typeof content === "string") {
      const newLines = content.split("\n");
      const diffLines = newLines.map((text, i2) => ({
        type: "insert",
        text,
        newLineNum: i2 + 1
      }));
      return { filePath, diffLines, stats: { added: newLines.length, removed: 0 } };
    }
  }
  return void 0;
}
function buildApplyPatchFileDiff(current) {
  const diffLines = [];
  let oldLineNum = 1;
  let newLineNum = 1;
  for (const line of current.rawLines) {
    const prefix = line[0];
    const text = line.slice(1);
    if (prefix === "+") {
      diffLines.push({ type: "insert", text, newLineNum: newLineNum++ });
      continue;
    }
    if (prefix === "-") {
      diffLines.push({ type: "delete", text, oldLineNum: oldLineNum++ });
      continue;
    }
    diffLines.push({ type: "equal", text, oldLineNum: oldLineNum++, newLineNum: newLineNum++ });
  }
  const result = {
    filePath: current.filePath,
    operation: current.operation,
    diffLines,
    stats: countLineChanges(diffLines)
  };
  if (current.movedTo) result.movedTo = current.movedTo;
  return result;
}

// src/utils/interrupt.ts
var INTERRUPT_MARKERS = /* @__PURE__ */ new Set([
  "[Request interrupted by user]",
  "[Request interrupted by user for tool use]"
]);
var COMPACTION_CANCELED_STDERR_PATTERN = /^<local-command-stderr>\s*Error:\s*Compaction canceled\.?\s*<\/local-command-stderr>$/i;
function normalize2(text) {
  return text.trim();
}
function isBracketInterruptText(text) {
  return INTERRUPT_MARKERS.has(normalize2(text));
}
function isCompactionCanceledStderr(text) {
  return COMPACTION_CANCELED_STDERR_PATTERN.test(normalize2(text));
}
function isInterruptSignalText(text) {
  return isBracketInterruptText(text) || isCompactionCanceledStderr(text);
}

// src/core/tools/toolResultContent.ts
function extractToolResultContent(content, options) {
  if (typeof content === "string") return content;
  if (content == null) return "";
  if (Array.isArray(content)) {
    const textParts = content.filter(isTextBlock).map((block) => block.text);
    if (textParts.length > 0) return textParts.join("\n");
    if (content.length > 0) return JSON.stringify(content, null, options == null ? void 0 : options.fallbackIndent);
    return "";
  }
  return JSON.stringify(content, null, options == null ? void 0 : options.fallbackIndent);
}
function isTextBlock(block) {
  if (!block || typeof block !== "object") return false;
  const record2 = block;
  return record2.type === "text" && typeof record2.text === "string";
}

// src/providers/claude/history/sdkMessageParsing.ts
function extractTextContent(content) {
  if (!content) {
    return "";
  }
  if (typeof content === "string") {
    return content;
  }
  return content.filter((block) => block.type === "text" && typeof block.text === "string" && block.text.trim() !== "(no content)").map((block) => block.text).join("\n");
}
function isRebuiltContextContent(textContent) {
  if (!/^(User|Assistant):\s/.test(textContent)) {
    return false;
  }
  return textContent.includes("\n\nUser:") || textContent.includes("\n\nAssistant:") || textContent.includes("\n\nA:");
}
function extractDisplayContent(textContent) {
  return extractContentBeforeXmlContext(textContent);
}
function extractImages(content) {
  if (!content || typeof content === "string") {
    return void 0;
  }
  const imageBlocks = content.filter(
    (block) => {
      var _a3;
      return block.type === "image" && !!((_a3 = block.source) == null ? void 0 : _a3.data);
    }
  );
  if (imageBlocks.length === 0) {
    return void 0;
  }
  return imageBlocks.map((block, index) => ({
    id: `sdk-img-${Date.now()}-${index}`,
    name: `image-${index + 1}`,
    mediaType: block.source.media_type,
    data: block.source.data,
    size: Math.ceil(block.source.data.length * 0.75),
    source: "paste"
  }));
}
function extractToolCalls(content, toolResults) {
  var _a3;
  if (!content || typeof content === "string") {
    return void 0;
  }
  const toolUses = content.filter(
    (block) => block.type === "tool_use" && !!block.id && !!block.name
  );
  if (toolUses.length === 0) {
    return void 0;
  }
  const results = toolResults != null ? toolResults : /* @__PURE__ */ new Map();
  if (!toolResults) {
    for (const block of content) {
      if (block.type === "tool_result" && block.tool_use_id) {
        results.set(block.tool_use_id, {
          content: extractToolResultContent(block.content),
          isError: (_a3 = block.is_error) != null ? _a3 : false
        });
      }
    }
  }
  return toolUses.map((block) => {
    var _a4;
    const result = results.get(block.id);
    return {
      id: block.id,
      name: block.name,
      input: (_a4 = block.input) != null ? _a4 : {},
      status: result ? result.isError ? "error" : "completed" : "running",
      result: result == null ? void 0 : result.content,
      isExpanded: false
    };
  });
}
function mapContentBlocks(content) {
  if (!content || typeof content === "string") {
    return void 0;
  }
  const blocks = [];
  for (const block of content) {
    switch (block.type) {
      case "text": {
        const text = block.text;
        const trimmed = text == null ? void 0 : text.trim();
        if (text && trimmed && trimmed !== "(no content)") {
          blocks.push({ type: "text", content: text });
        }
        break;
      }
      case "thinking":
        if (block.thinking) {
          blocks.push({ type: "thinking", content: block.thinking });
        }
        break;
      case "tool_use":
        if (block.id) {
          blocks.push({ type: "tool_use", toolId: block.id });
        }
        break;
      default:
        break;
    }
  }
  return blocks.length > 0 ? blocks : void 0;
}
function parseSDKMessageToChat(sdkMsg, toolResults) {
  var _a3;
  if (sdkMsg.type === "file-history-snapshot") {
    return null;
  }
  if (sdkMsg.type === "system") {
    if (sdkMsg.subtype === "compact_boundary") {
      const timestamp2 = sdkMsg.timestamp ? new Date(sdkMsg.timestamp).getTime() : Date.now();
      return {
        id: sdkMsg.uuid || `compact-${timestamp2}-${Math.random().toString(36).slice(2)}`,
        role: "assistant",
        content: "",
        timestamp: timestamp2,
        contentBlocks: [{ type: "context_compacted" }]
      };
    }
    return null;
  }
  if (sdkMsg.type === "result") {
    return null;
  }
  if (sdkMsg.type !== "user" && sdkMsg.type !== "assistant") {
    return null;
  }
  const content = (_a3 = sdkMsg.message) == null ? void 0 : _a3.content;
  const textContent = extractTextContent(content);
  const images = sdkMsg.type === "user" ? extractImages(content) : void 0;
  const hasToolUse = Array.isArray(content) && content.some((block) => block.type === "tool_use");
  const hasImages = !!images && images.length > 0;
  if (!textContent && !hasToolUse && !hasImages && (!content || typeof content === "string")) {
    return null;
  }
  const timestamp = sdkMsg.timestamp ? new Date(sdkMsg.timestamp).getTime() : Date.now();
  const commandNameMatch = sdkMsg.type === "user" ? textContent.match(/<command-name>(\/[^<]+)<\/command-name>/) : null;
  let displayContent;
  if (sdkMsg.type === "user") {
    displayContent = commandNameMatch ? commandNameMatch[1] : extractDisplayContent(textContent);
  }
  const isInterrupt = sdkMsg.type === "user" && isInterruptSignalText(textContent);
  const isRebuiltContext = sdkMsg.type === "user" && isRebuiltContextContent(textContent);
  return {
    id: sdkMsg.uuid || `sdk-${timestamp}-${Math.random().toString(36).slice(2)}`,
    role: sdkMsg.type,
    content: textContent,
    displayContent,
    timestamp,
    toolCalls: sdkMsg.type === "assistant" ? extractToolCalls(content, toolResults) : void 0,
    contentBlocks: sdkMsg.type === "assistant" ? mapContentBlocks(content) : void 0,
    images,
    ...sdkMsg.type === "user" && sdkMsg.uuid && { userMessageId: sdkMsg.uuid },
    ...sdkMsg.type === "assistant" && sdkMsg.uuid && { assistantMessageId: sdkMsg.uuid },
    ...isInterrupt && { isInterrupt: true },
    ...isRebuiltContext && { isRebuiltContext: true }
  };
}
function collectToolResults(sdkMessages) {
  var _a3, _b2;
  const results = /* @__PURE__ */ new Map();
  for (const sdkMsg of sdkMessages) {
    const content = (_a3 = sdkMsg.message) == null ? void 0 : _a3.content;
    if (!content || typeof content === "string") {
      continue;
    }
    for (const block of content) {
      if (block.type === "tool_result" && block.tool_use_id) {
        results.set(block.tool_use_id, {
          content: extractToolResultContent(block.content),
          isError: (_b2 = block.is_error) != null ? _b2 : false
        });
      }
    }
  }
  return results;
}
function collectStructuredPatchResults(sdkMessages) {
  var _a3;
  const results = /* @__PURE__ */ new Map();
  for (const sdkMsg of sdkMessages) {
    if (sdkMsg.type !== "user" || !sdkMsg.toolUseResult) {
      continue;
    }
    const content = (_a3 = sdkMsg.message) == null ? void 0 : _a3.content;
    if (!content || typeof content === "string") {
      continue;
    }
    for (const block of content) {
      if (block.type === "tool_result" && block.tool_use_id) {
        results.set(block.tool_use_id, sdkMsg.toolUseResult);
      }
    }
  }
  return results;
}
function collectAsyncSubagentResults(sdkMessages) {
  const results = /* @__PURE__ */ new Map();
  for (const sdkMsg of sdkMessages) {
    if (sdkMsg.type !== "queue-operation") {
      continue;
    }
    if (sdkMsg.operation !== "enqueue") {
      continue;
    }
    if (typeof sdkMsg.content !== "string") {
      continue;
    }
    if (!sdkMsg.content.includes("<task-notification>")) {
      continue;
    }
    const taskId = extractXmlTag(sdkMsg.content, "task-id");
    const status = extractXmlTag(sdkMsg.content, "status");
    const result = extractXmlTag(sdkMsg.content, "result");
    if (!taskId || !result) {
      continue;
    }
    results.set(taskId, {
      result,
      status: status != null ? status : "completed"
    });
  }
  return results;
}
function extractXmlTag(content, tagName) {
  const regex = new RegExp(`<${tagName}>\\s*([\\s\\S]*?)\\s*</${tagName}>`, "i");
  const match = content.match(regex);
  if (!match || !match[1]) {
    return null;
  }
  const trimmed = match[1].trim();
  return trimmed.length > 0 ? trimmed : null;
}
function isSystemInjectedMessage(sdkMsg) {
  var _a3;
  if (sdkMsg.type !== "user") {
    return false;
  }
  if ("toolUseResult" in sdkMsg || "sourceToolUseID" in sdkMsg || !!sdkMsg.isMeta) {
    return true;
  }
  const text = extractTextContent((_a3 = sdkMsg.message) == null ? void 0 : _a3.content);
  if (!text) {
    return false;
  }
  if (text.includes("<command-name>") && text.includes("<command-message>")) {
    return false;
  }
  if (isCompactionCanceledStderr(text)) {
    return false;
  }
  if (text.startsWith("This session is being continued from a previous conversation")) {
    return true;
  }
  if (text.includes("<command-name>")) {
    return true;
  }
  if (text.includes("<local-command-stdout>") || text.includes("<local-command-stderr>")) {
    return true;
  }
  if (text.includes("<task-notification>")) {
    return true;
  }
  return false;
}
function mergeAssistantMessage(target, source) {
  if (source.content) {
    target.content = target.content ? `${target.content}

${source.content}` : source.content;
  }
  if (source.toolCalls) {
    target.toolCalls = [...target.toolCalls || [], ...source.toolCalls];
  }
  if (source.contentBlocks) {
    target.contentBlocks = [...target.contentBlocks || [], ...source.contentBlocks];
  }
  if (source.assistantMessageId) {
    target.assistantMessageId = source.assistantMessageId;
  }
}
function hydrateStructuredToolResults(messages, toolUseResults) {
  var _a3;
  if (toolUseResults.size === 0) {
    return;
  }
  for (const msg of messages) {
    if (msg.role !== "assistant" || !msg.toolCalls) {
      continue;
    }
    for (const toolCall of msg.toolCalls) {
      const toolUseResult = toolUseResults.get(toolCall.id);
      if (!toolUseResult) {
        continue;
      }
      if (!toolCall.diffData) {
        toolCall.diffData = extractDiffData(toolUseResult, toolCall);
      }
      if (toolCall.name === TOOL_ASK_USER_QUESTION) {
        const answers = (_a3 = extractResolvedAnswers(toolUseResult)) != null ? _a3 : extractResolvedAnswersFromResultText(toolCall.result);
        if (answers) {
          toolCall.resolvedAnswers = answers;
        }
      }
    }
  }
}
function hydrateFallbackAskUserAnswers(messages) {
  for (const msg of messages) {
    if (msg.role !== "assistant" || !msg.toolCalls) {
      continue;
    }
    for (const toolCall of msg.toolCalls) {
      if (toolCall.name !== TOOL_ASK_USER_QUESTION || toolCall.resolvedAnswers) {
        continue;
      }
      const answers = extractResolvedAnswersFromResultText(toolCall.result);
      if (answers) {
        toolCall.resolvedAnswers = answers;
      }
    }
  }
}

// src/providers/claude/history/sdkSessionPaths.ts
var import_fs4 = require("fs");
var fs9 = __toESM(require("fs/promises"));
var os7 = __toESM(require("os"));
var path7 = __toESM(require("path"));
function encodeVaultPathForSDK(vaultPath) {
  const absolutePath = path7.resolve(vaultPath);
  return absolutePath.replace(/[^a-zA-Z0-9]/g, "-");
}
function getSDKProjectsPath() {
  return path7.join(os7.homedir(), ".claude", "projects");
}
function isPathSafeId(value) {
  if (!value || value.length === 0 || value.length > 128) {
    return false;
  }
  if (value.includes("..") || value.includes("/") || value.includes("\\")) {
    return false;
  }
  return /^[a-zA-Z0-9_-]+$/.test(value);
}
function isValidSessionId(sessionId) {
  return isPathSafeId(sessionId);
}
function getSDKSessionPath(vaultPath, sessionId) {
  if (!isValidSessionId(sessionId)) {
    throw new Error(`Invalid session ID: ${sessionId}`);
  }
  const projectsPath = getSDKProjectsPath();
  const encodedVault = encodeVaultPathForSDK(vaultPath);
  return path7.join(projectsPath, encodedVault, `${sessionId}.jsonl`);
}
function sdkSessionExists(vaultPath, sessionId) {
  try {
    const sessionPath = getSDKSessionPath(vaultPath, sessionId);
    return (0, import_fs4.existsSync)(sessionPath);
  } catch (e2) {
    return false;
  }
}
async function deleteSDKSession(vaultPath, sessionId) {
  try {
    const sessionPath = getSDKSessionPath(vaultPath, sessionId);
    if (!(0, import_fs4.existsSync)(sessionPath)) {
      return;
    }
    await fs9.unlink(sessionPath);
  } catch (e2) {
  }
}
async function readSDKSession(vaultPath, sessionId) {
  try {
    const sessionPath = getSDKSessionPath(vaultPath, sessionId);
    if (!(0, import_fs4.existsSync)(sessionPath)) {
      return { messages: [], skippedLines: 0 };
    }
    const content = await fs9.readFile(sessionPath, "utf-8");
    const lines = content.split("\n").filter((line) => line.trim());
    const messages = [];
    let skippedLines = 0;
    for (const line of lines) {
      try {
        const msg = JSON.parse(line);
        messages.push(msg);
      } catch (e2) {
        skippedLines++;
      }
    }
    return { messages, skippedLines };
  } catch (error48) {
    const errorMsg = error48 instanceof Error ? error48.message : String(error48);
    return { messages: [], skippedLines: 0, error: errorMsg };
  }
}

// src/providers/claude/history/sdkSubagentSidecar.ts
var import_fs5 = require("fs");
var fs10 = __toESM(require("fs/promises"));
var path8 = __toESM(require("path"));

// src/utils/subagentJsonl.ts
function extractFinalResultFromSubagentJsonl(content) {
  var _a3;
  const lines = content.split("\n").map((line) => line.trim()).filter((line) => line.length > 0 && line.startsWith("{"));
  let lastAssistantText = null;
  let lastResultText = null;
  for (const line of lines) {
    let raw;
    try {
      raw = JSON.parse(line);
    } catch (e2) {
      continue;
    }
    if (!raw || typeof raw !== "object") {
      continue;
    }
    const record2 = raw;
    if (typeof record2.result === "string" && record2.result.trim().length > 0) {
      lastResultText = record2.result.trim();
    }
    if (((_a3 = record2.message) == null ? void 0 : _a3.role) !== "assistant" || !Array.isArray(record2.message.content)) {
      continue;
    }
    for (const blockRaw of record2.message.content) {
      if (!blockRaw || typeof blockRaw !== "object") {
        continue;
      }
      const block = blockRaw;
      if (block.type === "text" && typeof block.text === "string" && block.text.trim().length > 0) {
        lastAssistantText = block.text.trim();
      }
    }
  }
  return lastAssistantText != null ? lastAssistantText : lastResultText;
}

// src/providers/claude/history/sdkSubagentSidecar.ts
function isValidAgentId(agentId) {
  return isPathSafeId(agentId);
}
function parseTimestampMs(raw) {
  if (typeof raw !== "string") {
    return Date.now();
  }
  const parsed = Date.parse(raw);
  return Number.isNaN(parsed) ? Date.now() : parsed;
}
function parseSubagentEvents(entry) {
  var _a3;
  if (!entry || typeof entry !== "object") {
    return [];
  }
  const record2 = entry;
  const content = (_a3 = record2.message) == null ? void 0 : _a3.content;
  if (!Array.isArray(content)) {
    return [];
  }
  const timestamp = parseTimestampMs(record2.timestamp);
  const events = [];
  for (const blockRaw of content) {
    if (!blockRaw || typeof blockRaw !== "object") {
      continue;
    }
    const block = blockRaw;
    if (block.type === "tool_use") {
      if (typeof block.id !== "string" || typeof block.name !== "string") {
        continue;
      }
      events.push({
        type: "tool_use",
        toolUseId: block.id,
        toolName: block.name,
        toolInput: block.input && typeof block.input === "object" ? block.input : {},
        timestamp
      });
      continue;
    }
    if (block.type === "tool_result") {
      if (typeof block.tool_use_id !== "string") {
        continue;
      }
      events.push({
        type: "tool_result",
        toolUseId: block.tool_use_id,
        content: extractToolResultContent(block.content),
        isError: block.is_error === true,
        timestamp
      });
    }
  }
  return events;
}
function buildToolCallsFromSubagentEvents(events) {
  const toolsById = /* @__PURE__ */ new Map();
  for (const event of events) {
    const existing = toolsById.get(event.toolUseId);
    if (event.type === "tool_use") {
      if (!existing) {
        toolsById.set(event.toolUseId, {
          toolCall: {
            id: event.toolUseId,
            name: event.toolName,
            input: { ...event.toolInput },
            status: "running",
            isExpanded: false
          },
          hasToolUse: true,
          hasToolResult: false,
          timestamp: event.timestamp
        });
      } else {
        existing.toolCall.name = event.toolName;
        existing.toolCall.input = { ...event.toolInput };
        existing.hasToolUse = true;
        existing.timestamp = event.timestamp;
      }
      continue;
    }
    if (!existing) {
      toolsById.set(event.toolUseId, {
        toolCall: {
          id: event.toolUseId,
          name: "Unknown",
          input: {},
          status: event.isError ? "error" : "completed",
          result: event.content,
          isExpanded: false
        },
        hasToolUse: false,
        hasToolResult: true,
        timestamp: event.timestamp
      });
      continue;
    }
    existing.toolCall.status = event.isError ? "error" : "completed";
    existing.toolCall.result = event.content;
    existing.hasToolResult = true;
  }
  return Array.from(toolsById.values()).filter((entry) => entry.hasToolUse).sort((a2, b10) => a2.timestamp - b10.timestamp).map((entry) => entry.toolCall);
}
function getSubagentSidecarPath(vaultPath, sessionId, agentId) {
  if (!isValidSessionId(sessionId) || !isValidAgentId(agentId)) {
    return null;
  }
  const encodedVault = encodeVaultPathForSDK(vaultPath);
  return path8.join(
    getSDKProjectsPath(),
    encodedVault,
    sessionId,
    "subagents",
    `agent-${agentId}.jsonl`
  );
}
async function loadSubagentToolCalls(vaultPath, sessionId, agentId) {
  const subagentFilePath = getSubagentSidecarPath(vaultPath, sessionId, agentId);
  if (!subagentFilePath) {
    return [];
  }
  try {
    if (!(0, import_fs5.existsSync)(subagentFilePath)) {
      return [];
    }
    const content = await fs10.readFile(subagentFilePath, "utf-8");
    const lines = content.split("\n").filter((line) => line.trim());
    const events = [];
    const seen = /* @__PURE__ */ new Set();
    for (const line of lines) {
      let raw;
      try {
        raw = JSON.parse(line);
      } catch (e2) {
        continue;
      }
      for (const event of parseSubagentEvents(raw)) {
        const key = `${event.type}:${event.toolUseId}`;
        if (seen.has(key)) {
          continue;
        }
        seen.add(key);
        events.push(event);
      }
    }
    if (events.length === 0) {
      return [];
    }
    return buildToolCallsFromSubagentEvents(events);
  } catch (e2) {
    return [];
  }
}
async function loadSubagentFinalResult(vaultPath, sessionId, agentId) {
  const subagentFilePath = getSubagentSidecarPath(vaultPath, sessionId, agentId);
  if (!subagentFilePath) {
    return null;
  }
  try {
    if (!(0, import_fs5.existsSync)(subagentFilePath)) {
      return null;
    }
    const content = await fs10.readFile(subagentFilePath, "utf-8");
    return extractFinalResultFromSubagentJsonl(content);
  } catch (e2) {
    return null;
  }
}

// src/providers/claude/history/ClaudeHistoryStore.ts
async function loadSDKSessionMessages(vaultPath, sessionId, resumeAtMessageId) {
  var _a3, _b2, _c;
  const result = await readSDKSession(vaultPath, sessionId);
  if (result.error) {
    return { messages: [], skippedLines: result.skippedLines, error: result.error };
  }
  const filteredEntries = filterActiveBranch(result.messages, resumeAtMessageId);
  const toolResults = collectToolResults(filteredEntries);
  const toolUseResults = collectStructuredPatchResults(filteredEntries);
  const asyncSubagentResults = collectAsyncSubagentResults(filteredEntries);
  const chatMessages = [];
  let pendingAssistant = null;
  for (const sdkMsg of filteredEntries) {
    if (isSystemInjectedMessage(sdkMsg)) continue;
    if (sdkMsg.type === "assistant" && ((_a3 = sdkMsg.message) == null ? void 0 : _a3.model) === "<synthetic>") continue;
    const chatMsg = parseSDKMessageToChat(sdkMsg, toolResults);
    if (!chatMsg) continue;
    if (chatMsg.role === "assistant") {
      const isCompactBoundary = (_b2 = chatMsg.contentBlocks) == null ? void 0 : _b2.some((b10) => b10.type === "context_compacted");
      if (isCompactBoundary) {
        if (pendingAssistant) {
          chatMessages.push(pendingAssistant);
        }
        chatMessages.push(chatMsg);
        pendingAssistant = null;
      } else if (pendingAssistant) {
        mergeAssistantMessage(pendingAssistant, chatMsg);
      } else {
        pendingAssistant = chatMsg;
      }
    } else {
      if (pendingAssistant) {
        chatMessages.push(pendingAssistant);
        pendingAssistant = null;
      }
      chatMessages.push(chatMsg);
    }
  }
  if (pendingAssistant) {
    chatMessages.push(pendingAssistant);
  }
  hydrateStructuredToolResults(chatMessages, toolUseResults);
  hydrateFallbackAskUserAnswers(chatMessages);
  if (toolUseResults.size > 0 || asyncSubagentResults.size > 0) {
    const sidecarLoads = [];
    for (const msg of chatMessages) {
      if (msg.role !== "assistant" || !msg.toolCalls) continue;
      for (const toolCall of msg.toolCalls) {
        if (!isSubagentToolName(toolCall.name)) continue;
        if (toolCall.subagent) continue;
        if (((_c = toolCall.input) == null ? void 0 : _c.run_in_background) !== true) continue;
        const toolUseResult = toolUseResults.get(toolCall.id);
        const subagent = buildAsyncSubagentInfo(
          toolCall,
          toolUseResult,
          asyncSubagentResults
        );
        if (subagent) {
          toolCall.subagent = subagent;
          if (subagent.result !== void 0) {
            toolCall.result = subagent.result;
          }
          toolCall.status = subagent.status;
          if (subagent.agentId && isValidAgentId(subagent.agentId)) {
            sidecarLoads.push({
              subagent,
              promise: loadSubagentToolCalls(vaultPath, sessionId, subagent.agentId)
            });
          }
        }
      }
    }
    if (sidecarLoads.length > 0) {
      const results = await Promise.all(sidecarLoads.map((s4) => s4.promise));
      for (let i2 = 0; i2 < sidecarLoads.length; i2++) {
        const toolCalls = results[i2];
        if (toolCalls.length > 0) {
          sidecarLoads[i2].subagent.toolCalls = toolCalls;
        }
      }
    }
  }
  chatMessages.sort((a2, b10) => a2.timestamp - b10.timestamp);
  return { messages: chatMessages, skippedLines: result.skippedLines };
}

// src/providers/claude/history/ClaudeConversationHistoryService.ts
function chooseRicherResult(sdkResult, cachedResult) {
  const sdkText = typeof sdkResult === "string" ? sdkResult.trim() : "";
  const cachedText = typeof cachedResult === "string" ? cachedResult.trim() : "";
  if (sdkText.length === 0 && cachedText.length === 0) return void 0;
  if (sdkText.length === 0) return cachedResult;
  if (cachedText.length === 0) return sdkResult;
  return sdkText.length >= cachedText.length ? sdkResult : cachedResult;
}
function chooseRicherToolCalls(sdkToolCalls = [], cachedToolCalls = []) {
  if (sdkToolCalls.length >= cachedToolCalls.length) {
    return sdkToolCalls;
  }
  return cachedToolCalls;
}
function normalizeAsyncStatus(subagent, modeOverride) {
  var _a3;
  if (!subagent) return void 0;
  const mode = modeOverride != null ? modeOverride : subagent.mode;
  if (mode === "sync") return void 0;
  if (mode === "async") return (_a3 = subagent.asyncStatus) != null ? _a3 : subagent.status;
  return subagent.asyncStatus;
}
function isTerminalAsyncStatus(status) {
  return status === "completed" || status === "error" || status === "orphaned";
}
function mergeSubagentInfo(taskToolCall, cachedSubagent) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h;
  const sdkSubagent = taskToolCall.subagent;
  const cachedAsyncStatus = normalizeAsyncStatus(cachedSubagent);
  if (!sdkSubagent) {
    return {
      ...cachedSubagent,
      asyncStatus: cachedAsyncStatus,
      result: chooseRicherResult(taskToolCall.result, cachedSubagent.result)
    };
  }
  const sdkAsyncStatus = normalizeAsyncStatus(sdkSubagent);
  const sdkIsTerminal = isTerminalAsyncStatus(sdkAsyncStatus);
  const cachedIsTerminal = isTerminalAsyncStatus(cachedAsyncStatus);
  const sdkResult = (_a3 = taskToolCall.result) != null ? _a3 : sdkSubagent.result;
  const preferred = !sdkIsTerminal && cachedIsTerminal ? cachedSubagent : sdkSubagent;
  const mergedMode = (_d2 = (_b2 = sdkSubagent.mode) != null ? _b2 : cachedSubagent.mode) != null ? _d2 : ((_c = taskToolCall.input) == null ? void 0 : _c.run_in_background) === true ? "async" : void 0;
  const fallbackResult = chooseRicherResult(sdkResult, cachedSubagent.result);
  const mergedResult = preferred === cachedSubagent ? (_e = cachedSubagent.result) != null ? _e : fallbackResult : fallbackResult;
  const mergedAsyncStatus = normalizeAsyncStatus(preferred, mergedMode);
  return {
    ...cachedSubagent,
    ...sdkSubagent,
    description: sdkSubagent.description || cachedSubagent.description,
    prompt: sdkSubagent.prompt || cachedSubagent.prompt,
    mode: mergedMode,
    status: preferred.status,
    asyncStatus: mergedAsyncStatus,
    result: mergedResult,
    toolCalls: chooseRicherToolCalls(sdkSubagent.toolCalls, cachedSubagent.toolCalls),
    agentId: sdkSubagent.agentId || cachedSubagent.agentId,
    outputToolId: sdkSubagent.outputToolId || cachedSubagent.outputToolId,
    startedAt: (_f = sdkSubagent.startedAt) != null ? _f : cachedSubagent.startedAt,
    completedAt: (_g = sdkSubagent.completedAt) != null ? _g : cachedSubagent.completedAt,
    isExpanded: (_h = sdkSubagent.isExpanded) != null ? _h : cachedSubagent.isExpanded
  };
}
function ensureTaskToolCall(msg, subagentId, subagent) {
  msg.toolCalls = msg.toolCalls || [];
  let taskToolCall = msg.toolCalls.find(
    (tc) => tc.id === subagentId && isSubagentToolName(tc.name)
  );
  if (!taskToolCall) {
    taskToolCall = {
      id: subagentId,
      name: TOOL_TASK,
      input: {
        description: subagent.description,
        prompt: subagent.prompt || "",
        ...subagent.mode === "async" ? { run_in_background: true } : {}
      },
      status: subagent.status,
      result: subagent.result,
      isExpanded: false,
      subagent
    };
    msg.toolCalls.push(taskToolCall);
    return taskToolCall;
  }
  if (!taskToolCall.input.description) {
    taskToolCall.input.description = subagent.description;
  }
  if (!taskToolCall.input.prompt) {
    taskToolCall.input.prompt = subagent.prompt || "";
  }
  if (subagent.mode === "async") {
    taskToolCall.input.run_in_background = true;
  }
  const mergedSubagent = mergeSubagentInfo(taskToolCall, subagent);
  taskToolCall.status = mergedSubagent.status;
  if (mergedSubagent.mode === "async") {
    taskToolCall.input.run_in_background = true;
  }
  if (mergedSubagent.result !== void 0) {
    taskToolCall.result = mergedSubagent.result;
  }
  taskToolCall.subagent = mergedSubagent;
  return taskToolCall;
}
function dedupeMessages(messages) {
  const seen = /* @__PURE__ */ new Set();
  const result = [];
  for (const message of messages) {
    if (seen.has(message.id)) continue;
    seen.add(message.id);
    result.push(message);
  }
  return result;
}
async function enrichAsyncSubagentToolCalls(subagentData, vaultPath, sessionIds) {
  var _a3, _b2;
  const uniqueSessionIds = [...new Set(sessionIds)];
  if (uniqueSessionIds.length === 0) return;
  const loaderCache = /* @__PURE__ */ new Map();
  for (const subagent of Object.values(subagentData)) {
    if (subagent.mode !== "async") continue;
    if (!subagent.agentId) continue;
    if (((_b2 = (_a3 = subagent.toolCalls) == null ? void 0 : _a3.length) != null ? _b2 : 0) > 0) continue;
    for (const sessionId of uniqueSessionIds) {
      const cacheKey = `${sessionId}:${subagent.agentId}`;
      let loader = loaderCache.get(cacheKey);
      if (!loader) {
        loader = loadSubagentToolCalls(vaultPath, sessionId, subagent.agentId);
        loaderCache.set(cacheKey, loader);
      }
      const recoveredToolCalls = await loader;
      if (recoveredToolCalls.length === 0) continue;
      subagent.toolCalls = recoveredToolCalls.map((toolCall) => ({
        ...toolCall,
        input: { ...toolCall.input }
      }));
      break;
    }
  }
}
function applySubagentData(messages, subagentData) {
  var _a3, _b2, _c, _d2, _e;
  const attachedSubagentIds = /* @__PURE__ */ new Set();
  for (const msg of messages) {
    if (msg.role !== "assistant") continue;
    for (const [subagentId, subagent] of Object.entries(subagentData)) {
      const hasSubagentBlock = (_a3 = msg.contentBlocks) == null ? void 0 : _a3.some(
        (block) => block.type === "subagent" && block.subagentId === subagentId || block.type === "tool_use" && block.toolId === subagentId
      );
      const hasTaskToolCall = (_c = (_b2 = msg.toolCalls) == null ? void 0 : _b2.some((tc) => tc.id === subagentId)) != null ? _c : false;
      if (!hasSubagentBlock && !hasTaskToolCall) continue;
      ensureTaskToolCall(msg, subagentId, subagent);
      if (!msg.contentBlocks) {
        msg.contentBlocks = [];
      }
      let hasNormalizedSubagentBlock = false;
      for (let i2 = 0; i2 < msg.contentBlocks.length; i2++) {
        const block = msg.contentBlocks[i2];
        if (block.type === "tool_use" && block.toolId === subagentId) {
          msg.contentBlocks[i2] = {
            type: "subagent",
            subagentId,
            mode: subagent.mode
          };
          hasNormalizedSubagentBlock = true;
        } else if (block.type === "subagent" && block.subagentId === subagentId && !block.mode) {
          block.mode = subagent.mode;
          hasNormalizedSubagentBlock = true;
        } else if (block.type === "subagent" && block.subagentId === subagentId) {
          hasNormalizedSubagentBlock = true;
        }
      }
      if (!hasNormalizedSubagentBlock && hasTaskToolCall) {
        msg.contentBlocks.push({
          type: "subagent",
          subagentId,
          mode: subagent.mode
        });
      }
      attachedSubagentIds.add(subagentId);
    }
  }
  for (const [subagentId, subagent] of Object.entries(subagentData)) {
    if (attachedSubagentIds.has(subagentId)) continue;
    let anchor = [...messages].reverse().find((msg) => msg.role === "assistant");
    if (!anchor) {
      anchor = {
        id: `subagent-recovery-${subagentId}`,
        role: "assistant",
        content: "",
        timestamp: (_e = (_d2 = subagent.completedAt) != null ? _d2 : subagent.startedAt) != null ? _e : Date.now(),
        contentBlocks: []
      };
      messages.push(anchor);
    }
    ensureTaskToolCall(anchor, subagentId, subagent);
    anchor.contentBlocks = anchor.contentBlocks || [];
    const hasSubagentBlock = anchor.contentBlocks.some(
      (block) => block.type === "subagent" && block.subagentId === subagentId
    );
    if (!hasSubagentBlock) {
      anchor.contentBlocks.push({
        type: "subagent",
        subagentId,
        mode: subagent.mode
      });
    }
  }
}
function buildPersistedSubagentData(messages) {
  const result = {};
  for (const msg of messages) {
    if (msg.role !== "assistant" || !msg.toolCalls) continue;
    for (const toolCall of msg.toolCalls) {
      if (!isSubagentToolName(toolCall.name) || !toolCall.subagent) continue;
      result[toolCall.subagent.id] = toolCall.subagent;
    }
  }
  return result;
}
function sanitizeProviderState(providerState) {
  const sanitizedEntries = Object.entries(providerState).filter(([, value]) => value !== void 0);
  if (sanitizedEntries.length === 0) {
    return void 0;
  }
  return Object.fromEntries(sanitizedEntries);
}
var ClaudeConversationHistoryService = class {
  constructor() {
    this.hydratedConversationIds = /* @__PURE__ */ new Set();
  }
  isPendingForkConversation(conversation) {
    const state = getClaudeState(conversation.providerState);
    return !!state.forkSource && !state.providerSessionId && !conversation.sessionId;
  }
  resolveSessionIdForConversation(conversation) {
    var _a3, _b2, _c, _d2;
    if (!conversation) return null;
    const state = getClaudeState(conversation.providerState);
    return (_d2 = (_c = (_a3 = state.providerSessionId) != null ? _a3 : conversation.sessionId) != null ? _c : (_b2 = state.forkSource) == null ? void 0 : _b2.sessionId) != null ? _d2 : null;
  }
  buildForkProviderState(sourceSessionId, resumeAt, _sourceProviderState) {
    const state = {
      forkSource: { sessionId: sourceSessionId, resumeAt }
    };
    return state;
  }
  buildPersistedProviderState(conversation) {
    const providerState = {
      ...getClaudeState(conversation.providerState)
    };
    const subagentData = buildPersistedSubagentData(conversation.messages);
    if (Object.keys(subagentData).length > 0) {
      providerState.subagentData = subagentData;
    } else {
      delete providerState.subagentData;
    }
    return sanitizeProviderState(providerState);
  }
  async hydrateConversationHistory(conversation, vaultPath) {
    var _a3, _b2;
    if (!vaultPath || this.hydratedConversationIds.has(conversation.id)) {
      return;
    }
    const state = getClaudeState(conversation.providerState);
    const isPendingFork = this.isPendingForkConversation(conversation);
    const allSessionIds = isPendingFork ? [state.forkSource.sessionId] : [
      ...state.previousProviderSessionIds || [],
      (_a3 = state.providerSessionId) != null ? _a3 : conversation.sessionId
    ].filter((id) => !!id);
    if (allSessionIds.length === 0) {
      return;
    }
    const allSdkMessages = [];
    let missingSessionCount = 0;
    let errorCount = 0;
    let successCount = 0;
    const currentSessionId = isPendingFork ? state.forkSource.sessionId : (_b2 = state.providerSessionId) != null ? _b2 : conversation.sessionId;
    for (const sessionId of allSessionIds) {
      if (!sdkSessionExists(vaultPath, sessionId)) {
        missingSessionCount++;
        continue;
      }
      const isCurrentSession = sessionId === currentSessionId;
      const truncateAt = isCurrentSession ? isPendingFork ? state.forkSource.resumeAt : conversation.resumeAtMessageId : void 0;
      const result = await loadSDKSessionMessages(vaultPath, sessionId, truncateAt);
      if (result.error) {
        errorCount++;
        continue;
      }
      successCount++;
      allSdkMessages.push(...result.messages);
    }
    const allSessionsMissing = missingSessionCount === allSessionIds.length;
    const hasLoadErrors = errorCount > 0 && successCount === 0 && !allSessionsMissing;
    if (hasLoadErrors) {
      return;
    }
    const filteredSdkMessages = allSdkMessages.filter((msg) => !msg.isRebuiltContext);
    const merged = dedupeMessages([
      ...conversation.messages,
      ...filteredSdkMessages
    ]).sort((a2, b10) => a2.timestamp - b10.timestamp);
    if (state.subagentData) {
      await enrichAsyncSubagentToolCalls(
        state.subagentData,
        vaultPath,
        allSessionIds
      );
      applySubagentData(merged, state.subagentData);
    }
    conversation.messages = merged;
    this.hydratedConversationIds.add(conversation.id);
  }
  async deleteConversationSession(conversation, vaultPath) {
    var _a3;
    const state = getClaudeState(conversation.providerState);
    const sessionId = (_a3 = state.providerSessionId) != null ? _a3 : conversation.sessionId;
    if (!vaultPath || !sessionId) {
      return;
    }
    await deleteSDKSession(vaultPath, sessionId);
  }
};

// src/providers/claude/runtime/ClaudeChatRuntime.ts
var import_obsidian14 = require("obsidian");
init_env();
init_path();

// src/utils/session.ts
var SESSION_ERROR_PATTERNS = [
  "session expired",
  "session not found",
  "invalid session",
  "session invalid",
  "process exited with code"
];
var SESSION_ERROR_COMPOUND_PATTERNS = [
  { includes: ["session", "expired"] },
  { includes: ["resume", "failed"] },
  { includes: ["resume", "error"] }
];
function isSessionExpiredError(error48) {
  const msg = error48 instanceof Error ? error48.message.toLowerCase() : "";
  for (const pattern of SESSION_ERROR_PATTERNS) {
    if (msg.includes(pattern)) {
      return true;
    }
  }
  for (const { includes } of SESSION_ERROR_COMPOUND_PATTERNS) {
    if (includes.every((part) => msg.includes(part))) {
      return true;
    }
  }
  return false;
}
function formatToolInput(input, maxLength = 200) {
  if (!input || Object.keys(input).length === 0) return "";
  try {
    const parts = [];
    for (const [key, value] of Object.entries(input)) {
      if (value === void 0 || value === null) continue;
      let valueStr;
      if (typeof value === "string") {
        valueStr = value.length > 100 ? `${value.slice(0, 100)}...` : value;
      } else if (typeof value === "object") {
        valueStr = "[object]";
      } else {
        valueStr = String(value);
      }
      parts.push(`${key}=${valueStr}`);
    }
    const result = parts.join(", ");
    return result.length > maxLength ? `${result.slice(0, maxLength)}...` : result;
  } catch (e2) {
    return "[input formatting error]";
  }
}
function formatToolCallForContext(toolCall, maxErrorLength = 500) {
  var _a3;
  const status = (_a3 = toolCall.status) != null ? _a3 : "completed";
  const isFailed = status === "error" || status === "blocked";
  const inputStr = formatToolInput(toolCall.input);
  const inputPart = inputStr ? ` input: ${inputStr}` : "";
  if (!isFailed) {
    return `[Tool ${toolCall.name}${inputPart} status=${status}]`;
  }
  const hasResult = typeof toolCall.result === "string" && toolCall.result.trim().length > 0;
  if (!hasResult) {
    return `[Tool ${toolCall.name}${inputPart} status=${status}]`;
  }
  const errorMsg = truncateToolResult(toolCall.result, maxErrorLength);
  return `[Tool ${toolCall.name}${inputPart} status=${status}] error: ${errorMsg}`;
}
function truncateToolResult(result, maxLength = 500) {
  if (result.length > maxLength) {
    return `${result.slice(0, maxLength)}... (truncated)`;
  }
  return result;
}
function formatContextLine(message) {
  if (!message.currentNote) {
    return null;
  }
  return formatCurrentNote(message.currentNote);
}
function formatThinkingBlocks(message) {
  if (!message.contentBlocks) return [];
  const thinkingBlocks = message.contentBlocks.filter(
    (block) => block.type === "thinking"
  );
  if (thinkingBlocks.length === 0) return [];
  const totalDuration = thinkingBlocks.reduce(
    (sum, block) => {
      var _a3;
      return sum + ((_a3 = block.durationSeconds) != null ? _a3 : 0);
    },
    0
  );
  const durationPart = totalDuration > 0 ? `, ${totalDuration.toFixed(1)}s total` : "";
  return [`[Thinking: ${thinkingBlocks.length} block(s)${durationPart}]`];
}
function buildContextFromHistory(messages) {
  var _a3, _b2, _c;
  const parts = [];
  for (const message of messages) {
    if (message.role !== "user" && message.role !== "assistant") {
      continue;
    }
    if (message.isInterrupt) {
      continue;
    }
    if (message.role === "assistant") {
      const hasContent = message.content && message.content.trim().length > 0;
      const hasToolCalls = message.toolCalls && message.toolCalls.length > 0;
      const hasThinking = (_a3 = message.contentBlocks) == null ? void 0 : _a3.some((b10) => b10.type === "thinking");
      if (!hasContent && !hasToolCalls && !hasThinking) {
        continue;
      }
    }
    const role = message.role === "user" ? "User" : "Assistant";
    const lines = [];
    const content = (_b2 = message.content) == null ? void 0 : _b2.trim();
    const contextLine = formatContextLine(message);
    const userPayload = contextLine ? content ? `${contextLine}

${content}` : contextLine : content;
    lines.push(userPayload ? `${role}: ${userPayload}` : `${role}:`);
    if (message.role === "assistant") {
      const thinkingLines = formatThinkingBlocks(message);
      if (thinkingLines.length > 0) {
        lines.push(...thinkingLines);
      }
    }
    if (message.role === "assistant" && ((_c = message.toolCalls) == null ? void 0 : _c.length)) {
      const toolLines = message.toolCalls.map((tc) => formatToolCallForContext(tc)).filter(Boolean);
      if (toolLines.length > 0) {
        lines.push(...toolLines);
      }
    }
    parts.push(lines.join("\n"));
  }
  return parts.join("\n\n");
}
function getLastUserMessage(messages) {
  for (let i2 = messages.length - 1; i2 >= 0; i2--) {
    if (messages[i2].role === "user") {
      return messages[i2];
    }
  }
  return void 0;
}
function buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory) {
  var _a3, _b2;
  if (!historyContext) return prompt;
  const lastUserMessage = getLastUserMessage(conversationHistory);
  const lastUserQuery = (_b2 = lastUserMessage == null ? void 0 : lastUserMessage.displayContent) != null ? _b2 : extractUserQuery((_a3 = lastUserMessage == null ? void 0 : lastUserMessage.content) != null ? _a3 : "");
  const currentUserQuery = extractUserQuery(actualPrompt);
  const shouldAppendPrompt = !lastUserMessage || lastUserQuery.trim() !== currentUserQuery.trim();
  return shouldAppendPrompt ? `${historyContext}

User: ${prompt}` : historyContext;
}

// src/providers/claude/hooks/SubagentHooks.ts
var STOP_BLOCK_REASON = 'Background subagents are still running. Use `TaskOutput task_id="..." block=true` to wait for their results before ending your turn.';
function createStopSubagentHook(getState) {
  return {
    hooks: [
      async () => {
        let hasRunning;
        try {
          hasRunning = getState().hasRunning;
        } catch (e2) {
          hasRunning = true;
        }
        if (hasRunning) {
          return { decision: "block", reason: STOP_BLOCK_REASON };
        }
        return {};
      }
    ]
  };
}

// src/utils/browser.ts
function escapeXmlAttribute(value) {
  return value.replace(/&/g, "&amp;").replace(/"/g, "&quot;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
}
function buildAttributeList(context) {
  var _a3, _b2;
  const attrs = [];
  const source = context.source.trim() || "unknown";
  attrs.push(`source="${escapeXmlAttribute(source)}"`);
  if ((_a3 = context.title) == null ? void 0 : _a3.trim()) {
    attrs.push(`title="${escapeXmlAttribute(context.title.trim())}"`);
  }
  if ((_b2 = context.url) == null ? void 0 : _b2.trim()) {
    attrs.push(`url="${escapeXmlAttribute(context.url.trim())}"`);
  }
  return attrs.join(" ");
}
function escapeXmlBody(text) {
  return text.replace(/<\/browser_selection>/gi, "&lt;/browser_selection&gt;");
}
function formatBrowserContext(context) {
  const selectedText = context.selectedText.trim();
  if (!selectedText) return "";
  const attrs = buildAttributeList(context);
  return `<browser_selection ${attrs}>
${escapeXmlBody(selectedText)}
</browser_selection>`;
}
function appendBrowserContext(prompt, context) {
  const formatted = formatBrowserContext(context);
  return formatted ? `${prompt}

${formatted}` : prompt;
}

// src/utils/canvas.ts
function formatCanvasContext(context) {
  if (context.nodeIds.length === 0) return "";
  return `<canvas_selection path="${context.canvasPath}">
${context.nodeIds.join(", ")}
</canvas_selection>`;
}
function appendCanvasContext(prompt, context) {
  const formatted = formatCanvasContext(context);
  return formatted ? `${prompt}

${formatted}` : prompt;
}

// src/utils/editor.ts
function getEditorView(editor) {
  return editor.cm;
}
function findNearestNonEmptyLine(getLine, lineCount, startLine, direction) {
  const step = direction === "before" ? -1 : 1;
  for (let i2 = startLine + step; i2 >= 0 && i2 < lineCount; i2 += step) {
    const content = getLine(i2);
    if (content.trim().length > 0) {
      return content;
    }
  }
  return "";
}
function buildCursorContext(getLine, lineCount, line, column) {
  const lineContent = getLine(line);
  const beforeCursor = lineContent.substring(0, column);
  const afterCursor = lineContent.substring(column);
  const lineIsEmpty = lineContent.trim().length === 0;
  const nothingBefore = beforeCursor.trim().length === 0;
  const nothingAfter = afterCursor.trim().length === 0;
  const isInbetween = lineIsEmpty || nothingBefore && nothingAfter;
  let contextBefore = beforeCursor;
  let contextAfter = afterCursor;
  if (isInbetween) {
    contextBefore = findNearestNonEmptyLine(getLine, lineCount, line, "before");
    contextAfter = findNearestNonEmptyLine(getLine, lineCount, line, "after");
  }
  return { beforeCursor: contextBefore, afterCursor: contextAfter, isInbetween, line, column };
}
function formatEditorContext(context) {
  if (context.mode === "selection" && context.selectedText) {
    const lineAttr = context.startLine && context.lineCount ? ` lines="${context.startLine}-${context.startLine + context.lineCount - 1}"` : "";
    return `<editor_selection path="${context.notePath}"${lineAttr}>
${context.selectedText}
</editor_selection>`;
  } else if (context.mode === "cursor" && context.cursorContext) {
    const ctx = context.cursorContext;
    let content;
    if (ctx.isInbetween) {
      const parts = [];
      if (ctx.beforeCursor) parts.push(ctx.beforeCursor);
      parts.push("| #inbetween");
      if (ctx.afterCursor) parts.push(ctx.afterCursor);
      content = parts.join("\n");
    } else {
      content = `${ctx.beforeCursor}|${ctx.afterCursor} #inline`;
    }
    return `<editor_cursor path="${context.notePath}">
${content}
</editor_cursor>`;
  }
  return "";
}
function appendEditorContext(prompt, context) {
  const formatted = formatEditorContext(context);
  return formatted ? `${prompt}

${formatted}` : prompt;
}

// src/providers/claude/prompt/ClaudeTurnEncoder.ts
function isCompactCommand(text) {
  return /^\/compact(\s|$)/i.test(text);
}
function encodeClaudeTurn(request, mcpManager) {
  const isCompact = isCompactCommand(request.text);
  let persistedContent = request.text;
  if (!isCompact) {
    if (request.currentNotePath) {
      persistedContent = appendCurrentNote(persistedContent, request.currentNotePath);
    }
    if (request.editorSelection) {
      persistedContent = appendEditorContext(persistedContent, request.editorSelection);
    }
    if (request.browserSelection) {
      persistedContent = appendBrowserContext(persistedContent, request.browserSelection);
    }
    if (request.canvasSelection) {
      persistedContent = appendCanvasContext(persistedContent, request.canvasSelection);
    }
  }
  const mcpMentions = mcpManager.extractMentions(persistedContent);
  return {
    request,
    persistedContent,
    prompt: mcpManager.transformMentions(persistedContent),
    isCompact,
    mcpMentions
  };
}

// src/providers/claude/sdk/typeGuards.ts
function isSessionInitEvent(event) {
  return event.type === "session_init";
}
function isContextWindowEvent(event) {
  return event.type === "context_window";
}
function isStreamChunk(event) {
  return event.type !== "session_init" && event.type !== "context_window";
}

// src/providers/claude/sdk/messages.ts
function isBlockedMessage(message) {
  return message.type === "user" && "_blocked" in message && message._blocked === true && "_blockReason" in message;
}

// src/providers/claude/stream/toolInputStreamState.ts
var MAIN_AGENT_STREAM = "__main__";
function isRecord3(value) {
  return !!value && typeof value === "object" && !Array.isArray(value);
}
function normalizeToolInput(value) {
  return isRecord3(value) ? value : {};
}
function getContentBlockKey(parentToolUseId, index) {
  return `${parentToolUseId != null ? parentToolUseId : MAIN_AGENT_STREAM}:${index}`;
}
function getParentPrefix(parentToolUseId) {
  return `${parentToolUseId != null ? parentToolUseId : MAIN_AGENT_STREAM}:`;
}
function findClosingTokenIndex(tokens, value) {
  var _a3;
  for (let index = tokens.length - 1; index >= 0; index -= 1) {
    if (((_a3 = tokens[index]) == null ? void 0 : _a3.value) === value) {
      return index;
    }
  }
  return -1;
}
function tokenizePartialJson(input) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h;
  const tokens = [];
  let index = 0;
  while (index < input.length) {
    let char = (_a3 = input[index]) != null ? _a3 : "";
    if (char === "\\") {
      index += 1;
      continue;
    }
    if (char === "{" || char === "}") {
      tokens.push({ type: "brace", value: char });
      index += 1;
      continue;
    }
    if (char === "[" || char === "]") {
      tokens.push({ type: "bracket", value: char });
      index += 1;
      continue;
    }
    if (char === ":") {
      tokens.push({ type: "separator", value: char });
      index += 1;
      continue;
    }
    if (char === ",") {
      tokens.push({ type: "delimiter", value: char });
      index += 1;
      continue;
    }
    if (char === '"') {
      let value = "";
      let isDanglingString = false;
      index += 1;
      char = (_b2 = input[index]) != null ? _b2 : "";
      while (char !== '"') {
        if (index === input.length) {
          isDanglingString = true;
          break;
        }
        if (char === "\\") {
          index += 1;
          if (index === input.length) {
            isDanglingString = true;
            break;
          }
          value += char + ((_c = input[index]) != null ? _c : "");
          index += 1;
          char = (_d2 = input[index]) != null ? _d2 : "";
          continue;
        }
        value += char;
        index += 1;
        char = (_e = input[index]) != null ? _e : "";
      }
      index += 1;
      if (!isDanglingString) {
        tokens.push({ type: "string", value });
      }
      continue;
    }
    if (/\s/.test(char)) {
      index += 1;
      continue;
    }
    if (/[0-9]/.test(char) || char === "-" || char === ".") {
      let value = "";
      if (char === "-") {
        value += char;
        index += 1;
        char = (_f = input[index]) != null ? _f : "";
      }
      while (/[0-9]/.test(char) || char === ".") {
        value += char;
        index += 1;
        char = (_g = input[index]) != null ? _g : "";
      }
      tokens.push({ type: "number", value });
      continue;
    }
    if (/[a-z]/i.test(char)) {
      let value = "";
      while (/[a-z]/i.test(char)) {
        value += char;
        index += 1;
        char = (_h = input[index]) != null ? _h : "";
      }
      if (value === "true" || value === "false" || value === "null") {
        tokens.push({ type: "name", value });
      } else {
        index += 1;
      }
      continue;
    }
    index += 1;
  }
  return tokens;
}
function stripIncompleteTail(tokens) {
  if (tokens.length === 0) {
    return tokens;
  }
  const lastToken = tokens[tokens.length - 1];
  if (!lastToken) {
    return tokens;
  }
  switch (lastToken.type) {
    case "separator":
    case "delimiter":
      return stripIncompleteTail(tokens.slice(0, -1));
    case "number": {
      const lastChar = lastToken.value[lastToken.value.length - 1];
      return lastChar === "." || lastChar === "-" ? stripIncompleteTail(tokens.slice(0, -1)) : tokens;
    }
    case "string": {
      const previousToken = tokens[tokens.length - 2];
      if ((previousToken == null ? void 0 : previousToken.type) === "delimiter") {
        return stripIncompleteTail(tokens.slice(0, -1));
      }
      if ((previousToken == null ? void 0 : previousToken.type) === "brace" && previousToken.value === "{") {
        return stripIncompleteTail(tokens.slice(0, -1));
      }
      return tokens;
    }
    default:
      return tokens;
  }
}
function closeOpenContainers(tokens) {
  const completedTokens = [...tokens];
  const closingTokens = [];
  for (const token of completedTokens) {
    if (token.type === "brace") {
      if (token.value === "{") {
        closingTokens.push({ type: "brace", value: "}" });
      } else {
        const closingIndex = findClosingTokenIndex(closingTokens, "}");
        if (closingIndex >= 0) {
          closingTokens.splice(closingIndex, 1);
        }
      }
      continue;
    }
    if (token.type === "bracket") {
      if (token.value === "[") {
        closingTokens.push({ type: "bracket", value: "]" });
      } else {
        const closingIndex = findClosingTokenIndex(closingTokens, "]");
        if (closingIndex >= 0) {
          closingTokens.splice(closingIndex, 1);
        }
      }
    }
  }
  for (let index = closingTokens.length - 1; index >= 0; index -= 1) {
    const token = closingTokens[index];
    if (token) {
      completedTokens.push(token);
    }
  }
  return completedTokens;
}
function renderJson(tokens) {
  return tokens.map((token) => token.type === "string" ? `"${token.value}"` : token.value).join("");
}
function parsePartialToolInput(input) {
  const tokens = tokenizePartialJson(input);
  if (tokens.length === 0) {
    return {};
  }
  try {
    const repairedJson = renderJson(closeOpenContainers(stripIncompleteTail(tokens)));
    return normalizeToolInput(JSON.parse(repairedJson));
  } catch (e2) {
    return null;
  }
}
function createTransformStreamState() {
  const activeToolUses = /* @__PURE__ */ new Map();
  return {
    registerToolUse(parentToolUseId, index, toolUse) {
      activeToolUses.set(getContentBlockKey(parentToolUseId, index), {
        ...toolUse,
        input: { ...toolUse.input },
        partialJson: ""
      });
    },
    applyInputJsonDelta(parentToolUseId, index, partialJson) {
      const snapshot = activeToolUses.get(getContentBlockKey(parentToolUseId, index));
      if (!snapshot) {
        return null;
      }
      snapshot.partialJson += partialJson;
      const parsedInput = parsePartialToolInput(snapshot.partialJson);
      if (parsedInput === null) {
        return null;
      }
      snapshot.input = {
        ...snapshot.input,
        ...parsedInput
      };
      return {
        id: snapshot.id,
        name: snapshot.name,
        input: { ...snapshot.input }
      };
    },
    clearContentBlock(parentToolUseId, index) {
      activeToolUses.delete(getContentBlockKey(parentToolUseId, index));
    },
    clearParent(parentToolUseId) {
      const parentPrefix = getParentPrefix(parentToolUseId);
      for (const key of activeToolUses.keys()) {
        if (key.startsWith(parentPrefix)) {
          activeToolUses.delete(key);
        }
      }
    },
    clearAll() {
      activeToolUses.clear();
    }
  };
}

// src/providers/claude/stream/transformClaudeMessage.ts
function getToolInput(input) {
  if (!input || typeof input !== "object" || Array.isArray(input)) {
    return {};
  }
  return input;
}
function emitToolUse(parentToolUseId, fields) {
  if (parentToolUseId === null) {
    return { type: "tool_use", ...fields };
  }
  return { type: "subagent_tool_use", subagentId: parentToolUseId, ...fields };
}
function emitToolResult(parentToolUseId, fields) {
  if (parentToolUseId === null) {
    return { type: "tool_result", ...fields };
  }
  return { type: "subagent_tool_result", subagentId: parentToolUseId, ...fields };
}
function isResultError(message) {
  return !!message.subtype && message.subtype !== "success";
}
function normalizeClaudeModelId(model) {
  const normalized = model.trim().toLowerCase();
  const claudeIndex = normalized.indexOf("claude-");
  return claudeIndex >= 0 ? normalized.slice(claudeIndex) : normalized;
}
function parseClaudeModelSignature(model) {
  const normalized = normalizeClaudeModelId(model);
  if (normalized === "haiku") {
    return { normalizedModel: normalized, family: "haiku", is1M: false };
  }
  if (normalized === "sonnet" || normalized === "sonnet[1m]") {
    return { normalizedModel: normalized, family: "sonnet", is1M: normalized.endsWith("[1m]") };
  }
  if (normalized === "opus" || normalized === "opus[1m]") {
    return { normalizedModel: normalized, family: "opus", is1M: normalized.endsWith("[1m]") };
  }
  const versionedMatch = normalized.match(
    /^claude-(haiku|sonnet|opus)-(\d+)(?:-(\d+))?(?:-(\d{8}))?(?:-v\d+:\d+)?(\[1m\])?$/
  );
  if (versionedMatch) {
    const [, familyMatch, major, minor, date7, oneMillionSuffix] = versionedMatch;
    const family = familyMatch;
    return {
      normalizedModel: normalized,
      family,
      is1M: oneMillionSuffix === "[1m]",
      major,
      minor,
      date: date7
    };
  }
  return null;
}
function findUniqueEntry(entries, predicate) {
  const matches = entries.filter(predicate);
  return matches.length === 1 ? matches[0] : null;
}
function matchClaudeModelSignature(entrySignature, intendedSignature, options) {
  if (!entrySignature || entrySignature.family !== intendedSignature.family) {
    return false;
  }
  if (!(options == null ? void 0 : options.ignoreIs1M) && entrySignature.is1M !== intendedSignature.is1M) {
    return false;
  }
  if (intendedSignature.major && entrySignature.major !== intendedSignature.major) {
    return false;
  }
  if (intendedSignature.minor && entrySignature.minor !== intendedSignature.minor) {
    return false;
  }
  if (intendedSignature.date && entrySignature.date !== intendedSignature.date) {
    return false;
  }
  return true;
}
function selectContextWindowEntry(modelUsage, intendedModel) {
  const entries = Object.entries(modelUsage).flatMap(
    ([model, usage]) => typeof (usage == null ? void 0 : usage.contextWindow) === "number" && usage.contextWindow > 0 ? [{ model, contextWindow: usage.contextWindow }] : []
  );
  if (entries.length === 0) {
    return null;
  }
  if (entries.length === 1) {
    return entries[0];
  }
  if (!intendedModel) {
    return null;
  }
  const literalExactMatch = entries.find((entry) => entry.model === intendedModel);
  if (literalExactMatch) {
    return literalExactMatch;
  }
  const normalizedIntendedModel = normalizeClaudeModelId(intendedModel);
  const exactMatch = findUniqueEntry(entries, (entry) => normalizeClaudeModelId(entry.model) === normalizedIntendedModel);
  if (exactMatch) {
    return exactMatch;
  }
  if (!isDefaultClaudeModel(intendedModel)) {
    return null;
  }
  const intendedSignature = parseClaudeModelSignature(intendedModel);
  if (!intendedSignature) {
    return null;
  }
  const strictSignatureMatch = findUniqueEntry(
    entries,
    (entry) => matchClaudeModelSignature(parseClaudeModelSignature(entry.model), intendedSignature)
  );
  if (strictSignatureMatch) {
    return strictSignatureMatch;
  }
  const hasVersionedTarget = Boolean(intendedSignature.major || intendedSignature.date);
  if (!hasVersionedTarget) {
    return null;
  }
  return findUniqueEntry(
    entries,
    (entry) => matchClaudeModelSignature(parseClaudeModelSignature(entry.model), intendedSignature, { ignoreIs1M: true })
  );
}
var EMPTY_PROMPT_USAGE = {
  inputTokens: 0,
  cacheCreationInputTokens: 0,
  cacheReadInputTokens: 0,
  contextTokens: 0
};
function normalizeTokenCount(value) {
  return typeof value === "number" && Number.isFinite(value) && value > 0 ? value : 0;
}
function hasPromptUsageField(usage) {
  if (!usage || typeof usage !== "object" || Array.isArray(usage)) {
    return false;
  }
  const record2 = usage;
  return typeof record2.input_tokens === "number" || typeof record2.cache_creation_input_tokens === "number" || typeof record2.cache_read_input_tokens === "number";
}
function toPromptUsageSnapshot(usage) {
  const inputTokens = normalizeTokenCount(usage.input_tokens);
  const cacheCreationInputTokens = normalizeTokenCount(usage.cache_creation_input_tokens);
  const cacheReadInputTokens = normalizeTokenCount(usage.cache_read_input_tokens);
  return {
    inputTokens,
    cacheCreationInputTokens,
    cacheReadInputTokens,
    contextTokens: inputTokens + cacheCreationInputTokens + cacheReadInputTokens
  };
}
function mergePromptUsage(current, usage) {
  const next = toPromptUsageSnapshot(usage);
  const inputTokens = Math.max(current.inputTokens, next.inputTokens);
  const cacheCreationInputTokens = Math.max(current.cacheCreationInputTokens, next.cacheCreationInputTokens);
  const cacheReadInputTokens = Math.max(current.cacheReadInputTokens, next.cacheReadInputTokens);
  return {
    inputTokens,
    cacheCreationInputTokens,
    cacheReadInputTokens,
    contextTokens: inputTokens + cacheCreationInputTokens + cacheReadInputTokens
  };
}
function samePromptUsage(a2, b10) {
  return a2.inputTokens === b10.inputTokens && a2.cacheCreationInputTokens === b10.cacheCreationInputTokens && a2.cacheReadInputTokens === b10.cacheReadInputTokens && a2.contextTokens === b10.contextTokens;
}
function buildUsageInfo(promptUsage, options) {
  var _a3;
  const model = (_a3 = options == null ? void 0 : options.intendedModel) != null ? _a3 : "sonnet";
  const contextWindow = getContextWindowSize(model, options == null ? void 0 : options.customContextLimits);
  const percentage = Math.min(100, Math.max(0, Math.round(promptUsage.contextTokens / contextWindow * 100)));
  return {
    model,
    inputTokens: promptUsage.inputTokens,
    cacheCreationInputTokens: promptUsage.cacheCreationInputTokens,
    cacheReadInputTokens: promptUsage.cacheReadInputTokens,
    contextWindow,
    contextTokens: promptUsage.contextTokens,
    percentage
  };
}
function createTransformUsageState() {
  let promptUsage = { ...EMPTY_PROMPT_USAGE };
  let lastEmittedPromptUsage = null;
  return {
    clear() {
      promptUsage = { ...EMPTY_PROMPT_USAGE };
      lastEmittedPromptUsage = null;
    },
    mergePromptUsage(usage) {
      promptUsage = mergePromptUsage(promptUsage, usage);
      return promptUsage;
    },
    getPromptUsage() {
      return { ...promptUsage };
    },
    hasEmitted(nextPromptUsage) {
      return lastEmittedPromptUsage !== null && samePromptUsage(lastEmittedPromptUsage, nextPromptUsage);
    },
    markEmitted(nextPromptUsage) {
      lastEmittedPromptUsage = { ...nextPromptUsage };
    }
  };
}
function maybeEmitUsageFromPromptUsage(promptUsage, options, behavior = {}) {
  var _a3, _b2;
  if (promptUsage.contextTokens <= 0) {
    return behavior.emitZeroUsage ? { type: "usage", usage: buildUsageInfo(promptUsage, options) } : null;
  }
  if ((_a3 = options == null ? void 0 : options.usageState) == null ? void 0 : _a3.hasEmitted(promptUsage)) {
    return null;
  }
  (_b2 = options == null ? void 0 : options.usageState) == null ? void 0 : _b2.markEmitted(promptUsage);
  return { type: "usage", usage: buildUsageInfo(promptUsage, options) };
}
function* transformSDKMessage(message, options) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l, _m, _n, _o, _p2, _q, _r, _s, _t, _u;
  switch (message.type) {
    case "system":
      if (message.subtype === "init" && message.session_id) {
        yield {
          type: "session_init",
          sessionId: message.session_id,
          agents: message.agents,
          permissionMode: message.permissionMode
        };
      } else if (message.subtype === "compact_boundary") {
        yield { type: "context_compacted" };
      }
      break;
    case "assistant": {
      const parentToolUseId = (_a3 = message.parent_tool_use_id) != null ? _a3 : null;
      if (message.error) {
        yield { type: "error", content: message.error };
      }
      if (((_b2 = message.message) == null ? void 0 : _b2.content) && Array.isArray(message.message.content)) {
        for (const block of message.message.content) {
          if (block.type === "thinking" && block.thinking) {
            if (parentToolUseId === null) {
              yield { type: "thinking", content: block.thinking };
            }
          } else if (block.type === "text" && block.text && block.text.trim() !== "(no content)") {
            if (parentToolUseId === null) {
              yield { type: "text", content: block.text };
            }
          } else if (block.type === "tool_use") {
            yield emitToolUse(parentToolUseId, {
              id: block.id || `tool-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`,
              name: block.name || "unknown",
              input: getToolInput(block.input)
            });
          }
        }
      }
      (_c = options == null ? void 0 : options.streamState) == null ? void 0 : _c.clearParent(parentToolUseId);
      const usage = (_d2 = message.message) == null ? void 0 : _d2.usage;
      if (parentToolUseId === null && usage) {
        if (options == null ? void 0 : options.usageState) {
          const promptUsage = options.usageState.mergePromptUsage(usage);
          const usageChunk = maybeEmitUsageFromPromptUsage(promptUsage, options, { emitZeroUsage: true });
          if (usageChunk) {
            yield usageChunk;
          }
        } else {
          yield { type: "usage", usage: buildUsageInfo(toPromptUsageSnapshot(usage), options) };
        }
      }
      break;
    }
    case "user": {
      const parentToolUseId = (_e = message.parent_tool_use_id) != null ? _e : null;
      if (isBlockedMessage(message)) {
        yield {
          type: "notice",
          content: message._blockReason,
          level: "warning"
        };
        break;
      }
      if (message.tool_use_result !== void 0 && message.parent_tool_use_id) {
        const toolUseResult = (_f = message.tool_use_result) != null ? _f : void 0;
        yield emitToolResult(parentToolUseId, {
          id: message.parent_tool_use_id,
          content: extractToolResultContent(message.tool_use_result, { fallbackIndent: 2 }),
          isError: false,
          ...toolUseResult !== void 0 ? { toolUseResult } : {}
        });
      }
      if (((_g = message.message) == null ? void 0 : _g.content) && Array.isArray(message.message.content)) {
        for (const block of message.message.content) {
          if (block.type === "tool_result") {
            const toolUseResult = (_h = message.tool_use_result) != null ? _h : void 0;
            yield emitToolResult(parentToolUseId, {
              id: block.tool_use_id || message.parent_tool_use_id || "",
              content: extractToolResultContent(block.content, { fallbackIndent: 2 }),
              isError: block.is_error || false,
              ...toolUseResult !== void 0 ? { toolUseResult } : {}
            });
          }
        }
      }
      break;
    }
    case "stream_event": {
      const parentToolUseId = (_i = message.parent_tool_use_id) != null ? _i : null;
      const event = message.event;
      if (parentToolUseId === null && (event == null ? void 0 : event.type) === "message_start") {
        (_j2 = options == null ? void 0 : options.usageState) == null ? void 0 : _j2.clear();
        const usage = (_k = event.message) == null ? void 0 : _k.usage;
        if (usage && hasPromptUsageField(usage)) {
          if (options == null ? void 0 : options.usageState) {
            options.usageState.mergePromptUsage(usage);
          } else {
            const usageChunk = maybeEmitUsageFromPromptUsage(toPromptUsageSnapshot(usage), options);
            if (usageChunk) {
              yield usageChunk;
            }
          }
        }
      } else if (parentToolUseId === null && (event == null ? void 0 : event.type) === "message_delta" && hasPromptUsageField(event.usage)) {
        if (options == null ? void 0 : options.usageState) {
          const previousPromptUsage = options.usageState.getPromptUsage();
          const promptUsage = options.usageState.mergePromptUsage(event.usage);
          const shouldEmitDeltaUsage = previousPromptUsage.contextTokens <= 0 || options.usageState.hasEmitted(previousPromptUsage);
          if (shouldEmitDeltaUsage) {
            const usageChunk = maybeEmitUsageFromPromptUsage(promptUsage, options);
            if (usageChunk) {
              yield usageChunk;
            }
          }
        } else {
          const usageChunk = maybeEmitUsageFromPromptUsage(toPromptUsageSnapshot(event.usage), options);
          if (usageChunk) {
            yield usageChunk;
          }
        }
      } else if ((event == null ? void 0 : event.type) === "content_block_start" && ((_l = event.content_block) == null ? void 0 : _l.type) === "tool_use") {
        const toolUseFields = {
          id: event.content_block.id || `tool-${Date.now()}`,
          name: event.content_block.name || "unknown",
          input: getToolInput(event.content_block.input)
        };
        if (typeof event.index === "number") {
          (_m = options == null ? void 0 : options.streamState) == null ? void 0 : _m.registerToolUse(parentToolUseId, event.index, toolUseFields);
        }
        yield emitToolUse(parentToolUseId, toolUseFields);
      } else if ((event == null ? void 0 : event.type) === "content_block_start" && ((_n = event.content_block) == null ? void 0 : _n.type) === "thinking") {
        if (parentToolUseId === null && event.content_block.thinking) {
          yield { type: "thinking", content: event.content_block.thinking };
        }
      } else if ((event == null ? void 0 : event.type) === "content_block_start" && ((_o = event.content_block) == null ? void 0 : _o.type) === "text") {
        if (parentToolUseId === null && event.content_block.text) {
          yield { type: "text", content: event.content_block.text };
        }
      } else if ((event == null ? void 0 : event.type) === "content_block_delta") {
        if (((_p2 = event.delta) == null ? void 0 : _p2.type) === "input_json_delta" && typeof event.index === "number") {
          const toolUseFields = (_q = options == null ? void 0 : options.streamState) == null ? void 0 : _q.applyInputJsonDelta(
            parentToolUseId,
            event.index,
            event.delta.partial_json
          );
          if (toolUseFields) {
            yield emitToolUse(parentToolUseId, toolUseFields);
          }
        } else if (parentToolUseId === null && ((_r = event.delta) == null ? void 0 : _r.type) === "thinking_delta" && event.delta.thinking) {
          yield { type: "thinking", content: event.delta.thinking };
        } else if (parentToolUseId === null && ((_s = event.delta) == null ? void 0 : _s.type) === "text_delta" && event.delta.text) {
          yield { type: "text", content: event.delta.text };
        }
      } else if ((event == null ? void 0 : event.type) === "content_block_stop" && typeof event.index === "number") {
        (_t = options == null ? void 0 : options.streamState) == null ? void 0 : _t.clearContentBlock(parentToolUseId, event.index);
      }
      break;
    }
    case "result":
      (_u = options == null ? void 0 : options.streamState) == null ? void 0 : _u.clearAll();
      if (options == null ? void 0 : options.usageState) {
        const usageChunk = maybeEmitUsageFromPromptUsage(options.usageState.getPromptUsage(), options);
        if (usageChunk) {
          yield usageChunk;
        }
        options.usageState.clear();
      }
      if (isResultError(message)) {
        const content = message.errors.filter((e2) => e2.trim().length > 0).join("\n");
        yield {
          type: "error",
          content: content || `Result error: ${message.subtype}`
        };
      }
      if ("modelUsage" in message && message.modelUsage) {
        const modelUsage = message.modelUsage;
        const selectedEntry = selectContextWindowEntry(modelUsage, options == null ? void 0 : options.intendedModel);
        if (selectedEntry) {
          yield { type: "context_window", contextWindow: selectedEntry.contextWindow };
        }
      }
      break;
    default:
      break;
  }
}

// src/core/security/ApprovalManager.ts
function getActionPattern(toolName, input) {
  switch (toolName) {
    case TOOL_BASH:
      return typeof input.command === "string" ? input.command.trim() : "";
    case TOOL_READ:
    case TOOL_WRITE:
    case TOOL_EDIT:
      return typeof input.file_path === "string" && input.file_path ? input.file_path : null;
    case TOOL_NOTEBOOK_EDIT:
      if (typeof input.notebook_path === "string" && input.notebook_path) {
        return input.notebook_path;
      }
      return typeof input.file_path === "string" && input.file_path ? input.file_path : null;
    case TOOL_GLOB:
      return typeof input.pattern === "string" && input.pattern ? input.pattern : null;
    case TOOL_GREP:
      return typeof input.pattern === "string" && input.pattern ? input.pattern : null;
    default:
      return JSON.stringify(input);
  }
}
function getActionDescription(toolName, input) {
  var _a3;
  const pattern = (_a3 = getActionPattern(toolName, input)) != null ? _a3 : "(unknown)";
  switch (toolName) {
    case TOOL_BASH:
      return `Run command: ${pattern}`;
    case TOOL_READ:
      return `Read file: ${pattern}`;
    case TOOL_WRITE:
      return `Write to file: ${pattern}`;
    case TOOL_EDIT:
      return `Edit file: ${pattern}`;
    case TOOL_GLOB:
      return `Search files matching: ${pattern}`;
    case TOOL_GREP:
      return `Search content matching: ${pattern}`;
    default:
      return `${toolName}: ${pattern}`;
  }
}

// src/providers/claude/security/ClaudePermissionUpdates.ts
function buildPermissionUpdates(toolName, input, decision, suggestions) {
  const destination = decision === "allow-always" ? "projectSettings" : "session";
  const processed = [];
  let hasRuleUpdate = false;
  if (suggestions) {
    for (const suggestion of suggestions) {
      if (suggestion.type === "addRules" || suggestion.type === "replaceRules") {
        hasRuleUpdate = true;
        processed.push({ ...suggestion, behavior: "allow", destination });
      } else {
        processed.push(suggestion);
      }
    }
  }
  if (!hasRuleUpdate) {
    const pattern = getActionPattern(toolName, input);
    const ruleValue = { toolName };
    if (pattern && !pattern.startsWith("{")) {
      ruleValue.ruleContent = pattern;
    }
    processed.unshift({
      type: "addRules",
      behavior: "allow",
      rules: [ruleValue],
      destination
    });
  }
  return processed;
}

// src/providers/claude/runtime/ClaudeApprovalHandler.ts
function createClaudeApprovalCallback(deps) {
  return async (toolName, input, options) => {
    const currentAllowedTools = deps.getAllowedTools();
    if (currentAllowedTools !== null) {
      if (!currentAllowedTools.includes(toolName) && toolName !== TOOL_SKILL) {
        const allowedList = currentAllowedTools.length > 0 ? ` Allowed tools: ${currentAllowedTools.join(", ")}.` : " No tools are allowed for this query type.";
        return {
          behavior: "deny",
          message: `Tool "${toolName}" is not allowed for this query.${allowedList}`
        };
      }
    }
    const exitPlanModeCallback = deps.getExitPlanModeCallback();
    if (toolName === TOOL_EXIT_PLAN_MODE && exitPlanModeCallback) {
      try {
        const decision = await exitPlanModeCallback(input, options.signal);
        if (decision === null) {
          return { behavior: "deny", message: "User cancelled.", interrupt: true };
        }
        if (decision.type === "feedback") {
          return { behavior: "deny", message: decision.text, interrupt: false };
        }
        const permissionMode = deps.getPermissionMode();
        const sdkMode = deps.resolveSDKPermissionMode(permissionMode);
        deps.syncPermissionMode(permissionMode, sdkMode);
        return {
          behavior: "allow",
          updatedInput: input,
          updatedPermissions: [
            { type: "setMode", mode: sdkMode, destination: "session" }
          ]
        };
      } catch (error48) {
        return {
          behavior: "deny",
          message: `Failed to handle plan mode exit: ${error48 instanceof Error ? error48.message : "Unknown error"}`,
          interrupt: true
        };
      }
    }
    const askUserQuestionCallback = deps.getAskUserQuestionCallback();
    if (toolName === TOOL_ASK_USER_QUESTION && askUserQuestionCallback) {
      try {
        const answers = await askUserQuestionCallback(input, options.signal);
        if (answers === null) {
          return { behavior: "deny", message: "User declined to answer.", interrupt: true };
        }
        return { behavior: "allow", updatedInput: { ...input, answers } };
      } catch (error48) {
        return {
          behavior: "deny",
          message: `Failed to get user answers: ${error48 instanceof Error ? error48.message : "Unknown error"}`,
          interrupt: true
        };
      }
    }
    const approvalCallback = deps.getApprovalCallback();
    if (!approvalCallback) {
      return { behavior: "deny", message: "No approval handler available." };
    }
    try {
      const { decisionReason, blockedPath, agentID } = options;
      const description = getActionDescription(toolName, input);
      const decision = await approvalCallback(
        toolName,
        input,
        description,
        { decisionReason, blockedPath, agentID }
      );
      if (decision === "cancel") {
        return { behavior: "deny", message: "User interrupted.", interrupt: true };
      }
      if (decision === "allow" || decision === "allow-always") {
        const updatedPermissions = buildPermissionUpdates(
          toolName,
          input,
          decision,
          options.suggestions
        );
        return { behavior: "allow", updatedInput: input, updatedPermissions };
      }
      return { behavior: "deny", message: "User denied this action.", interrupt: false };
    } catch (error48) {
      return {
        behavior: "deny",
        message: `Approval request failed: ${error48 instanceof Error ? error48.message : "Unknown error"}`,
        interrupt: false
      };
    }
  };
}

// src/providers/claude/runtime/ClaudeDynamicUpdates.ts
async function applyClaudeDynamicUpdates(deps, queryOptions, restartOptions, allowRestart = true) {
  var _a3, _b2, _c, _d2, _e;
  const persistentQuery = deps.getPersistentQuery();
  if (!persistentQuery) {
    return;
  }
  const vaultPath = deps.getVaultPath();
  if (!vaultPath) {
    return;
  }
  const cliPath = deps.getCliPath();
  if (!cliPath) {
    return;
  }
  const settings11 = deps.getScopedSettings();
  const selectedModel = (queryOptions == null ? void 0 : queryOptions.model) || settings11.model;
  const permissionMode = deps.getPermissionMode();
  const currentConfig = deps.getCurrentConfig();
  if (currentConfig && selectedModel !== currentConfig.model) {
    try {
      await persistentQuery.setModel(selectedModel);
      deps.mutateCurrentConfig((config2) => {
        config2.model = selectedModel;
      });
    } catch (e2) {
      deps.notifyFailure("Failed to update model");
    }
  }
  const thinkingTokens = resolveThinkingTokens(selectedModel, settings11.thinkingBudget);
  const currentThinking = (_b2 = (_a3 = deps.getCurrentConfig()) == null ? void 0 : _a3.thinkingTokens) != null ? _b2 : null;
  if (thinkingTokens !== currentThinking) {
    try {
      await persistentQuery.setMaxThinkingTokens(thinkingTokens);
      deps.mutateCurrentConfig((config2) => {
        config2.thinkingTokens = thinkingTokens;
      });
    } catch (e2) {
      deps.notifyFailure("Failed to update thinking budget");
    }
  } else {
    deps.mutateCurrentConfig((config2) => {
      config2.thinkingTokens = thinkingTokens;
    });
  }
  const effortLevel = resolveAdaptiveEffortLevel(selectedModel, settings11.effortLevel);
  if (effortLevel !== null) {
    const currentEffort = (_d2 = (_c = deps.getCurrentConfig()) == null ? void 0 : _c.effortLevel) != null ? _d2 : null;
    if (effortLevel !== currentEffort) {
      try {
        await persistentQuery.applyFlagSettings({ effortLevel });
        deps.mutateCurrentConfig((config2) => {
          config2.effortLevel = effortLevel;
        });
      } catch (e2) {
        deps.notifyFailure("Failed to update effort level");
      }
    }
  } else {
    deps.mutateCurrentConfig((config2) => {
      config2.effortLevel = null;
    });
  }
  const configBeforePermissionUpdate = deps.getCurrentConfig();
  if (configBeforePermissionUpdate) {
    const sdkMode = deps.resolveSDKPermissionMode(permissionMode);
    const currentSdkMode = (_e = configBeforePermissionUpdate.sdkPermissionMode) != null ? _e : null;
    const requiresAutoModeRestart = sdkMode === "auto" && !configBeforePermissionUpdate.enableAutoMode;
    if (requiresAutoModeRestart) {
    } else if (sdkMode !== currentSdkMode) {
      try {
        await persistentQuery.setPermissionMode(sdkMode);
        deps.mutateCurrentConfig((config2) => {
          config2.permissionMode = permissionMode;
          config2.sdkPermissionMode = sdkMode;
        });
      } catch (e2) {
        deps.notifyFailure("Failed to update permission mode");
      }
    } else {
      deps.mutateCurrentConfig((config2) => {
        config2.permissionMode = permissionMode;
        config2.sdkPermissionMode = sdkMode;
      });
    }
  }
  const mcpMentions = (queryOptions == null ? void 0 : queryOptions.mcpMentions) || /* @__PURE__ */ new Set();
  const uiEnabledServers = (queryOptions == null ? void 0 : queryOptions.enabledMcpServers) || /* @__PURE__ */ new Set();
  const combinedMentions = /* @__PURE__ */ new Set([...mcpMentions, ...uiEnabledServers]);
  const mcpServers = deps.mcpManager.getActiveServers(combinedMentions);
  const mcpServersKey = JSON.stringify(mcpServers);
  if (deps.getCurrentConfig() && mcpServersKey !== deps.getCurrentConfig().mcpServersKey) {
    const serverConfigs = {};
    for (const [name, config2] of Object.entries(mcpServers)) {
      serverConfigs[name] = config2;
    }
    try {
      await persistentQuery.setMcpServers(serverConfigs);
      deps.mutateCurrentConfig((config2) => {
        config2.mcpServersKey = mcpServersKey;
      });
    } catch (e2) {
      deps.notifyFailure("Failed to update MCP servers");
    }
  }
  const newExternalContextPaths = (queryOptions == null ? void 0 : queryOptions.externalContextPaths) || [];
  deps.setCurrentExternalContextPaths(newExternalContextPaths);
  if (!allowRestart) {
    return;
  }
  const newConfig = deps.buildPersistentQueryConfig(vaultPath, cliPath, newExternalContextPaths);
  if (!deps.needsRestart(newConfig)) {
    return;
  }
  const restarted = await deps.ensureReady({
    externalContextPaths: newExternalContextPaths,
    preserveHandlers: restartOptions == null ? void 0 : restartOptions.preserveHandlers,
    force: true
  });
  if (restarted && deps.getPersistentQuery()) {
    await applyClaudeDynamicUpdates(deps, queryOptions, restartOptions, false);
  }
}

// src/providers/claude/runtime/types.ts
var MESSAGE_CHANNEL_CONFIG = {
  MAX_QUEUED_MESSAGES: 8,
  // Memory protection from rapid user input
  MAX_MERGED_CHARS: 12e3
  // ~3k tokens — batch size under context limits
};
function createResponseHandler(options) {
  let _sawStreamText = false;
  let _sawStreamThinking = false;
  let _sawAnyChunk = false;
  return {
    id: options.id,
    onChunk: options.onChunk,
    onDone: options.onDone,
    onError: options.onError,
    get sawStreamText() {
      return _sawStreamText;
    },
    get sawStreamThinking() {
      return _sawStreamThinking;
    },
    get sawAnyChunk() {
      return _sawAnyChunk;
    },
    markStreamTextSeen() {
      _sawStreamText = true;
    },
    markStreamThinkingSeen() {
      _sawStreamThinking = true;
    },
    resetStreamText() {
      _sawStreamText = false;
    },
    resetStreamThinking() {
      _sawStreamThinking = false;
    },
    markChunkSeen() {
      _sawAnyChunk = true;
    }
  };
}
var UNSUPPORTED_SDK_TOOLS = [];
var DISABLED_BUILTIN_SUBAGENTS = [
  "Task(statusline-setup)"
];
function isTurnCompleteMessage(message) {
  return message.type === "result";
}

// src/providers/claude/runtime/ClaudeMessageChannel.ts
var MessageChannel = class {
  constructor(onWarning = () => {
  }) {
    this.queue = [];
    this.turnActive = false;
    this.closed = false;
    this.resolveNext = null;
    this.currentSessionId = null;
    this.onWarning = onWarning;
  }
  setSessionId(sessionId) {
    this.currentSessionId = sessionId;
  }
  isTurnActive() {
    return this.turnActive;
  }
  isClosed() {
    return this.closed;
  }
  /**
   * Enqueue a message. If a turn is active:
   * - Text-only: merge with queued text (up to MAX_MERGED_CHARS)
   * - With attachments: replace any existing queued attachment (one at a time)
   */
  enqueue(message) {
    if (this.closed) {
      throw new Error("MessageChannel is closed");
    }
    const hasAttachments = this.messageHasAttachments(message);
    if (!this.turnActive) {
      if (this.resolveNext) {
        this.turnActive = true;
        const resolve8 = this.resolveNext;
        this.resolveNext = null;
        resolve8({ value: message, done: false });
      } else {
        if (this.queue.length >= MESSAGE_CHANNEL_CONFIG.MAX_QUEUED_MESSAGES) {
          this.onWarning(`[MessageChannel] Queue full (${MESSAGE_CHANNEL_CONFIG.MAX_QUEUED_MESSAGES}), dropping newest`);
          return;
        }
        if (hasAttachments) {
          this.queue.push({ type: "attachment", message });
        } else {
          this.queue.push({ type: "text", content: this.extractTextContent(message) });
        }
      }
      return;
    }
    if (hasAttachments) {
      const existingIdx = this.queue.findIndex((m2) => m2.type === "attachment");
      if (existingIdx >= 0) {
        this.queue[existingIdx] = { type: "attachment", message };
        this.onWarning("[MessageChannel] Attachment message replaced (only one can be queued)");
      } else {
        this.queue.push({ type: "attachment", message });
      }
      return;
    }
    const textContent = this.extractTextContent(message);
    const existingTextIdx = this.queue.findIndex((m2) => m2.type === "text");
    if (existingTextIdx >= 0) {
      const existing = this.queue[existingTextIdx];
      const mergedContent = existing.content + "\n\n" + textContent;
      if (mergedContent.length > MESSAGE_CHANNEL_CONFIG.MAX_MERGED_CHARS) {
        this.onWarning(`[MessageChannel] Merged content exceeds ${MESSAGE_CHANNEL_CONFIG.MAX_MERGED_CHARS} chars, dropping newest`);
        return;
      }
      existing.content = mergedContent;
    } else {
      if (this.queue.length >= MESSAGE_CHANNEL_CONFIG.MAX_QUEUED_MESSAGES) {
        this.onWarning(`[MessageChannel] Queue full (${MESSAGE_CHANNEL_CONFIG.MAX_QUEUED_MESSAGES}), dropping newest`);
        return;
      }
      this.queue.push({ type: "text", content: textContent });
    }
  }
  onTurnComplete() {
    this.turnActive = false;
    if (this.queue.length > 0 && this.resolveNext) {
      const pending = this.queue.shift();
      this.turnActive = true;
      const resolve8 = this.resolveNext;
      this.resolveNext = null;
      resolve8({ value: this.pendingToMessage(pending), done: false });
    }
  }
  close() {
    this.closed = true;
    this.queue = [];
    if (this.resolveNext) {
      const resolve8 = this.resolveNext;
      this.resolveNext = null;
      resolve8({ value: void 0, done: true });
    }
  }
  reset() {
    this.queue = [];
    this.turnActive = false;
    this.closed = false;
    this.resolveNext = null;
  }
  getQueueLength() {
    return this.queue.length;
  }
  [Symbol.asyncIterator]() {
    return {
      next: () => {
        if (this.closed) {
          return Promise.resolve({ value: void 0, done: true });
        }
        if (this.queue.length > 0 && !this.turnActive) {
          const pending = this.queue.shift();
          this.turnActive = true;
          return Promise.resolve({ value: this.pendingToMessage(pending), done: false });
        }
        return new Promise((resolve8) => {
          this.resolveNext = resolve8;
        });
      }
    };
  }
  messageHasAttachments(message) {
    var _a3;
    if (!((_a3 = message.message) == null ? void 0 : _a3.content)) return false;
    if (typeof message.message.content === "string") return false;
    return message.message.content.some((block) => block.type === "image");
  }
  extractTextContent(message) {
    var _a3;
    if (!((_a3 = message.message) == null ? void 0 : _a3.content)) return "";
    if (typeof message.message.content === "string") return message.message.content;
    return message.message.content.filter((block) => block.type === "text").map((block) => block.text).join("\n\n");
  }
  pendingToMessage(pending) {
    if (pending.type === "attachment") {
      return pending.message;
    }
    return {
      type: "user",
      message: {
        role: "user",
        content: pending.content
      },
      parent_tool_use_id: null,
      session_id: this.currentSessionId || ""
    };
  }
};

// src/core/prompt/mainAgent.ts
function getPathRules(vaultPath) {
  return `## Path Conventions

| Location | Access | Path Format | Example |
|----------|--------|-------------|---------|
| **Vault** | Read/Write | Relative from vault root | \`notes/my-note.md\`, \`.\` |
| **External contexts** | Full access | Absolute path | \`/Users/me/Workspace/file.ts\` |

**Vault files** (default working directory):
- \u2713 Correct: \`notes/my-note.md\`, \`my-note.md\`, \`folder/subfolder/file.md\`, \`.\`
- \u2717 WRONG: \`/notes/my-note.md\`, \`${vaultPath || "/absolute/path"}/file.md\`
- A leading slash or absolute path will FAIL for vault operations.

**External context paths**: When external directories are selected, use absolute paths to access files there. These directories are explicitly granted for the current session.`;
}
function getBaseSystemPrompt(vaultPath, userName) {
  const vaultInfo = vaultPath ? `

Vault absolute path: ${vaultPath}` : "";
  const trimmedUserName = userName == null ? void 0 : userName.trim();
  const userContext = trimmedUserName ? `## User Context

You are collaborating with **${trimmedUserName}**.

` : "";
  const pathRules = getPathRules(vaultPath);
  return `${userContext}## Time Context

- **Current Date**: Use \`bash: date\` to get the current date and time. Never guess or assume.
- **Knowledge Status**: You possess extensive internal knowledge up to your training cutoff. You do not know the exact date of your cutoff, but you must assume that your internal weights are static and "past," while the Current Date is "present."

## Identity & Role

You are **Claudian**, an expert AI assistant specialized in Obsidian vault management, knowledge organization, and code analysis. You operate directly inside the user's Obsidian vault.

**Core Principles:**
1.  **Obsidian Native**: You understand Markdown, YAML frontmatter, Wiki-links, and the "second brain" philosophy.
2.  **Safety First**: You never overwrite data without understanding context. You always use relative paths.
3.  **Proactive Thinking**: You do not just execute; you *plan* and *verify*. You anticipate potential issues (like broken links or missing files).
4.  **Clarity**: Your changes are precise, minimizing "noise" in the user's notes or code.

The current working directory is the user's vault root.${vaultInfo}

${pathRules}

## User Message Format

User messages have the query first, followed by optional XML context tags:

\`\`\`
User's question or request here

<current_note>
path/to/note.md
</current_note>

<editor_selection path="path/to/note.md" lines="10-15">
selected text content
</editor_selection>

<browser_selection source="browser:https://leetcode.com/problems/two-sum" title="LeetCode" url="https://leetcode.com/problems/two-sum">
selected content from an Obsidian browser view
</browser_selection>
\`\`\`

- The user's query/instruction always comes first in the message.
- \`<current_note>\`: The note the user is currently viewing/focused on. Read this to understand context.
- \`<editor_selection>\`: Text currently selected in the editor, with file path and line numbers.
- \`<browser_selection>\`: Text selected in an Obsidian browser/web view (for example Surfing), including optional source/title/url metadata.
- \`@filename.md\`: Files mentioned with @ in the query. Read these files when referenced.

## Obsidian Context

- **Structure**: Files are Markdown (.md). Folders organize content.
- **Frontmatter**: YAML at the top of files (metadata). Respect existing fields.
- **Links**: Internal Wiki-links \`[[note-name]]\` or \`[[folder/note-name]]\`. External links \`[text](url)\`.
  - When reading a note with wikilinks, consider reading linked notes; they often contain related context that helps understand the current note.
- **Tags**: #tag-name for categorization.
- **Dataview**: You may encounter Dataview queries (in \`\`\`dataview\`\`\` blocks). Do not break them unless asked.
- **Vault Config**: \`.obsidian/\` contains internal config. Touch only if you know what you are doing.

**File References in Responses:**
When mentioning vault files in your responses, use wikilink format so users can click to open them:
- \u2713 Use: \`[[folder/note.md]]\` or \`[[note]]\`
- \u2717 Avoid: plain paths like \`folder/note.md\` (not clickable)

**Image embeds:** Use \`![[image.png]]\` to display images directly in chat. Images render visually, making it easy to show diagrams, screenshots, or visual content you're discussing.

Examples:
- "I found your notes in [[30.areas/finance/Investment lessons/2024.Current trading lessons.md]]"
- "See [[daily notes/2024-01-15]] for more details"
- "Here's the diagram: ![[attachments/architecture.png]]"

## Selection Context

User messages may include an \`<editor_selection>\` tag showing text the user selected:

\`\`\`xml
<editor_selection path="path/to/file.md" lines="line numbers">
selected text here
possibly multiple lines
</editor_selection>
\`\`\`

User messages may also include a \`<browser_selection>\` tag when selection comes from an Obsidian browser view:

\`\`\`xml
<browser_selection source="browser:https://leetcode.com/problems/two-sum" title="LeetCode" url="https://leetcode.com/problems/two-sum">
selected webpage content
</browser_selection>
\`\`\`

**When present:** The user selected this text before sending their message. Use this context to understand what they're referring to.`;
}
function getImageInstructions(mediaFolder) {
  const folder = mediaFolder.trim();
  const mediaPath = folder ? `./${folder}` : ".";
  const examplePath = folder ? `${folder}/` : "";
  return `

## Embedded Images in Notes

**Proactive image reading**: When reading a note with embedded images, read them alongside text for full context. Images often contain critical information (diagrams, screenshots, charts).

**Local images** (\`![[image.jpg]]\`):
- Located in media folder: \`${mediaPath}\`
- Read with: \`Read file_path="${examplePath}image.jpg"\`
- Formats: PNG, JPG/JPEG, GIF, WebP

**External images** (\`![alt](url)\`):
- WebFetch does NOT support images
- Download to media folder -> Read -> Replace URL with wiki-link:

\`\`\`bash
# Download to media folder with descriptive name
mkdir -p ${mediaPath}
img_name="downloaded_\\$(date +%s).png"
curl -sfo "${examplePath}$img_name" 'URL'
\`\`\`

Then read with \`Read file_path="${examplePath}$img_name"\`, and replace the markdown link \`![alt](url)\` with \`![[${examplePath}$img_name]]\` in the note.

**Benefits**: Image becomes a permanent vault asset, works offline, and uses Obsidian's native embed syntax.`;
}
function getAppendixSections(appendices) {
  if (!appendices || appendices.length === 0) {
    return "";
  }
  const sections = appendices.map((appendix) => appendix.trim()).filter(Boolean);
  if (sections.length === 0) {
    return "";
  }
  return `

${sections.join("\n\n")}`;
}
function buildSystemPrompt(settings11 = {}, options = {}) {
  var _a3;
  let prompt = getBaseSystemPrompt(settings11.vaultPath, settings11.userName);
  prompt += getImageInstructions(settings11.mediaFolder || "");
  prompt += getAppendixSections(options.appendices);
  if ((_a3 = settings11.customPrompt) == null ? void 0 : _a3.trim()) {
    prompt += `

## Custom Instructions

${settings11.customPrompt.trim()}`;
  }
  return prompt;
}
function computeSystemPromptKey(settings11, options = {}) {
  const appendixKey = (options.appendices || []).map((appendix) => appendix.trim()).filter(Boolean).join("||");
  const parts = [
    settings11.mediaFolder || "",
    settings11.customPrompt || "",
    settings11.vaultPath || "",
    (settings11.userName || "").trim()
  ];
  if (appendixKey) {
    parts.push(appendixKey);
  }
  return parts.join("::");
}

// src/providers/claude/runtime/ClaudeQueryOptionsBuilder.ts
var QueryOptionsBuilder = class _QueryOptionsBuilder {
  static needsRestart(currentConfig, newConfig) {
    if (!currentConfig) return true;
    if (currentConfig.systemPromptKey !== newConfig.systemPromptKey) return true;
    if (currentConfig.disallowedToolsKey !== newConfig.disallowedToolsKey) return true;
    if (currentConfig.pluginsKey !== newConfig.pluginsKey) return true;
    if (currentConfig.settingSources !== newConfig.settingSources) return true;
    if (currentConfig.claudeCliPath !== newConfig.claudeCliPath) return true;
    if (currentConfig.enableChrome !== newConfig.enableChrome) return true;
    if (currentConfig.enableAutoMode !== newConfig.enableAutoMode) return true;
    if (_QueryOptionsBuilder.pathsChanged(currentConfig.externalContextPaths, newConfig.externalContextPaths)) {
      return true;
    }
    return false;
  }
  static buildPersistentQueryConfig(ctx, externalContextPaths) {
    const claudeSettings = getClaudeProviderSettings(ctx.settings);
    const systemPromptSettings = {
      mediaFolder: ctx.settings.mediaFolder,
      customPrompt: ctx.settings.systemPrompt,
      vaultPath: ctx.vaultPath,
      userName: ctx.settings.userName
    };
    const sdkPermissionMode = _QueryOptionsBuilder.resolveClaudeSdkPermissionMode(
      ctx.settings.permissionMode,
      claudeSettings.safeMode
    );
    const disallowedToolsKey = ctx.mcpManager.getAllDisallowedMcpTools().join("|");
    const pluginsKey = ctx.pluginManager.getPluginsKey();
    return {
      model: ctx.settings.model,
      thinkingTokens: resolveThinkingTokens(ctx.settings.model, ctx.settings.thinkingBudget),
      effortLevel: resolveAdaptiveEffortLevel(ctx.settings.model, ctx.settings.effortLevel),
      permissionMode: ctx.settings.permissionMode,
      sdkPermissionMode,
      systemPromptKey: computeSystemPromptKey(systemPromptSettings),
      disallowedToolsKey,
      mcpServersKey: "",
      // Dynamic via setMcpServers, not tracked for restart
      pluginsKey,
      externalContextPaths: externalContextPaths || [],
      settingSources: claudeSettings.loadUserSettings ? "user,project" : "project",
      claudeCliPath: ctx.cliPath,
      enableChrome: claudeSettings.enableChrome,
      enableAutoMode: claudeSettings.safeMode === "auto"
    };
  }
  static buildPersistentQueryOptions(ctx) {
    const { options, claudeSettings } = _QueryOptionsBuilder.buildBaseOptions(
      ctx,
      ctx.settings.model,
      ctx.abortController
    );
    options.disallowedTools = [
      ...ctx.mcpManager.getAllDisallowedMcpTools(),
      ...UNSUPPORTED_SDK_TOOLS,
      ...DISABLED_BUILTIN_SUBAGENTS
    ];
    _QueryOptionsBuilder.applyPermissionMode(
      options,
      ctx.settings.permissionMode,
      claudeSettings.safeMode,
      ctx.canUseTool
    );
    _QueryOptionsBuilder.applyThinking(options, ctx.settings, ctx.settings.model);
    options.hooks = ctx.hooks;
    options.enableFileCheckpointing = true;
    if (ctx.resume) {
      options.resume = ctx.resume.sessionId;
      if (ctx.resume.sessionAt) {
        options.resumeSessionAt = ctx.resume.sessionAt;
      }
      if (ctx.resume.fork) {
        options.forkSession = true;
      }
    }
    if (ctx.externalContextPaths && ctx.externalContextPaths.length > 0) {
      options.additionalDirectories = ctx.externalContextPaths;
    }
    return options;
  }
  static buildColdStartQueryOptions(ctx) {
    var _a3, _b2;
    const selectedModel = (_a3 = ctx.modelOverride) != null ? _a3 : ctx.settings.model;
    const { options, claudeSettings } = _QueryOptionsBuilder.buildBaseOptions(
      ctx,
      selectedModel,
      ctx.abortController
    );
    const mcpMentions = ctx.mcpMentions || /* @__PURE__ */ new Set();
    const uiEnabledServers = ctx.enabledMcpServers || /* @__PURE__ */ new Set();
    const combinedMentions = /* @__PURE__ */ new Set([...mcpMentions, ...uiEnabledServers]);
    const mcpServers = ctx.mcpManager.getActiveServers(combinedMentions);
    if (Object.keys(mcpServers).length > 0) {
      options.mcpServers = mcpServers;
    }
    const disallowedMcpTools = ctx.mcpManager.getDisallowedMcpTools(combinedMentions);
    options.disallowedTools = [
      ...disallowedMcpTools,
      ...UNSUPPORTED_SDK_TOOLS,
      ...DISABLED_BUILTIN_SUBAGENTS
    ];
    _QueryOptionsBuilder.applyPermissionMode(
      options,
      ctx.settings.permissionMode,
      claudeSettings.safeMode,
      ctx.canUseTool
    );
    options.hooks = ctx.hooks;
    _QueryOptionsBuilder.applyThinking(options, ctx.settings, (_b2 = ctx.modelOverride) != null ? _b2 : ctx.settings.model);
    if (ctx.allowedTools !== void 0 && ctx.allowedTools.length > 0) {
      options.tools = ctx.allowedTools;
    }
    if (ctx.sessionId) {
      options.resume = ctx.sessionId;
    }
    if (ctx.externalContextPaths && ctx.externalContextPaths.length > 0) {
      options.additionalDirectories = ctx.externalContextPaths;
    }
    return options;
  }
  static resolveClaudeSdkPermissionMode(permissionMode, claudeSafeMode = "acceptEdits") {
    if (permissionMode === "yolo") return "bypassPermissions";
    if (permissionMode === "plan") return "plan";
    return claudeSafeMode;
  }
  static applyPermissionMode(options, permissionMode, claudeSafeMode, canUseTool) {
    options.allowDangerouslySkipPermissions = true;
    if (canUseTool) {
      options.canUseTool = canUseTool;
    }
    options.permissionMode = _QueryOptionsBuilder.resolveClaudeSdkPermissionMode(
      permissionMode,
      claudeSafeMode
    );
  }
  static applyExtraArgs(options, settings11) {
    if (settings11.safeMode === "auto") {
      options.extraArgs = { ...options.extraArgs, "enable-auto-mode": null };
    }
    if (settings11.enableChrome) {
      options.extraArgs = { ...options.extraArgs, chrome: null };
    }
  }
  static buildBaseOptions(ctx, model, abortController) {
    const claudeSettings = getClaudeProviderSettings(ctx.settings);
    const systemPromptSettings = {
      mediaFolder: ctx.settings.mediaFolder,
      customPrompt: ctx.settings.systemPrompt,
      vaultPath: ctx.vaultPath,
      userName: ctx.settings.userName
    };
    const options = {
      cwd: ctx.vaultPath,
      systemPrompt: buildSystemPrompt(systemPromptSettings),
      model,
      abortController,
      pathToClaudeCodeExecutable: ctx.cliPath,
      settingSources: claudeSettings.loadUserSettings ? ["user", "project"] : ["project"],
      env: {
        ...process.env,
        ...ctx.customEnv,
        PATH: ctx.enhancedPath
      },
      includePartialMessages: true
    };
    _QueryOptionsBuilder.applyExtraArgs(options, claudeSettings);
    options.spawnClaudeCodeProcess = createCustomSpawnFunction(ctx.enhancedPath);
    return { options, claudeSettings };
  }
  static applyThinking(options, settings11, model) {
    const effortLevel = resolveAdaptiveEffortLevel(model, settings11.effortLevel);
    if (effortLevel !== null) {
      options.thinking = { type: "adaptive" };
      options.effort = effortLevel;
      return;
    }
    const thinkingTokens = resolveThinkingTokens(model, settings11.thinkingBudget);
    if (thinkingTokens !== null) {
      options.maxThinkingTokens = thinkingTokens;
    }
  }
  static pathsChanged(a2, b10) {
    const aKey = [...a2 || []].sort().join("|");
    const bKey = [...b10 || []].sort().join("|");
    return aKey !== bKey;
  }
};

// src/providers/claude/runtime/ClaudeRewindService.ts
var fs11 = __toESM(require("fs/promises"));
var os8 = __toESM(require("os"));
var path9 = __toESM(require("path"));
function resolveRewindFilePath(filePath, vaultPath) {
  if (path9.isAbsolute(filePath)) {
    return filePath;
  }
  if (vaultPath) {
    return path9.join(vaultPath, filePath);
  }
  return filePath;
}
async function copyDir(from, to) {
  await fs11.mkdir(to, { recursive: true });
  const dirents = await fs11.readdir(from, { withFileTypes: true });
  for (const dirent of dirents) {
    const srcPath = path9.join(from, dirent.name);
    const destPath = path9.join(to, dirent.name);
    if (dirent.isDirectory()) {
      await copyDir(srcPath, destPath);
      continue;
    }
    if (dirent.isSymbolicLink()) {
      const target = await fs11.readlink(srcPath);
      await fs11.symlink(target, destPath);
      continue;
    }
    if (dirent.isFile()) {
      await fs11.copyFile(srcPath, destPath);
    }
  }
}
async function createClaudeRewindBackup(filesChanged, vaultPath) {
  if (!filesChanged || filesChanged.length === 0) {
    return null;
  }
  const backupRoot = await fs11.mkdtemp(path9.join(os8.tmpdir(), "claudian-rewind-"));
  const entries = [];
  const backupPathForIndex = (index) => path9.join(backupRoot, String(index));
  for (let i2 = 0; i2 < filesChanged.length; i2++) {
    const originalPath = resolveRewindFilePath(filesChanged[i2], vaultPath);
    try {
      const stats = await fs11.lstat(originalPath);
      if (stats.isSymbolicLink()) {
        const target = await fs11.readlink(originalPath);
        entries.push({ originalPath, existedBefore: true, kind: "symlink", symlinkTarget: target });
        continue;
      }
      const backupPath = backupPathForIndex(i2);
      if (stats.isDirectory()) {
        await copyDir(originalPath, backupPath);
        entries.push({ originalPath, existedBefore: true, kind: "dir", backupPath });
        continue;
      }
      if (stats.isFile()) {
        await fs11.copyFile(originalPath, backupPath);
        entries.push({ originalPath, existedBefore: true, kind: "file", backupPath });
        continue;
      }
      entries.push({ originalPath, existedBefore: false });
    } catch (error48) {
      const err = error48;
      if (err.code === "ENOENT") {
        entries.push({ originalPath, existedBefore: false });
        continue;
      }
      await fs11.rm(backupRoot, { recursive: true, force: true });
      throw error48;
    }
  }
  const restore = async () => {
    const errors = [];
    for (const entry of entries) {
      try {
        if (!entry.existedBefore) {
          await fs11.rm(entry.originalPath, { recursive: true, force: true });
          continue;
        }
        await fs11.rm(entry.originalPath, { recursive: true, force: true });
        await fs11.mkdir(path9.dirname(entry.originalPath), { recursive: true });
        if (entry.kind === "symlink") {
          await fs11.symlink(entry.symlinkTarget, entry.originalPath);
          continue;
        }
        if (entry.kind === "dir") {
          await copyDir(entry.backupPath, entry.originalPath);
          continue;
        }
        await fs11.copyFile(entry.backupPath, entry.originalPath);
      } catch (error48) {
        errors.push(error48);
      }
    }
    if (errors.length > 0) {
      throw new Error(`Failed to restore ${errors.length} file(s) after rewind failure.`);
    }
  };
  const cleanup = async () => {
    await fs11.rm(backupRoot, { recursive: true, force: true });
  };
  return { restore, cleanup };
}
async function executeClaudeRewind(userMessageId, deps) {
  const preview = await deps.rewindFiles(userMessageId, true);
  if (!preview.canRewind) {
    return preview;
  }
  const backup = await createClaudeRewindBackup(preview.filesChanged, deps.vaultPath);
  try {
    const result = await deps.rewindFiles(userMessageId);
    if (!result.canRewind) {
      await (backup == null ? void 0 : backup.restore());
      deps.closePersistentQuery("rewind failed");
      return result;
    }
    deps.setPendingResumeAt(deps.assistantMessageId);
    deps.closePersistentQuery("rewind");
    return {
      ...result,
      filesChanged: preview.filesChanged,
      insertions: preview.insertions,
      deletions: preview.deletions
    };
  } catch (error48) {
    try {
      await (backup == null ? void 0 : backup.restore());
    } catch (rollbackError) {
      deps.closePersistentQuery("rewind failed");
      throw new Error(
        `Rewind failed and files could not be fully restored: ${rollbackError instanceof Error ? rollbackError.message : "Unknown error"}`,
        { cause: rollbackError }
      );
    }
    deps.closePersistentQuery("rewind failed");
    throw new Error(
      `Rewind failed but files were restored: ${error48 instanceof Error ? error48.message : "Unknown error"}`,
      { cause: error48 }
    );
  } finally {
    await (backup == null ? void 0 : backup.cleanup());
  }
}

// src/providers/claude/runtime/ClaudeSessionManager.ts
var SessionManager = class {
  constructor() {
    this.state = {
      sessionId: null,
      sessionModel: null,
      pendingSessionModel: null,
      wasInterrupted: false,
      needsHistoryRebuild: false,
      sessionInvalidated: false
    };
  }
  getSessionId() {
    return this.state.sessionId;
  }
  setSessionId(id, defaultModel) {
    this.state.sessionId = id;
    this.state.sessionModel = id ? defaultModel != null ? defaultModel : null : null;
    this.state.needsHistoryRebuild = false;
    this.state.sessionInvalidated = false;
  }
  wasInterrupted() {
    return this.state.wasInterrupted;
  }
  markInterrupted() {
    this.state.wasInterrupted = true;
  }
  clearInterrupted() {
    this.state.wasInterrupted = false;
  }
  setPendingModel(model) {
    this.state.pendingSessionModel = model;
  }
  clearPendingModel() {
    this.state.pendingSessionModel = null;
  }
  captureSession(sessionId) {
    const hadSession = this.state.sessionId !== null;
    const isDifferent = this.state.sessionId !== sessionId;
    if (hadSession && isDifferent) {
      this.state.needsHistoryRebuild = true;
    }
    this.state.sessionId = sessionId;
    this.state.sessionModel = this.state.pendingSessionModel;
    this.state.pendingSessionModel = null;
    this.state.sessionInvalidated = false;
  }
  needsHistoryRebuild() {
    return this.state.needsHistoryRebuild;
  }
  clearHistoryRebuild() {
    this.state.needsHistoryRebuild = false;
  }
  invalidateSession() {
    this.state.sessionId = null;
    this.state.sessionModel = null;
    this.state.sessionInvalidated = true;
  }
  /** Consume the invalidation flag (returns true once). */
  consumeInvalidation() {
    const wasInvalidated = this.state.sessionInvalidated;
    this.state.sessionInvalidated = false;
    return wasInvalidated;
  }
  reset() {
    this.state = {
      sessionId: null,
      sessionModel: null,
      pendingSessionModel: null,
      wasInterrupted: false,
      needsHistoryRebuild: false,
      sessionInvalidated: false
    };
  }
};

// src/providers/claude/runtime/ClaudeUserMessageFactory.ts
var import_crypto6 = require("crypto");
function buildUserContentBlocks(prompt, images) {
  const content = [];
  for (const image of images != null ? images : []) {
    content.push({
      type: "image",
      source: {
        type: "base64",
        media_type: image.mediaType,
        data: image.data
      }
    });
  }
  if (prompt.trim()) {
    content.push({
      type: "text",
      text: prompt
    });
  }
  return content;
}
function buildClaudeSDKUserMessage(prompt, sessionId, images) {
  if (!images || images.length === 0) {
    return {
      type: "user",
      message: {
        role: "user",
        content: prompt
      },
      parent_tool_use_id: null,
      session_id: sessionId,
      uuid: (0, import_crypto6.randomUUID)()
    };
  }
  return {
    type: "user",
    message: {
      role: "user",
      content: buildUserContentBlocks(prompt, images)
    },
    parent_tool_use_id: null,
    session_id: sessionId,
    uuid: (0, import_crypto6.randomUUID)()
  };
}
function buildClaudePromptWithImages(prompt, images) {
  if (!images || images.length === 0) {
    return prompt;
  }
  const content = buildUserContentBlocks(prompt, images);
  async function* messageGenerator() {
    yield {
      type: "user",
      message: {
        role: "user",
        content
      }
    };
  }
  return messageGenerator();
}

// src/providers/claude/runtime/ClaudeChatRuntime.ts
function isChatMessageArray(value) {
  return Array.isArray(value) && value.length > 0 && !!value[0] && typeof value[0] === "object" && "role" in value[0] && "content" in value[0];
}
function isImageAttachmentArray(value) {
  return Array.isArray(value) && value.length > 0 && !!value[0] && typeof value[0] === "object" && "mediaType" in value[0] && "data" in value[0];
}
var ClaudianService = class {
  constructor(plugin, services) {
    this.providerId = CLAUDE_PROVIDER_CAPABILITIES.providerId;
    this.abortController = null;
    this.approvalCallback = null;
    this.approvalDismisser = null;
    this.askUserQuestionCallback = null;
    this.exitPlanModeCallback = null;
    this.permissionModeSyncCallback = null;
    this.vaultPath = null;
    this.currentExternalContextPaths = [];
    this.readyStateListeners = /* @__PURE__ */ new Set();
    // Modular components
    this.sessionManager = new SessionManager();
    this.persistentQuery = null;
    this.messageChannel = null;
    this.queryAbortController = null;
    this.responseHandlers = [];
    this.responseConsumerRunning = false;
    this.responseConsumerPromise = null;
    this.shuttingDown = false;
    // Tracked configuration for detecting changes that require restart
    this.currentConfig = null;
    // Current allowed tools for canUseTool enforcement (null = no restriction)
    this.currentAllowedTools = null;
    this.pendingForkSession = false;
    // Last sent message for crash recovery (Phase 1.3)
    this.lastSentMessage = null;
    this.lastSentQueryOptions = null;
    this.crashRecoveryAttempted = false;
    this.coldStartInProgress = false;
    // Prevent consumer error restarts during cold-start
    // SDK command cache — populated on system/init, cleared on persistent query close
    this.cachedSdkCommands = [];
    // Subagent hook state provider (set from feature layer to avoid core→feature dependency)
    this._subagentStateProvider = null;
    // Auto-triggered turn handling (e.g., task-notification delivery by the SDK)
    this._autoTurnBuffer = [];
    this._autoTurnSawStreamText = false;
    this._autoTurnSawStreamThinking = false;
    this._autoTurnCallback = null;
    this.turnMetadata = {};
    this.bufferedUsageChunk = null;
    this.streamTransformState = createTransformStreamState();
    this.usageTransformState = createTransformUsageState();
    var _a3, _b2, _c, _d2, _e, _f;
    this.plugin = plugin;
    const legacyPlugin = this.getLegacyPluginDeps();
    if ("mcpManager" in services) {
      this.mcpManager = services.mcpManager;
      this.pluginManager = (_b2 = (_a3 = services.pluginManager) != null ? _a3 : legacyPlugin.pluginManager) != null ? _b2 : null;
      this.agentManager = (_d2 = (_c = services.agentManager) != null ? _c : legacyPlugin.agentManager) != null ? _d2 : null;
      return;
    }
    this.mcpManager = services;
    this.pluginManager = (_e = legacyPlugin.pluginManager) != null ? _e : null;
    this.agentManager = (_f = legacyPlugin.agentManager) != null ? _f : null;
  }
  getLegacyPluginDeps() {
    return this.plugin;
  }
  getCapabilities() {
    return CLAUDE_PROVIDER_CAPABILITIES;
  }
  prepareTurn(request) {
    return encodeClaudeTurn(request, this.mcpManager);
  }
  consumeTurnMetadata() {
    const metadata = { ...this.turnMetadata };
    this.turnMetadata = {};
    this.bufferedUsageChunk = null;
    return metadata;
  }
  onReadyStateChange(listener) {
    this.readyStateListeners.add(listener);
    try {
      listener(this.isReady());
    } catch (e2) {
    }
    return () => {
      this.readyStateListeners.delete(listener);
    };
  }
  notifyReadyStateChange() {
    if (this.readyStateListeners.size === 0) {
      return;
    }
    const isReady = this.isReady();
    for (const listener of this.readyStateListeners) {
      try {
        listener(isReady);
      } catch (e2) {
      }
    }
  }
  resetTurnMetadata() {
    this.turnMetadata = {};
    this.bufferedUsageChunk = null;
    this.usageTransformState.clear();
  }
  recordTurnMetadata(update) {
    this.turnMetadata = {
      ...this.turnMetadata,
      ...update
    };
  }
  bufferUsageChunk(chunk) {
    this.bufferedUsageChunk = chunk;
    return chunk;
  }
  updateBufferedUsageContextWindow(contextWindow) {
    if (!this.bufferedUsageChunk || contextWindow <= 0) {
      return null;
    }
    const usage = this.bufferedUsageChunk.usage;
    const percentage = Math.min(
      100,
      Math.max(0, Math.round(usage.contextTokens / contextWindow * 100))
    );
    const nextChunk = {
      ...this.bufferedUsageChunk,
      usage: {
        ...usage,
        contextWindow,
        contextWindowIsAuthoritative: true,
        percentage
      }
    };
    this.bufferedUsageChunk = nextChunk;
    return nextChunk;
  }
  setPendingResumeAt(uuid3) {
    this.pendingResumeAt = uuid3;
  }
  setResumeCheckpoint(checkpointId) {
    this.setPendingResumeAt(checkpointId);
  }
  /** One-shot: consumed on the next query, then cleared by routeMessage on session init. */
  applyForkState(conv) {
    var _a3, _b2, _c;
    const state = getClaudeState(conv.providerState);
    const isPending = !conv.sessionId && !state.providerSessionId && !!state.forkSource;
    this.pendingForkSession = isPending;
    if (isPending) {
      this.pendingResumeAt = state.forkSource.resumeAt;
    } else {
      this.pendingResumeAt = void 0;
    }
    return (_c = (_b2 = conv.sessionId) != null ? _b2 : (_a3 = state.forkSource) == null ? void 0 : _a3.sessionId) != null ? _c : null;
  }
  syncConversationState(conversation, externalContextPaths) {
    if (!conversation) {
      this.pendingForkSession = false;
      this.pendingResumeAt = void 0;
      this.setSessionId(null, externalContextPaths);
      return;
    }
    const resolvedSessionId = this.applyForkState(conversation);
    this.setSessionId(resolvedSessionId, externalContextPaths);
  }
  buildSessionUpdates({ conversation, sessionInvalidated }) {
    var _a3, _b2;
    const sessionId = this.getSessionId();
    const existingState = getClaudeState(conversation == null ? void 0 : conversation.providerState);
    const oldSdkSessionId = existingState.providerSessionId;
    const sessionChanged = sessionId && oldSdkSessionId && sessionId !== oldSdkSessionId;
    const previousProviderSessionIds = sessionChanged ? [.../* @__PURE__ */ new Set([...existingState.previousProviderSessionIds || [], oldSdkSessionId])] : existingState.previousProviderSessionIds;
    const isForkSourceOnly = !!existingState.forkSource && !existingState.providerSessionId && sessionId === existingState.forkSource.sessionId;
    let resolvedSessionId;
    if (sessionInvalidated) {
      resolvedSessionId = null;
    } else if (isForkSourceOnly) {
      resolvedSessionId = (_a3 = conversation == null ? void 0 : conversation.sessionId) != null ? _a3 : null;
    } else {
      resolvedSessionId = (_b2 = sessionId != null ? sessionId : conversation == null ? void 0 : conversation.sessionId) != null ? _b2 : null;
    }
    const newProviderState = {
      ...existingState,
      providerSessionId: sessionId && !isForkSourceOnly ? sessionId : existingState.providerSessionId,
      previousProviderSessionIds
    };
    if (existingState.forkSource && sessionId && sessionId !== existingState.forkSource.sessionId) {
      delete newProviderState.forkSource;
    }
    return {
      updates: {
        sessionId: resolvedSessionId,
        providerState: newProviderState
      }
    };
  }
  resolveSessionIdForFork(conversation) {
    var _a3, _b2, _c, _d2;
    const sessionId = this.getSessionId();
    if (sessionId) return sessionId;
    if (!conversation) return null;
    const state = getClaudeState(conversation.providerState);
    return (_d2 = (_c = (_a3 = state.providerSessionId) != null ? _a3 : conversation.sessionId) != null ? _c : (_b2 = state.forkSource) == null ? void 0 : _b2.sessionId) != null ? _d2 : null;
  }
  async loadSubagentToolCalls(agentId) {
    const sessionId = this.getSessionId();
    const vaultPath = getVaultPath(this.plugin.app);
    if (!sessionId || !vaultPath) return [];
    return loadSubagentToolCalls(vaultPath, sessionId, agentId);
  }
  async loadSubagentFinalResult(agentId) {
    const sessionId = this.getSessionId();
    const vaultPath = getVaultPath(this.plugin.app);
    if (!sessionId || !vaultPath) return null;
    return loadSubagentFinalResult(vaultPath, sessionId, agentId);
  }
  async reloadMcpServers() {
    await this.mcpManager.loadServers();
  }
  /**
   * Ensures the persistent query is running with current configuration.
   * Unified API that replaces preWarm() and restartPersistentQuery().
   *
   * Behavior:
   * - If not running → start (if paths available)
   * - If running and force=true → close and restart
   * - If running and config changed → close and restart
   * - If running and config unchanged → no-op
   *
   * Note: When restart is needed, the query is closed BEFORE checking if we can
   * start a new one. This ensures fallback to cold-start if CLI becomes unavailable.
   *
   * @returns true if the query was (re)started, false otherwise
   */
  async ensureReady(options) {
    var _a3, _b2, _c;
    const vaultPath = getVaultPath(this.plugin.app);
    if (options && options.externalContextPaths !== void 0) {
      this.currentExternalContextPaths = options.externalContextPaths;
    }
    const effectiveSessionId = (_b2 = (_a3 = options == null ? void 0 : options.sessionId) != null ? _a3 : this.sessionManager.getSessionId()) != null ? _b2 : void 0;
    const externalContextPaths = (_c = options == null ? void 0 : options.externalContextPaths) != null ? _c : this.currentExternalContextPaths;
    if (!this.persistentQuery) {
      if (!vaultPath) return false;
      const cliPath2 = this.plugin.getResolvedProviderCliPath("claude");
      if (!cliPath2) return false;
      await this.startPersistentQuery(vaultPath, cliPath2, effectiveSessionId, externalContextPaths);
      return true;
    }
    if (options == null ? void 0 : options.force) {
      this.closePersistentQuery("forced restart", { preserveHandlers: options.preserveHandlers });
      if (!vaultPath) return false;
      const cliPath2 = this.plugin.getResolvedProviderCliPath("claude");
      if (!cliPath2) return false;
      await this.startPersistentQuery(vaultPath, cliPath2, effectiveSessionId, externalContextPaths);
      return true;
    }
    if (!vaultPath) return false;
    const cliPath = this.plugin.getResolvedProviderCliPath("claude");
    if (!cliPath) return false;
    const newConfig = this.buildPersistentQueryConfig(vaultPath, cliPath, externalContextPaths);
    if (this.needsRestart(newConfig)) {
      this.closePersistentQuery("config changed", { preserveHandlers: options == null ? void 0 : options.preserveHandlers });
      const cliPathAfterClose = this.plugin.getResolvedProviderCliPath("claude");
      if (cliPathAfterClose) {
        await this.startPersistentQuery(vaultPath, cliPathAfterClose, effectiveSessionId, externalContextPaths);
        return true;
      }
      return false;
    }
    return false;
  }
  /**
   * Starts the persistent query for the active chat conversation.
   */
  async startPersistentQuery(vaultPath, cliPath, resumeSessionId, externalContextPaths) {
    if (this.persistentQuery) {
      return;
    }
    this.shuttingDown = false;
    this.vaultPath = vaultPath;
    this.messageChannel = new MessageChannel();
    if (resumeSessionId) {
      this.messageChannel.setSessionId(resumeSessionId);
      this.sessionManager.setSessionId(resumeSessionId, this.getScopedSettings().model);
    }
    this.queryAbortController = new AbortController();
    const config2 = this.buildPersistentQueryConfig(vaultPath, cliPath, externalContextPaths);
    this.currentConfig = config2;
    const resumeAtMessageId = this.pendingResumeAt;
    const options = await this.buildPersistentQueryOptions(
      vaultPath,
      cliPath,
      resumeSessionId,
      resumeAtMessageId,
      externalContextPaths
    );
    this.persistentQuery = E$$({
      prompt: this.messageChannel,
      options
    });
    if (this.pendingResumeAt === resumeAtMessageId) {
      this.pendingResumeAt = void 0;
    }
    this.attachPersistentQueryStdinErrorHandler(this.persistentQuery);
    this.startResponseConsumer();
    this.notifyReadyStateChange();
  }
  attachPersistentQueryStdinErrorHandler(query) {
    var _a3;
    const stdin = (_a3 = query.transport) == null ? void 0 : _a3.processStdin;
    if (!stdin || typeof stdin.on !== "function" || typeof stdin.once !== "function") {
      return;
    }
    const handler = (error48) => {
      if (this.shuttingDown || this.isPipeError(error48)) {
        return;
      }
      this.closePersistentQuery("stdin error");
    };
    stdin.on("error", handler);
    stdin.once("close", () => {
      stdin.removeListener("error", handler);
    });
  }
  isPipeError(error48) {
    if (!error48 || typeof error48 !== "object") return false;
    const e2 = error48;
    return e2.code === "EPIPE" || typeof e2.message === "string" && e2.message.includes("EPIPE");
  }
  /**
   * Closes the persistent query and cleans up resources.
   */
  closePersistentQuery(_reason, options) {
    var _a3, _b2, _c;
    if (!this.persistentQuery) {
      return;
    }
    const preserveHandlers = (_a3 = options == null ? void 0 : options.preserveHandlers) != null ? _a3 : false;
    this.shuttingDown = true;
    (_b2 = this.messageChannel) == null ? void 0 : _b2.close();
    void this.persistentQuery.interrupt().catch(() => {
    });
    (_c = this.queryAbortController) == null ? void 0 : _c.abort();
    if (!preserveHandlers) {
      for (const handler of this.responseHandlers) {
        handler.onDone();
      }
    }
    this.shuttingDown = false;
    this.notifyReadyStateChange();
    this.persistentQuery = null;
    this.messageChannel = null;
    this.queryAbortController = null;
    this.responseConsumerRunning = false;
    this.responseConsumerPromise = null;
    this.currentConfig = null;
    this.cachedSdkCommands = [];
    this.streamTransformState.clearAll();
    this.usageTransformState.clear();
    this._autoTurnBuffer = [];
    this._autoTurnSawStreamText = false;
    this._autoTurnSawStreamThinking = false;
    if (!preserveHandlers) {
      this.responseHandlers = [];
      this.currentAllowedTools = null;
    }
  }
  /**
   * Checks if the persistent query needs to be restarted based on configuration changes.
   */
  needsRestart(newConfig) {
    return QueryOptionsBuilder.needsRestart(this.currentConfig, newConfig);
  }
  /**
   * Builds configuration object for tracking changes.
   */
  buildPersistentQueryConfig(vaultPath, cliPath, externalContextPaths) {
    return QueryOptionsBuilder.buildPersistentQueryConfig(
      this.buildQueryOptionsContext(vaultPath, cliPath),
      externalContextPaths
    );
  }
  /**
   * Builds the base query options context from current state.
   */
  getScopedSettings() {
    return ProviderSettingsCoordinator.getProviderSettingsSnapshot(
      this.plugin.settings,
      this.providerId
    );
  }
  buildQueryOptionsContext(vaultPath, cliPath) {
    const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables(this.providerId));
    const enhancedPath = getEnhancedPath(customEnv.PATH, cliPath);
    return {
      vaultPath,
      cliPath,
      settings: this.getScopedSettings(),
      customEnv,
      enhancedPath,
      mcpManager: this.mcpManager,
      pluginManager: this.requirePluginManager()
    };
  }
  requirePluginManager() {
    var _a3, _b2;
    const pluginManager = (_b2 = (_a3 = this.pluginManager) != null ? _a3 : this.getLegacyPluginDeps().pluginManager) != null ? _b2 : null;
    if (!pluginManager) {
      throw new Error("Claude plugin manager is unavailable.");
    }
    return pluginManager;
  }
  getAgentManager() {
    var _a3, _b2;
    return (_b2 = (_a3 = this.agentManager) != null ? _a3 : this.getLegacyPluginDeps().agentManager) != null ? _b2 : null;
  }
  /**
   * Builds SDK options for the persistent query.
   */
  buildPersistentQueryOptions(vaultPath, cliPath, resumeSessionId, resumeAtMessageId, externalContextPaths) {
    var _a3;
    const baseContext = this.buildQueryOptionsContext(vaultPath, cliPath);
    const hooks = this.buildHooks();
    const ctx = {
      ...baseContext,
      abortController: (_a3 = this.queryAbortController) != null ? _a3 : void 0,
      resume: resumeSessionId ? { sessionId: resumeSessionId, sessionAt: resumeAtMessageId, fork: this.pendingForkSession || void 0 } : void 0,
      canUseTool: this.createApprovalCallback(),
      hooks,
      externalContextPaths
    };
    return QueryOptionsBuilder.buildPersistentQueryOptions(ctx);
  }
  /**
   * Builds the hooks for SDK options.
   * Hooks need access to `this` for dynamic settings, so they're built here.
   */
  buildHooks() {
    const hooks = {};
    hooks.Stop = [createStopSubagentHook(
      () => {
        var _a3, _b2;
        return (_b2 = (_a3 = this._subagentStateProvider) == null ? void 0 : _a3.call(this)) != null ? _b2 : { hasRunning: false };
      }
    )];
    return hooks;
  }
  /**
   * Starts the background consumer loop that routes chunks to handlers.
   */
  startResponseConsumer() {
    if (this.responseConsumerRunning) {
      return;
    }
    this.responseConsumerRunning = true;
    const queryForThisConsumer = this.persistentQuery;
    this.responseConsumerPromise = (async () => {
      var _a3;
      if (!this.persistentQuery) return;
      try {
        for await (const message of this.persistentQuery) {
          if (this.shuttingDown) break;
          await this.routeMessage(message);
        }
      } catch (error48) {
        if (this.persistentQuery !== queryForThisConsumer && this.persistentQuery !== null) {
          return;
        }
        if (!this.shuttingDown && !this.coldStartInProgress) {
          const handler = this.responseHandlers[this.responseHandlers.length - 1];
          const errorInstance = error48 instanceof Error ? error48 : new Error(String(error48));
          const messageToReplay = this.lastSentMessage;
          if (!this.crashRecoveryAttempted && messageToReplay && handler && !handler.sawAnyChunk) {
            this.crashRecoveryAttempted = true;
            try {
              await this.ensureReady({ force: true, preserveHandlers: true });
              if (!this.messageChannel) {
                throw new Error("Persistent query restart did not create message channel", {
                  cause: error48
                });
              }
              await this.applyDynamicUpdates((_a3 = this.lastSentQueryOptions) != null ? _a3 : void 0, { preserveHandlers: true });
              this.messageChannel.enqueue(messageToReplay);
              return;
            } catch (restartError) {
              if (isSessionExpiredError(restartError)) {
                this.sessionManager.invalidateSession();
              }
              handler.onError(errorInstance);
              return;
            }
          }
          if (handler) {
            handler.onError(errorInstance);
          }
          if (!this.crashRecoveryAttempted) {
            this.crashRecoveryAttempted = true;
            try {
              await this.ensureReady({ force: true });
            } catch (restartError) {
              if (isSessionExpiredError(restartError)) {
                this.sessionManager.invalidateSession();
              }
            }
          }
        }
      } finally {
        if (this.persistentQuery === queryForThisConsumer || this.persistentQuery === null) {
          this.responseConsumerRunning = false;
        }
      }
    })();
  }
  /** @param modelOverride - Optional model override for cold-start queries */
  getTransformOptions(modelOverride, streamState = this.streamTransformState, usageState = this.usageTransformState) {
    const settings11 = this.getScopedSettings();
    return {
      intendedModel: modelOverride != null ? modelOverride : settings11.model,
      customContextLimits: settings11.customContextLimits,
      streamState,
      usageState
    };
  }
  /**
   * Routes an SDK message to the active response handler.
   *
   * Design: Only one handler exists at a time because MessageChannel enforces
   * single-turn processing. When a turn is active, new messages are queued/merged.
   * The next message only dequeues after onTurnComplete(), which calls onDone()
   * on the current handler. A new handler is registered only when the next query starts.
   */
  async routeMessage(message) {
    var _a3, _b2, _c, _d2;
    const handler = this.responseHandlers[this.responseHandlers.length - 1];
    for (const event of transformSDKMessage(message, this.getTransformOptions())) {
      this.noteVisibleStreamContent(message, event, {
        onText: () => {
          if (handler) {
            handler.markStreamTextSeen();
          } else {
            this._autoTurnSawStreamText = true;
          }
        },
        onThinking: () => {
          if (handler) {
            handler.markStreamThinkingSeen();
          } else {
            this._autoTurnSawStreamThinking = true;
          }
        }
      });
      if (isSessionInitEvent(event)) {
        const wasFork = this.pendingForkSession;
        this.sessionManager.captureSession(event.sessionId);
        if (wasFork) {
          this.sessionManager.clearHistoryRebuild();
          this.pendingForkSession = false;
        }
        (_a3 = this.messageChannel) == null ? void 0 : _a3.setSessionId(event.sessionId);
        if (event.agents) {
          try {
            (_b2 = this.getAgentManager()) == null ? void 0 : _b2.setBuiltinAgentNames(event.agents);
          } catch (e2) {
          }
        }
        if (event.permissionMode && this.permissionModeSyncCallback) {
          try {
            this.permissionModeSyncCallback(event.permissionMode);
          } catch (e2) {
          }
        }
        void this.fetchAndCacheCommands(this.persistentQuery);
      } else if (isContextWindowEvent(event)) {
        const usageChunk = this.updateBufferedUsageContextWindow(event.contextWindow);
        if (!usageChunk) {
          continue;
        }
        if (handler) {
          handler.onChunk(usageChunk);
        } else {
          this._autoTurnBuffer.push(usageChunk);
        }
      } else if (isStreamChunk(event)) {
        if (message.type === "assistant" && event.type === "text") {
          if ((handler == null ? void 0 : handler.sawStreamText) || !handler && this._autoTurnSawStreamText) {
            continue;
          }
        }
        if (message.type === "assistant" && event.type === "thinking") {
          if ((handler == null ? void 0 : handler.sawStreamThinking) || !handler && this._autoTurnSawStreamThinking) {
            continue;
          }
        }
        if (event.type === "tool_use" && event.name === TOOL_ENTER_PLAN_MODE) {
          if (this.currentConfig) {
            this.currentConfig.permissionMode = "plan";
            this.currentConfig.sdkPermissionMode = "plan";
          }
          if (this.permissionModeSyncCallback) {
            try {
              this.permissionModeSyncCallback("plan");
            } catch (e2) {
            }
          }
        }
        const normalizedChunk = event.type === "usage" ? this.bufferUsageChunk({ ...event, sessionId: this.sessionManager.getSessionId() }) : event;
        if (handler) {
          handler.onChunk(normalizedChunk);
        } else {
          this._autoTurnBuffer.push(normalizedChunk);
        }
      }
    }
    if (message.type === "assistant" && message.uuid) {
      this.recordTurnMetadata({ assistantMessageId: message.uuid });
    }
    if (isTurnCompleteMessage(message)) {
      (_c = this.messageChannel) == null ? void 0 : _c.onTurnComplete();
      if (handler) {
        handler.resetStreamText();
        handler.resetStreamThinking();
        handler.onDone();
      } else {
        this._autoTurnSawStreamText = false;
        this._autoTurnSawStreamThinking = false;
        if (this._autoTurnBuffer.length === 0) {
          return;
        }
        const chunks = [...this._autoTurnBuffer];
        const metadata = this.consumeTurnMetadata();
        this._autoTurnBuffer = [];
        try {
          (_d2 = this._autoTurnCallback) == null ? void 0 : _d2.call(this, { chunks, metadata });
        } catch (e2) {
          new import_obsidian14.Notice("Background task completed, but the result could not be rendered.");
        }
      }
    }
  }
  registerResponseHandler(handler) {
    this.responseHandlers.push(handler);
  }
  unregisterResponseHandler(handlerId) {
    const idx = this.responseHandlers.findIndex((h) => h.id === handlerId);
    if (idx >= 0) {
      this.responseHandlers.splice(idx, 1);
    }
  }
  buildLegacyTurnRequest(prompt, images, queryOptions) {
    return {
      text: prompt,
      images,
      externalContextPaths: queryOptions == null ? void 0 : queryOptions.externalContextPaths,
      enabledMcpServers: queryOptions == null ? void 0 : queryOptions.enabledMcpServers
    };
  }
  buildQueryOptionsFromTurnRequest(request, encodedTurn, legacyQueryOptions) {
    var _a3, _b2, _c, _d2;
    const mcpMentions = (legacyQueryOptions == null ? void 0 : legacyQueryOptions.mcpMentions) ? /* @__PURE__ */ new Set([...legacyQueryOptions.mcpMentions, ...encodedTurn.mcpMentions]) : encodedTurn.mcpMentions;
    const effectiveQueryOptions = {
      allowedTools: legacyQueryOptions == null ? void 0 : legacyQueryOptions.allowedTools,
      model: legacyQueryOptions == null ? void 0 : legacyQueryOptions.model,
      mcpMentions,
      enabledMcpServers: (_a3 = request.enabledMcpServers) != null ? _a3 : legacyQueryOptions == null ? void 0 : legacyQueryOptions.enabledMcpServers,
      forceColdStart: legacyQueryOptions == null ? void 0 : legacyQueryOptions.forceColdStart,
      externalContextPaths: (_b2 = request.externalContextPaths) != null ? _b2 : legacyQueryOptions == null ? void 0 : legacyQueryOptions.externalContextPaths
    };
    if (effectiveQueryOptions.allowedTools === void 0 && effectiveQueryOptions.model === void 0 && effectiveQueryOptions.enabledMcpServers === void 0 && effectiveQueryOptions.forceColdStart === void 0 && effectiveQueryOptions.externalContextPaths === void 0 && ((_d2 = (_c = effectiveQueryOptions.mcpMentions) == null ? void 0 : _c.size) != null ? _d2 : 0) === 0) {
      return void 0;
    }
    return effectiveQueryOptions;
  }
  normalizeTurnInvocation(turnOrPrompt, imagesOrHistory, conversationHistoryOrQueryOptions, legacyQueryOptions) {
    if (typeof turnOrPrompt !== "string") {
      const turn = turnOrPrompt;
      const conversationHistory2 = isChatMessageArray(imagesOrHistory) ? imagesOrHistory : void 0;
      const explicitQueryOptions = isChatMessageArray(conversationHistoryOrQueryOptions) ? void 0 : conversationHistoryOrQueryOptions;
      return {
        request: turn.request,
        encodedTurn: turn,
        conversationHistory: conversationHistory2,
        queryOptions: this.buildQueryOptionsFromTurnRequest(turn.request, turn, explicitQueryOptions)
      };
    }
    const images = isImageAttachmentArray(imagesOrHistory) ? imagesOrHistory : void 0;
    const conversationHistory = isChatMessageArray(conversationHistoryOrQueryOptions) ? conversationHistoryOrQueryOptions : void 0;
    const queryOptions = isChatMessageArray(conversationHistoryOrQueryOptions) ? legacyQueryOptions : conversationHistoryOrQueryOptions != null ? conversationHistoryOrQueryOptions : legacyQueryOptions;
    const request = this.buildLegacyTurnRequest(turnOrPrompt, images, queryOptions);
    const encodedTurn = this.prepareTurn(request);
    return {
      request,
      encodedTurn,
      conversationHistory,
      queryOptions: this.buildQueryOptionsFromTurnRequest(request, encodedTurn, queryOptions)
    };
  }
  isPersistentQueryActive() {
    return this.persistentQuery !== null && !this.shuttingDown;
  }
  async *query(turnOrPrompt, imagesOrHistory, conversationHistoryOrQueryOptions, legacyQueryOptions) {
    var _a3;
    const normalized = this.normalizeTurnInvocation(
      turnOrPrompt,
      imagesOrHistory,
      conversationHistoryOrQueryOptions,
      legacyQueryOptions
    );
    const prompt = normalized.encodedTurn.prompt;
    const images = normalized.request.images;
    const conversationHistory = normalized.conversationHistory;
    const queryOptions = normalized.queryOptions;
    const vaultPath = getVaultPath(this.plugin.app);
    if (!vaultPath) {
      yield { type: "error", content: "Could not determine vault path" };
      return;
    }
    const resolvedClaudePath = this.plugin.getResolvedProviderCliPath("claude");
    if (!resolvedClaudePath) {
      yield { type: "error", content: "Claude CLI not found. Please install Claude Code CLI." };
      return;
    }
    const customEnv = parseEnvironmentVariables(this.plugin.getActiveEnvironmentVariables(this.providerId));
    const enhancedPath = getEnhancedPath(customEnv.PATH, resolvedClaudePath);
    const missingNodeError = getMissingNodeError(resolvedClaudePath, enhancedPath);
    if (missingNodeError) {
      yield { type: "error", content: missingNodeError };
      return;
    }
    let promptToSend = prompt;
    let forceColdStart = false;
    if (this.sessionManager.wasInterrupted()) {
      this.sessionManager.clearInterrupted();
    }
    if (this.sessionManager.needsHistoryRebuild() && conversationHistory && conversationHistory.length > 0) {
      const historyContext = buildContextFromHistory(conversationHistory);
      const actualPrompt = stripCurrentNoteContext(prompt);
      promptToSend = buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory);
      this.sessionManager.clearHistoryRebuild();
    }
    const noSessionButHasHistory = !this.sessionManager.getSessionId() && conversationHistory && conversationHistory.length > 0;
    if (noSessionButHasHistory) {
      const historyContext = buildContextFromHistory(conversationHistory);
      const actualPrompt = stripCurrentNoteContext(prompt);
      promptToSend = buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory);
      forceColdStart = true;
    }
    const effectiveQueryOptions = forceColdStart ? { ...queryOptions, forceColdStart: true } : queryOptions;
    if (forceColdStart) {
      this.coldStartInProgress = true;
      this.closePersistentQuery("session invalidated");
    }
    const shouldUsePersistent = !(effectiveQueryOptions == null ? void 0 : effectiveQueryOptions.forceColdStart);
    if (shouldUsePersistent) {
      if (!this.persistentQuery && !this.shuttingDown) {
        await this.startPersistentQuery(
          vaultPath,
          resolvedClaudePath,
          (_a3 = this.sessionManager.getSessionId()) != null ? _a3 : void 0
        );
      }
      if (this.persistentQuery && !this.shuttingDown) {
        try {
          yield* this.queryViaPersistent(promptToSend, images, vaultPath, resolvedClaudePath, effectiveQueryOptions);
          return;
        } catch (error48) {
          if (isSessionExpiredError(error48) && conversationHistory && conversationHistory.length > 0) {
            this.sessionManager.invalidateSession();
            const retryRequest = this.buildHistoryRebuildRequest(prompt, conversationHistory);
            this.coldStartInProgress = true;
            this.abortController = new AbortController();
            try {
              yield* this.queryViaSDK(
                retryRequest.prompt,
                vaultPath,
                resolvedClaudePath,
                // Use current message's images, fallback to history images
                images != null ? images : retryRequest.images,
                effectiveQueryOptions
              );
            } catch (retryError) {
              const msg = retryError instanceof Error ? retryError.message : "Unknown error";
              yield { type: "error", content: msg };
            } finally {
              this.coldStartInProgress = false;
              this.abortController = null;
            }
            return;
          }
          throw error48;
        }
      }
    }
    this.coldStartInProgress = true;
    this.abortController = new AbortController();
    try {
      yield* this.queryViaSDK(promptToSend, vaultPath, resolvedClaudePath, images, effectiveQueryOptions);
    } catch (error48) {
      if (isSessionExpiredError(error48) && conversationHistory && conversationHistory.length > 0) {
        this.sessionManager.invalidateSession();
        const retryRequest = this.buildHistoryRebuildRequest(prompt, conversationHistory);
        try {
          yield* this.queryViaSDK(
            retryRequest.prompt,
            vaultPath,
            resolvedClaudePath,
            // Use current message's images, fallback to history images
            images != null ? images : retryRequest.images,
            effectiveQueryOptions
          );
        } catch (retryError) {
          const msg2 = retryError instanceof Error ? retryError.message : "Unknown error";
          yield { type: "error", content: msg2 };
        }
        return;
      }
      const msg = error48 instanceof Error ? error48.message : "Unknown error";
      yield { type: "error", content: msg };
    } finally {
      this.coldStartInProgress = false;
      this.abortController = null;
    }
  }
  buildHistoryRebuildRequest(prompt, conversationHistory) {
    const historyContext = buildContextFromHistory(conversationHistory);
    const actualPrompt = stripCurrentNoteContext(prompt);
    const fullPrompt = buildPromptWithHistoryContext(historyContext, prompt, actualPrompt, conversationHistory);
    const lastUserMessage = getLastUserMessage(conversationHistory);
    return {
      prompt: fullPrompt,
      images: lastUserMessage == null ? void 0 : lastUserMessage.images
    };
  }
  /**
   * Query via persistent query (Phase 1.5).
   * Uses the message channel to send messages without cold-start latency.
   */
  async *queryViaPersistent(prompt, images, vaultPath, cliPath, queryOptions) {
    var _a3;
    this.resetTurnMetadata();
    if (!this.persistentQuery || !this.messageChannel) {
      yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions);
      return;
    }
    if ((queryOptions == null ? void 0 : queryOptions.allowedTools) !== void 0) {
      this.currentAllowedTools = queryOptions.allowedTools.length > 0 ? [...queryOptions.allowedTools, TOOL_SKILL] : [];
    } else {
      this.currentAllowedTools = null;
    }
    const savedAllowedTools = this.currentAllowedTools;
    await this.applyDynamicUpdates(queryOptions);
    this.currentAllowedTools = savedAllowedTools;
    if (!this.persistentQuery || !this.messageChannel) {
      yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions);
      return;
    }
    if (!this.responseConsumerRunning) {
      yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions);
      return;
    }
    const message = this.buildSDKUserMessage(prompt, images);
    const state = {
      chunks: [],
      resolveChunk: null,
      done: false,
      error: null
    };
    const handlerId = `handler-${Date.now()}-${Math.random().toString(36).slice(2)}`;
    const handler = createResponseHandler({
      id: handlerId,
      onChunk: (chunk) => {
        handler.markChunkSeen();
        if (state.resolveChunk) {
          state.resolveChunk(chunk);
          state.resolveChunk = null;
        } else {
          state.chunks.push(chunk);
        }
      },
      onDone: () => {
        state.done = true;
        if (state.resolveChunk) {
          state.resolveChunk(null);
          state.resolveChunk = null;
        }
      },
      onError: (err) => {
        state.error = err;
        state.done = true;
        if (state.resolveChunk) {
          state.resolveChunk(null);
          state.resolveChunk = null;
        }
      }
    });
    this.registerResponseHandler(handler);
    try {
      this.lastSentMessage = message;
      this.lastSentQueryOptions = queryOptions != null ? queryOptions : null;
      this.crashRecoveryAttempted = false;
      try {
        this.messageChannel.enqueue(message);
      } catch (error48) {
        if (error48 instanceof Error && error48.message.includes("closed")) {
          yield* this.queryViaSDK(prompt, vaultPath, cliPath, images, queryOptions);
          return;
        }
        throw error48;
      }
      this.recordTurnMetadata({
        userMessageId: (_a3 = message.uuid) != null ? _a3 : void 0,
        wasSent: true
      });
      while (!state.done) {
        if (state.chunks.length > 0) {
          yield state.chunks.shift();
        } else {
          const chunk = await new Promise((resolve8) => {
            state.resolveChunk = resolve8;
          });
          if (chunk) {
            yield chunk;
          }
        }
      }
      while (state.chunks.length > 0) {
        yield state.chunks.shift();
      }
      if (state.error) {
        if (isSessionExpiredError(state.error)) {
          throw state.error;
        }
        yield { type: "error", content: state.error.message };
      }
      this.lastSentMessage = null;
      this.lastSentQueryOptions = null;
      yield { type: "done" };
    } finally {
      this.unregisterResponseHandler(handlerId);
      this.currentAllowedTools = null;
    }
  }
  buildSDKUserMessage(prompt, images) {
    return buildClaudeSDKUserMessage(
      prompt,
      this.sessionManager.getSessionId() || "",
      images
    );
  }
  /**
   * Apply dynamic updates to the persistent query before sending a message (Phase 1.6).
   */
  async applyDynamicUpdates(queryOptions, restartOptions, allowRestart = true) {
    await applyClaudeDynamicUpdates(
      {
        getPersistentQuery: () => this.persistentQuery,
        getCurrentConfig: () => this.currentConfig,
        mutateCurrentConfig: (mutate) => {
          if (this.currentConfig) {
            mutate(this.currentConfig);
          }
        },
        getVaultPath: () => this.vaultPath,
        getCliPath: () => this.plugin.getResolvedProviderCliPath("claude"),
        getScopedSettings: () => this.getScopedSettings(),
        getPermissionMode: () => this.plugin.settings.permissionMode,
        resolveSDKPermissionMode: (mode) => this.resolveSDKPermissionMode(mode),
        mcpManager: this.mcpManager,
        buildPersistentQueryConfig: (vaultPath, cliPath, externalContextPaths) => this.buildPersistentQueryConfig(vaultPath, cliPath, externalContextPaths),
        needsRestart: (newConfig) => this.needsRestart(newConfig),
        ensureReady: (options) => this.ensureReady(options),
        setCurrentExternalContextPaths: (paths) => {
          this.currentExternalContextPaths = paths;
        },
        notifyFailure: (message) => {
          new import_obsidian14.Notice(message);
        }
      },
      queryOptions,
      restartOptions,
      allowRestart
    );
  }
  noteVisibleStreamContent(message, event, callbacks) {
    if (message.type !== "stream_event") {
      return;
    }
    if (event.type === "text") {
      callbacks.onText();
    } else if (event.type === "thinking") {
      callbacks.onThinking();
    }
  }
  buildPromptWithImages(prompt, images) {
    return buildClaudePromptWithImages(prompt, images);
  }
  async *queryViaSDK(prompt, cwd, cliPath, images, queryOptions) {
    var _a3, _b2, _c;
    this.resetTurnMetadata();
    const selectedModel = (queryOptions == null ? void 0 : queryOptions.model) || this.getScopedSettings().model;
    this.sessionManager.setPendingModel(selectedModel);
    this.vaultPath = cwd;
    const queryPrompt = this.buildPromptWithImages(prompt, images);
    const baseContext = this.buildQueryOptionsContext(cwd, cliPath);
    const externalContextPaths = (queryOptions == null ? void 0 : queryOptions.externalContextPaths) || [];
    const hooks = this.buildHooks();
    const hasEditorContext = prompt.includes("<editor_selection");
    let allowedTools;
    if ((queryOptions == null ? void 0 : queryOptions.allowedTools) !== void 0 && queryOptions.allowedTools.length > 0) {
      const toolSet = /* @__PURE__ */ new Set([...queryOptions.allowedTools, TOOL_SKILL]);
      allowedTools = [...toolSet];
    }
    const ctx = {
      ...baseContext,
      abortController: (_a3 = this.abortController) != null ? _a3 : void 0,
      sessionId: (_b2 = this.sessionManager.getSessionId()) != null ? _b2 : void 0,
      modelOverride: queryOptions == null ? void 0 : queryOptions.model,
      canUseTool: this.createApprovalCallback(),
      hooks,
      mcpMentions: queryOptions == null ? void 0 : queryOptions.mcpMentions,
      enabledMcpServers: queryOptions == null ? void 0 : queryOptions.enabledMcpServers,
      allowedTools,
      hasEditorContext,
      externalContextPaths
    };
    const options = QueryOptionsBuilder.buildColdStartQueryOptions(ctx);
    let sawStreamText = false;
    let sawStreamThinking = false;
    const streamState = createTransformStreamState();
    const usageState = createTransformUsageState();
    try {
      const response = E$$({ prompt: queryPrompt, options });
      this.recordTurnMetadata({ wasSent: true });
      let streamSessionId = this.sessionManager.getSessionId();
      for await (const message of response) {
        if ((_c = this.abortController) == null ? void 0 : _c.signal.aborted) {
          await response.interrupt();
          break;
        }
        for (const event of transformSDKMessage(message, this.getTransformOptions(selectedModel, streamState, usageState))) {
          this.noteVisibleStreamContent(message, event, {
            onText: () => {
              sawStreamText = true;
            },
            onThinking: () => {
              sawStreamThinking = true;
            }
          });
          if (isSessionInitEvent(event)) {
            this.sessionManager.captureSession(event.sessionId);
            streamSessionId = event.sessionId;
          } else if (isContextWindowEvent(event)) {
            const usageChunk = this.updateBufferedUsageContextWindow(event.contextWindow);
            if (usageChunk) {
              yield usageChunk;
            }
          } else if (isStreamChunk(event)) {
            if (message.type === "assistant" && sawStreamText && event.type === "text") {
              continue;
            }
            if (message.type === "assistant" && sawStreamThinking && event.type === "thinking") {
              continue;
            }
            if (event.type === "usage") {
              yield this.bufferUsageChunk({ ...event, sessionId: streamSessionId });
            } else {
              yield event;
            }
          }
        }
        if (message.type === "assistant" && message.uuid) {
          this.recordTurnMetadata({ assistantMessageId: message.uuid });
        }
        if (message.type === "result") {
          sawStreamText = false;
          sawStreamThinking = false;
        }
      }
    } catch (error48) {
      if (isSessionExpiredError(error48)) {
        throw error48;
      }
      const msg = error48 instanceof Error ? error48.message : "Unknown error";
      yield { type: "error", content: msg };
    } finally {
      this.sessionManager.clearPendingModel();
      this.currentAllowedTools = null;
    }
    yield { type: "done" };
  }
  cancel() {
    var _a3;
    (_a3 = this.approvalDismisser) == null ? void 0 : _a3.call(this);
    if (this.abortController) {
      this.abortController.abort();
      this.sessionManager.markInterrupted();
    }
    if (this.persistentQuery && !this.shuttingDown) {
      void this.persistentQuery.interrupt().catch(() => {
      });
    }
  }
  /**
   * Reset the conversation session.
   * Closes the persistent query since session is changing.
   */
  resetSession() {
    this.closePersistentQuery("session reset");
    this.crashRecoveryAttempted = false;
    this.sessionManager.reset();
  }
  getSessionId() {
    return this.sessionManager.getSessionId();
  }
  /** Consume session invalidation flag for persistence updates. */
  consumeSessionInvalidation() {
    return this.sessionManager.consumeInvalidation();
  }
  /**
   * Check if the service is ready (persistent query is active).
   * Used to determine if SDK skills are available.
   */
  isReady() {
    return this.isPersistentQueryActive();
  }
  /**
   * Get supported commands (SDK skills).
   * Returns cached commands populated on system/init. Falls back to a fresh
   * supportedCommands() call if the cache is empty (e.g., dropdown opened
   * before the first init event).
   */
  async getSupportedCommands() {
    if (this.cachedSdkCommands.length > 0) {
      return this.cachedSdkCommands;
    }
    if (!this.persistentQuery) {
      return [];
    }
    return this.fetchAndCacheCommands(this.persistentQuery);
  }
  /**
   * Fetches commands from the SDK and caches them. Called on system/init
   * (fire-and-forget) and as a fallback from getSupportedCommands().
   */
  async fetchAndCacheCommands(query) {
    if (!query) return [];
    try {
      const sdkCommands = await query.supportedCommands();
      const mappedCommands = sdkCommands.map((cmd) => ({
        id: `sdk:${cmd.name}`,
        name: cmd.name,
        description: cmd.description,
        argumentHint: cmd.argumentHint,
        content: "",
        source: "sdk"
      }));
      if (this.persistentQuery !== query) {
        return this.cachedSdkCommands;
      }
      this.cachedSdkCommands = mappedCommands;
      return this.cachedSdkCommands;
    } catch (e2) {
      return [];
    }
  }
  /**
   * Set the session ID (for restoring from saved conversation).
   * Closes persistent query synchronously if session is changing, then ensures query is ready.
   *
   * @param id - Session ID to restore, or null for new session
   * @param externalContextPaths - External context paths for the session (prevents stale contexts)
   */
  setSessionId(id, externalContextPaths) {
    const currentId = this.sessionManager.getSessionId();
    const sessionChanged = currentId !== id;
    if (sessionChanged) {
      this.closePersistentQuery("session switch");
      this.crashRecoveryAttempted = false;
    }
    this.sessionManager.setSessionId(id, this.getScopedSettings().model);
    if (externalContextPaths !== void 0) {
      this.currentExternalContextPaths = externalContextPaths;
    }
  }
  /**
   * Cleanup resources (Phase 5).
   * Called on plugin unload to close persistent query and abort any cold-start query.
   */
  cleanup() {
    this.closePersistentQuery("plugin cleanup");
    this.cancel();
    this.resetSession();
  }
  async rewindFiles(userMessageId, dryRun) {
    if (!this.persistentQuery) throw new Error("No active query");
    if (this.shuttingDown) throw new Error("Service is shutting down");
    return this.persistentQuery.rewindFiles(userMessageId, { dryRun });
  }
  async rewind(userMessageId, assistantMessageId) {
    return executeClaudeRewind(userMessageId, {
      assistantMessageId,
      rewindFiles: this.rewindFiles.bind(this),
      closePersistentQuery: (reason) => this.closePersistentQuery(reason),
      setPendingResumeAt: (resumeAt) => {
        this.pendingResumeAt = resumeAt;
      },
      vaultPath: this.vaultPath
    });
  }
  setApprovalCallback(callback) {
    this.approvalCallback = callback;
  }
  setApprovalDismisser(dismisser) {
    this.approvalDismisser = dismisser;
  }
  setAskUserQuestionCallback(callback) {
    this.askUserQuestionCallback = callback;
  }
  setExitPlanModeCallback(callback) {
    this.exitPlanModeCallback = callback;
  }
  setPermissionModeSyncCallback(callback) {
    this.permissionModeSyncCallback = callback;
  }
  setSubagentHookProvider(getState) {
    this._subagentStateProvider = getState;
  }
  setAutoTurnCallback(callback) {
    this._autoTurnCallback = callback;
  }
  createApprovalCallback() {
    return createClaudeApprovalCallback({
      getAllowedTools: () => this.currentAllowedTools,
      getApprovalCallback: () => this.approvalCallback,
      getAskUserQuestionCallback: () => this.askUserQuestionCallback,
      getExitPlanModeCallback: () => this.exitPlanModeCallback,
      getPermissionMode: () => this.plugin.settings.permissionMode,
      resolveSDKPermissionMode: (mode) => this.resolveSDKPermissionMode(mode),
      syncPermissionMode: (mode, sdkMode) => {
        if (this.currentConfig) {
          this.currentConfig.permissionMode = mode;
          this.currentConfig.sdkPermissionMode = sdkMode;
        }
      }
    });
  }
  resolveSDKPermissionMode(mode) {
    return QueryOptionsBuilder.resolveClaudeSdkPermissionMode(
      mode,
      getClaudeProviderSettings(this.plugin.settings).safeMode
    );
  }
};

// src/providers/claude/runtime/ClaudeTaskResultInterpreter.ts
function extractAgentIdFromString(value) {
  const regexPatterns = [
    /"agent_id"\s*:\s*"([^"]+)"/,
    /"agentId"\s*:\s*"([^"]+)"/,
    /agent_id[=:]\s*"?([a-zA-Z0-9_-]+)"?/i,
    /agentId[=:]\s*"?([a-zA-Z0-9_-]+)"?/i
  ];
  for (const pattern of regexPatterns) {
    const match = value.match(pattern);
    if (match && match[1]) {
      return match[1];
    }
  }
  return null;
}
function extractResultFromTaskObject(task) {
  if (!task || typeof task !== "object") {
    return null;
  }
  const record2 = task;
  const result = typeof record2.result === "string" ? record2.result.trim() : "";
  if (result.length > 0) {
    return result;
  }
  const output = typeof record2.output === "string" ? record2.output.trim() : "";
  return output.length > 0 ? output : null;
}
function extractTextFromContentBlocks(content) {
  if (!Array.isArray(content)) {
    return null;
  }
  const firstTextBlock = content.find((block) => block && typeof block === "object" && block.type === "text" && typeof block.text === "string");
  if (!firstTextBlock || typeof firstTextBlock.text !== "string") {
    return null;
  }
  const text = firstTextBlock.text.trim();
  return text.length > 0 ? text : null;
}
var ClaudeTaskResultInterpreter = class {
  hasAsyncLaunchMarker(toolUseResult) {
    var _a3;
    if (!toolUseResult || typeof toolUseResult !== "object") {
      return false;
    }
    const record2 = toolUseResult;
    if (record2.isAsync === true) {
      return true;
    }
    const rawStatus = (_a3 = record2.retrieval_status) != null ? _a3 : record2.status;
    if (typeof rawStatus === "string" && rawStatus.toLowerCase() === "async_launched") {
      return true;
    }
    return typeof record2.outputFile === "string" && record2.outputFile.length > 0;
  }
  extractAgentId(toolUseResult) {
    const directId = extractAgentIdFromToolUseResult(toolUseResult);
    if (directId) {
      return directId;
    }
    if (!toolUseResult || typeof toolUseResult !== "object") {
      return null;
    }
    const record2 = toolUseResult;
    if (Array.isArray(record2.content)) {
      for (const block of record2.content) {
        if (typeof block === "string") {
          const extracted2 = extractAgentIdFromString(block);
          if (extracted2) {
            return extracted2;
          }
          continue;
        }
        if (!block || typeof block !== "object") {
          continue;
        }
        const text = block.text;
        if (typeof text !== "string") {
          continue;
        }
        const extracted = extractAgentIdFromString(text);
        if (extracted) {
          return extracted;
        }
      }
    }
    if (typeof record2.content === "string") {
      return extractAgentIdFromString(record2.content);
    }
    return null;
  }
  extractStructuredResult(toolUseResult) {
    if (!toolUseResult || typeof toolUseResult !== "object") {
      return null;
    }
    const record2 = toolUseResult;
    if (record2.retrieval_status === "error") {
      const errorMsg = typeof record2.error === "string" ? record2.error : "Task retrieval failed";
      return `Error: ${errorMsg}`;
    }
    const taskResult = extractResultFromTaskObject(record2.task);
    if (taskResult) {
      return taskResult;
    }
    const result = typeof record2.result === "string" ? record2.result.trim() : "";
    if (result.length > 0) {
      return result;
    }
    const output = typeof record2.output === "string" ? record2.output.trim() : "";
    if (output.length > 0) {
      return output;
    }
    return extractTextFromContentBlocks(record2.content);
  }
  resolveTerminalStatus(toolUseResult, fallbackStatus) {
    const resolved = resolveToolUseResultStatus(toolUseResult, fallbackStatus);
    if (resolved === "error") {
      return "error";
    }
    if (resolved === "completed") {
      return "completed";
    }
    return fallbackStatus;
  }
  extractTagValue(payload, tagName) {
    return extractXmlTag(payload, tagName);
  }
};

// src/providers/claude/registration.ts
var claudeProviderRegistration = {
  displayName: "Claude",
  blankTabOrder: 20,
  isEnabled: () => true,
  capabilities: CLAUDE_PROVIDER_CAPABILITIES,
  environmentKeyPatterns: [/^ANTHROPIC_/i, /^CLAUDE_/i],
  chatUIConfig: claudeChatUIConfig,
  settingsReconciler: claudeSettingsReconciler,
  createRuntime: ({ plugin }) => {
    const workspace = getClaudeWorkspaceServices();
    const resolvedMcpManager = workspace == null ? void 0 : workspace.mcpManager;
    if (!resolvedMcpManager) {
      throw new Error("Claude workspace services are not initialized.");
    }
    return new ClaudianService(plugin, {
      mcpManager: resolvedMcpManager,
      pluginManager: workspace == null ? void 0 : workspace.pluginManager,
      agentManager: workspace == null ? void 0 : workspace.agentManager
    });
  },
  createTitleGenerationService: (plugin) => new TitleGenerationService(plugin),
  createInstructionRefineService: (plugin) => new InstructionRefineService(plugin),
  createInlineEditService: (plugin) => new InlineEditService(plugin),
  historyService: new ClaudeConversationHistoryService(),
  taskResultInterpreter: new ClaudeTaskResultInterpreter()
};

// src/providers/codex/app/CodexWorkspaceServices.ts
init_path();

// src/providers/codex/agents/CodexAgentMentionProvider.ts
var CodexAgentMentionProvider = class {
  constructor(storage) {
    this.storage = storage;
    this.agents = [];
  }
  async loadAgents() {
    this.agents = await this.storage.loadAll();
  }
  searchAgents(query) {
    const q10 = query.toLowerCase();
    return this.agents.filter(
      (a2) => a2.name.toLowerCase().includes(q10) || a2.description.toLowerCase().includes(q10)
    ).map((a2) => ({
      id: a2.name,
      name: a2.name,
      description: a2.description,
      source: "vault"
    }));
  }
};

// src/providers/codex/runtime/CodexAppServerProcess.ts
var import_child_process5 = require("child_process");
var SIGKILL_TIMEOUT_MS = 3e3;
var WINDOWS_CMD_ARGUMENT_CHARS = /[\s"&<>|{}^=;!'+,`~()%@]/u;
function requiresWindowsShellQuoting(value) {
  return WINDOWS_CMD_ARGUMENT_CHARS.test(value) || value.includes("[") || value.includes("]");
}
function quoteWindowsShellArgument(value) {
  if (!value.length) {
    return '""';
  }
  if (!requiresWindowsShellQuoting(value)) {
    return value;
  }
  return `"${value.replace(/"/g, '""')}"`;
}
function resolveWindowsSpawnSpec(launchSpec) {
  const command = launchSpec.command.trim();
  const lowerCommand = command.toLowerCase();
  if (!command || process.platform !== "win32") {
    return {
      command: launchSpec.command,
      args: launchSpec.args,
      env: launchSpec.env
    };
  }
  if (lowerCommand.endsWith(".cmd")) {
    const shellCommand = [command, ...launchSpec.args].map((value) => quoteWindowsShellArgument(value)).join(" ");
    return {
      command: process.env.ComSpec || process.env.comspec || "cmd.exe",
      args: ["/d", "/s", "/c", `"${shellCommand}"`],
      env: launchSpec.env,
      windowsVerbatimArguments: true
    };
  }
  return {
    command: launchSpec.command,
    args: launchSpec.args,
    env: launchSpec.env
  };
}
var CodexAppServerProcess = class {
  constructor(launchSpec) {
    this.launchSpec = launchSpec;
    this.proc = null;
    this.alive = false;
    this.exitCallbacks = [];
  }
  start() {
    const resolvedSpawnSpec = resolveWindowsSpawnSpec(this.launchSpec);
    this.proc = (0, import_child_process5.spawn)(resolvedSpawnSpec.command, resolvedSpawnSpec.args, {
      stdio: ["pipe", "pipe", "pipe"],
      cwd: this.launchSpec.spawnCwd,
      env: resolvedSpawnSpec.env,
      windowsHide: true,
      ...resolvedSpawnSpec.windowsVerbatimArguments ? { windowsVerbatimArguments: true } : {}
    });
    this.alive = true;
    this.proc.on("exit", (code, signal) => {
      this.alive = false;
      for (const cb of this.exitCallbacks) {
        cb(code, signal);
      }
    });
    this.proc.on("error", () => {
      this.alive = false;
    });
  }
  get stdin() {
    var _a3;
    if (!((_a3 = this.proc) == null ? void 0 : _a3.stdin)) throw new Error("Process not started");
    return this.proc.stdin;
  }
  get stdout() {
    var _a3;
    if (!((_a3 = this.proc) == null ? void 0 : _a3.stdout)) throw new Error("Process not started");
    return this.proc.stdout;
  }
  get stderr() {
    var _a3;
    if (!((_a3 = this.proc) == null ? void 0 : _a3.stderr)) throw new Error("Process not started");
    return this.proc.stderr;
  }
  isAlive() {
    return this.alive;
  }
  onExit(callback) {
    this.exitCallbacks.push(callback);
  }
  offExit(callback) {
    const idx = this.exitCallbacks.indexOf(callback);
    if (idx !== -1) this.exitCallbacks.splice(idx, 1);
  }
  async shutdown() {
    if (!this.proc || !this.alive) return;
    return new Promise((resolve8) => {
      const onExit = () => {
        clearTimeout(killTimer);
        resolve8();
      };
      this.proc.once("exit", onExit);
      this.proc.kill("SIGTERM");
      const killTimer = setTimeout(() => {
        if (this.alive) {
          this.proc.kill("SIGKILL");
        }
      }, SIGKILL_TIMEOUT_MS);
    });
  }
};

// src/providers/codex/runtime/codexAppServerSupport.ts
init_env();
init_path();

// src/providers/codex/runtime/CodexExecutionTargetResolver.ts
var import_child_process6 = require("child_process");
function resolveHostPlatformOs(hostPlatform) {
  if (hostPlatform === "win32") {
    return "windows";
  }
  if (hostPlatform === "darwin") {
    return "macos";
  }
  return "linux";
}
function resolveHostPlatformFamily(hostPlatform) {
  return hostPlatform === "win32" ? "windows" : "unix";
}
function inferWslDistroFromWindowsPath(hostPath) {
  if (!hostPath) {
    return void 0;
  }
  const normalized = hostPath.replace(/\//g, "\\");
  const match = normalized.match(/^\\\\wsl\$\\([^\\]+)(?:\\|$)/i);
  return (match == null ? void 0 : match[1]) || void 0;
}
function parseDefaultWslDistroListOutput(output) {
  var _a3;
  for (const line of output.replace(/\uFEFF/g, "").split(/\r?\n/)) {
    const trimmed = line.trimStart();
    if (!trimmed.startsWith("*")) {
      continue;
    }
    const candidate = (_a3 = trimmed.slice(1).trimStart().split(/\s{2,}/)[0]) == null ? void 0 : _a3.trim();
    if (candidate) {
      return candidate;
    }
  }
  return void 0;
}
function resolveDefaultWslDistroName() {
  try {
    const output = (0, import_child_process6.execFileSync)("wsl.exe", ["--list", "--verbose"], {
      encoding: "utf8",
      stdio: ["ignore", "pipe", "ignore"],
      windowsHide: true
    });
    return parseDefaultWslDistroListOutput(output);
  } catch (e2) {
    return void 0;
  }
}
function resolveCodexExecutionTarget(options) {
  var _a3, _b2;
  const hostPlatform = (_a3 = options.hostPlatform) != null ? _a3 : process.platform;
  if (hostPlatform !== "win32") {
    return {
      method: "host-native",
      platformFamily: resolveHostPlatformFamily(hostPlatform),
      platformOs: resolveHostPlatformOs(hostPlatform)
    };
  }
  const codexSettings = getCodexProviderSettings(options.settings);
  if (codexSettings.installationMethod === "wsl") {
    const distroName = codexSettings.wslDistroOverride || inferWslDistroFromWindowsPath(options.hostVaultPath) || ((_b2 = options.resolveDefaultWslDistro) == null ? void 0 : _b2.call(options)) || resolveDefaultWslDistroName();
    return {
      method: "wsl",
      platformFamily: "unix",
      platformOs: "linux",
      distroName
    };
  }
  return {
    method: "native-windows",
    platformFamily: "windows",
    platformOs: "windows"
  };
}

// src/providers/codex/runtime/CodexPathMapper.ts
var path10 = __toESM(require("path"));
function normalizeWindowsPath(value) {
  if (!value) {
    return "";
  }
  let normalized = value.replace(/\//g, "\\");
  if (normalized.startsWith("\\\\?\\UNC\\")) {
    normalized = `\\\\${normalized.slice("\\\\?\\UNC\\".length)}`;
  } else if (normalized.startsWith("\\\\?\\")) {
    normalized = normalized.slice("\\\\?\\".length);
  }
  return path10.win32.normalize(normalized);
}
function normalizePosixPath(value) {
  if (!value) {
    return "";
  }
  const normalized = path10.posix.normalize(value.replace(/\\/g, "/"));
  return normalized === "/" ? normalized : normalized.replace(/\/+$/, "");
}
function maybeMapWindowsDriveToWsl(hostPath) {
  var _a3;
  const normalized = normalizeWindowsPath(hostPath);
  const match = normalized.match(/^([A-Za-z]):(?:\\(.*))?$/);
  if (!match) {
    return null;
  }
  const drive = match[1].toLowerCase();
  const tail = ((_a3 = match[2]) != null ? _a3 : "").replace(/\\/g, "/");
  return tail ? `/mnt/${drive}/${tail}` : `/mnt/${drive}`;
}
function maybeMapWslUncToLinux(hostPath, distroName) {
  const normalized = normalizeWindowsPath(hostPath);
  const match = normalized.match(/^\\\\wsl\$\\([^\\]+)(?:\\(.*))?$/i);
  if (!match) {
    return null;
  }
  const uncDistro = match[1];
  if (distroName && uncDistro.toLowerCase() !== distroName.toLowerCase()) {
    return null;
  }
  const tail = match[2] ? match[2].replace(/\\/g, "/") : "";
  return tail ? `/${tail}` : "/";
}
function maybeMapLinuxToWindowsDrive(targetPath) {
  const normalized = normalizePosixPath(targetPath);
  const match = normalized.match(/^\/mnt\/([a-zA-Z])(?:\/(.*))?$/);
  if (!match) {
    return null;
  }
  const drive = match[1].toUpperCase();
  const tail = match[2] ? match[2].replace(/\//g, "\\") : "";
  return tail ? `${drive}:\\${tail}` : `${drive}:\\`;
}
function maybeMapLinuxToWslUnc(targetPath, distroName) {
  if (!distroName) {
    return null;
  }
  const normalized = normalizePosixPath(targetPath);
  if (!normalized.startsWith("/")) {
    return null;
  }
  const tail = normalized === "/" ? "" : normalized.slice(1).replace(/\//g, "\\");
  return tail ? `\\\\wsl$\\${distroName}\\${tail}` : `\\\\wsl$\\${distroName}`;
}
function createIdentityMapper(target) {
  return {
    target,
    toTargetPath(hostPath) {
      if (!hostPath) {
        return null;
      }
      return target.platformFamily === "windows" ? normalizeWindowsPath(hostPath) : normalizePosixPath(hostPath);
    },
    toHostPath(targetPath) {
      if (!targetPath) {
        return null;
      }
      return target.platformFamily === "windows" ? normalizeWindowsPath(targetPath) : normalizePosixPath(targetPath);
    },
    mapTargetPathList(hostPaths) {
      return hostPaths.map((hostPath) => this.toTargetPath(hostPath)).filter((value) => typeof value === "string" && value.length > 0);
    },
    canRepresentHostPath(hostPath) {
      return this.toTargetPath(hostPath) !== null;
    }
  };
}
function createWslPathMapper(target) {
  return {
    target,
    toTargetPath(hostPath) {
      var _a3;
      if (!hostPath) {
        return null;
      }
      return (_a3 = maybeMapWslUncToLinux(hostPath, target.distroName)) != null ? _a3 : maybeMapWindowsDriveToWsl(hostPath);
    },
    toHostPath(targetPath) {
      var _a3;
      if (!targetPath) {
        return null;
      }
      return (_a3 = maybeMapLinuxToWindowsDrive(targetPath)) != null ? _a3 : maybeMapLinuxToWslUnc(targetPath, target.distroName);
    },
    mapTargetPathList(hostPaths) {
      return hostPaths.map((hostPath) => this.toTargetPath(hostPath)).filter((value) => typeof value === "string" && value.length > 0);
    },
    canRepresentHostPath(hostPath) {
      return this.toTargetPath(hostPath) !== null;
    }
  };
}
function createCodexPathMapper(target) {
  return target.method === "wsl" ? createWslPathMapper(target) : createIdentityMapper(target);
}

// src/providers/codex/runtime/CodexLaunchSpecBuilder.ts
var CODEX_APP_SERVER_ARGS = Object.freeze(["app-server", "--listen", "stdio://"]);
function buildCodexLaunchSpec(options) {
  var _a3, _b2;
  const target = resolveCodexExecutionTarget({
    settings: options.settings,
    hostPlatform: options.hostPlatform,
    hostVaultPath: options.hostVaultPath,
    resolveDefaultWslDistro: options.resolveDefaultWslDistro
  });
  const pathMapper = createCodexPathMapper(target);
  const spawnCwd = (_a3 = options.hostVaultPath) != null ? _a3 : process.cwd();
  const workspaceDistro = inferWslDistroFromWindowsPath(options.hostVaultPath);
  if (target.method === "wsl" && target.distroName && workspaceDistro && target.distroName.toLowerCase() !== workspaceDistro.toLowerCase()) {
    throw new Error(
      `WSL distro override "${target.distroName}" does not match workspace distro "${workspaceDistro}"`
    );
  }
  if (target.method === "wsl" && !target.distroName) {
    throw new Error(
      "Unable to determine the WSL distro. Set WSL distro override or configure a default WSL distro."
    );
  }
  const targetCwd = pathMapper.toTargetPath(spawnCwd);
  if (!targetCwd) {
    throw new Error("WSL mode only supports Windows drive paths and \\\\wsl$ workspace paths");
  }
  const resolvedCliCommand = ((_b2 = options.resolvedCliCommand) == null ? void 0 : _b2.trim()) || "codex";
  if (target.method === "wsl") {
    const args = [
      ...target.distroName ? ["--distribution", target.distroName] : [],
      "--cd",
      targetCwd,
      resolvedCliCommand,
      ...CODEX_APP_SERVER_ARGS
    ];
    return {
      target,
      command: "wsl.exe",
      args,
      spawnCwd,
      targetCwd,
      env: options.env,
      pathMapper
    };
  }
  return {
    target,
    command: resolvedCliCommand,
    args: [...CODEX_APP_SERVER_ARGS],
    spawnCwd,
    targetCwd,
    env: options.env,
    pathMapper
  };
}

// src/providers/codex/runtime/codexAppServerSupport.ts
var CODEX_APP_SERVER_CLIENT_INFO = Object.freeze({
  name: "claudian",
  version: "1.0.0"
});
function getCodexAppServerWorkingDirectory(plugin) {
  var _a3;
  return (_a3 = getVaultPath(plugin.app)) != null ? _a3 : process.cwd();
}
function buildCodexAppServerEnvironment(plugin, providerId = "codex") {
  const customEnv = parseEnvironmentVariables(plugin.getActiveEnvironmentVariables(providerId));
  const baseEnv = Object.fromEntries(
    Object.entries(process.env).filter((entry) => entry[1] !== void 0)
  );
  const enhancedPath = getEnhancedPath(customEnv.PATH);
  return {
    ...baseEnv,
    ...customEnv,
    PATH: enhancedPath
  };
}
function resolveCodexAppServerLaunchSpec(plugin, providerId = "codex") {
  return buildCodexLaunchSpec({
    settings: plugin.settings,
    resolvedCliCommand: plugin.getResolvedProviderCliPath(providerId),
    hostVaultPath: getCodexAppServerWorkingDirectory(plugin),
    env: buildCodexAppServerEnvironment(plugin, providerId)
  });
}
async function initializeCodexAppServerTransport(transport) {
  const result = await transport.request("initialize", {
    clientInfo: CODEX_APP_SERVER_CLIENT_INFO,
    capabilities: { experimentalApi: true }
  });
  transport.notify("initialized");
  return result;
}

// src/providers/codex/runtime/CodexRpcTransport.ts
var import_readline2 = require("readline");
var DEFAULT_TIMEOUT_MS = 3e4;
var CodexRpcTransport = class {
  constructor(proc) {
    this.proc = proc;
    this.nextId = 1;
    this.pending = /* @__PURE__ */ new Map();
    this.notificationHandlers = /* @__PURE__ */ new Map();
    this.serverRequestHandlers = /* @__PURE__ */ new Map();
    this.disposed = false;
  }
  start() {
    const rl = (0, import_readline2.createInterface)({ input: this.proc.stdout });
    rl.on("line", (line) => this.handleLine(line));
    this.proc.onExit(() => {
      this.rejectAllPending(new Error("App-server process exited"));
    });
  }
  request(method, params, timeoutMs = DEFAULT_TIMEOUT_MS) {
    const id = this.nextId++;
    const msg = { jsonrpc: "2.0", id, method, params };
    return new Promise((resolve8, reject) => {
      const timer = timeoutMs > 0 ? setTimeout(() => {
        this.pending.delete(id);
        reject(new Error(`Request timeout: ${method} (${timeoutMs}ms)`));
      }, timeoutMs) : null;
      this.pending.set(id, {
        resolve: resolve8,
        reject,
        timer
      });
      this.sendRaw(msg);
    });
  }
  notify(method, params) {
    const msg = { jsonrpc: "2.0", method };
    if (params !== void 0) msg.params = params;
    this.sendRaw(msg);
  }
  onNotification(method, handler) {
    this.notificationHandlers.set(method, handler);
  }
  onServerRequest(method, handler) {
    this.serverRequestHandlers.set(method, handler);
  }
  dispose() {
    this.disposed = true;
    this.rejectAllPending(new Error("Transport disposed"));
  }
  // -----------------------------------------------------------------------
  // Private
  // -----------------------------------------------------------------------
  sendRaw(msg) {
    if (this.disposed) return;
    this.proc.stdin.write(JSON.stringify(msg) + "\n");
  }
  handleLine(line) {
    let msg;
    try {
      msg = JSON.parse(line);
    } catch (e2) {
      return;
    }
    const id = msg.id;
    const method = msg.method;
    if (typeof id === "number" && !method) {
      this.handleResponse(id, msg);
      return;
    }
    if (method && id === void 0) {
      this.handleNotification(method, msg.params);
      return;
    }
    if (method && id !== void 0) {
      this.handleServerRequest(id, method, msg.params);
      return;
    }
  }
  handleResponse(id, msg) {
    const pending = this.pending.get(id);
    if (!pending) return;
    this.pending.delete(id);
    if (pending.timer) clearTimeout(pending.timer);
    if (msg.error) {
      const err = msg.error;
      pending.reject(new Error(err.message));
    } else {
      pending.resolve(msg.result);
    }
  }
  handleNotification(method, params) {
    const handler = this.notificationHandlers.get(method);
    if (handler) handler(params);
  }
  handleServerRequest(id, method, params) {
    const handler = this.serverRequestHandlers.get(method);
    if (!handler) {
      this.sendRaw({
        jsonrpc: "2.0",
        id,
        error: { code: -32601, message: `Unhandled server request: ${method}` }
      });
      return;
    }
    handler(id, params).then(
      (result) => {
        this.sendRaw({ jsonrpc: "2.0", id, result });
      },
      (err) => {
        this.sendRaw({
          jsonrpc: "2.0",
          id,
          error: { code: -32603, message: err instanceof Error ? err.message : "Internal error" }
        });
      }
    );
  }
  rejectAllPending(error48) {
    for (const [, pending] of this.pending) {
      if (pending.timer) clearTimeout(pending.timer);
      pending.reject(error48);
    }
    this.pending.clear();
  }
};

// src/providers/codex/runtime/CodexRuntimeContext.ts
var path11 = __toESM(require("path"));
function normalizeTargetPath(launchSpec, value) {
  return launchSpec.target.platformFamily === "windows" ? path11.win32.normalize(value) : path11.posix.normalize(value.replace(/\\/g, "/"));
}
function joinTargetPath(launchSpec, ...parts) {
  return launchSpec.target.platformFamily === "windows" ? path11.win32.join(...parts) : path11.posix.join(...parts.map((part) => part.replace(/\\/g, "/")));
}
function normalizeOptionalTargetPath(launchSpec, value) {
  const trimmed = typeof value === "string" ? value.trim() : "";
  return trimmed ? normalizeTargetPath(launchSpec, trimmed) : null;
}
function resolveFallbackCodexHomeTarget(launchSpec) {
  const rawCodexHome = typeof launchSpec.env.CODEX_HOME === "string" ? launchSpec.env.CODEX_HOME.trim() : "";
  const envCodexHome = launchSpec.target.method === "wsl" ? normalizeOptionalTargetPath(
    launchSpec,
    rawCodexHome.startsWith("/") ? rawCodexHome : launchSpec.pathMapper.toTargetPath(rawCodexHome)
  ) : normalizeOptionalTargetPath(launchSpec, rawCodexHome);
  if (envCodexHome) {
    return envCodexHome;
  }
  if (launchSpec.target.method === "wsl") {
    return null;
  }
  const homeVar = launchSpec.target.platformFamily === "windows" ? launchSpec.env.USERPROFILE : launchSpec.env.HOME;
  const homeDir = normalizeOptionalTargetPath(launchSpec, homeVar);
  return homeDir ? joinTargetPath(launchSpec, homeDir, ".codex") : null;
}
function resolveCodexHomeTarget(launchSpec, initializeResult) {
  var _a3;
  return (_a3 = normalizeOptionalTargetPath(launchSpec, initializeResult.codexHome)) != null ? _a3 : resolveFallbackCodexHomeTarget(launchSpec);
}
function validateInitializeTarget(launchSpec, initializeResult) {
  if (initializeResult.platformOs !== launchSpec.target.platformOs) {
    throw new Error(
      `Codex target mismatch: expected ${launchSpec.target.platformOs}, received ${initializeResult.platformOs}`
    );
  }
  if (initializeResult.platformFamily !== launchSpec.target.platformFamily) {
    throw new Error(
      `Codex target mismatch: expected ${launchSpec.target.platformFamily}, received ${initializeResult.platformFamily}`
    );
  }
}
function createCodexRuntimeContext(launchSpec, initializeResult) {
  validateInitializeTarget(launchSpec, initializeResult);
  const codexHomeTarget = resolveCodexHomeTarget(launchSpec, initializeResult);
  const sessionsDirTarget = codexHomeTarget ? joinTargetPath(launchSpec, codexHomeTarget, "sessions") : null;
  const memoriesDirTarget = codexHomeTarget ? joinTargetPath(launchSpec, codexHomeTarget, "memories") : null;
  return {
    launchSpec,
    initializeResult,
    codexHomeTarget,
    codexHomeHost: codexHomeTarget ? launchSpec.pathMapper.toHostPath(codexHomeTarget) : null,
    sessionsDirTarget,
    sessionsDirHost: sessionsDirTarget ? launchSpec.pathMapper.toHostPath(sessionsDirTarget) : null,
    memoriesDirTarget
  };
}

// src/providers/codex/skills/CodexSkillListingService.ts
var DEFAULT_SKILL_LIST_TTL_MS = 5e3;
var SKILL_SCOPE_PRIORITY = {
  repo: 0,
  user: 1,
  system: 2,
  admin: 3
};
function compareCodexSkillPriority(left, right) {
  const scopeDelta = SKILL_SCOPE_PRIORITY[left.scope] - SKILL_SCOPE_PRIORITY[right.scope];
  if (scopeDelta !== 0) {
    return scopeDelta;
  }
  const nameDelta = left.name.localeCompare(right.name);
  if (nameDelta !== 0) {
    return nameDelta;
  }
  return left.path.localeCompare(right.path);
}
function extractExplicitCodexSkillNames(text) {
  const matches = text.matchAll(/(^|\s)\$([A-Za-z0-9_-]+)/g);
  const names = [];
  const seen = /* @__PURE__ */ new Set();
  for (const match of matches) {
    const name = match[2];
    if (!name) {
      continue;
    }
    const normalized = name.toLowerCase();
    if (seen.has(normalized)) {
      continue;
    }
    seen.add(normalized);
    names.push(name);
  }
  return names;
}
function getCodexSkillDescription(skill) {
  var _a3, _b2, _c, _d2;
  return (_d2 = (_c = (_b2 = (_a3 = skill.interface) == null ? void 0 : _a3.shortDescription) != null ? _b2 : skill.shortDescription) != null ? _c : skill.description) != null ? _d2 : void 0;
}
function findPreferredCodexSkillByName(skills, name) {
  var _a3;
  const normalized = name.toLowerCase();
  const candidates = skills.filter((skill) => skill.enabled && skill.name.toLowerCase() === normalized).sort(compareCodexSkillPriority);
  return (_a3 = candidates[0]) != null ? _a3 : null;
}
var CodexSkillListingService = class {
  constructor(plugin, options = {}) {
    this.plugin = plugin;
    this.cache = null;
    this.cacheExpiresAt = 0;
    this.pending = null;
    var _a3, _b2;
    this.ttlMs = (_a3 = options.ttlMs) != null ? _a3 : DEFAULT_SKILL_LIST_TTL_MS;
    this.now = (_b2 = options.now) != null ? _b2 : (() => Date.now());
  }
  async listSkills(options) {
    if (options == null ? void 0 : options.forceReload) {
      const skills = await this.fetchSkills(true);
      this.storeCache(skills);
      return skills;
    }
    if (this.cache && this.now() < this.cacheExpiresAt) {
      return this.cache;
    }
    if (this.pending) {
      return this.pending;
    }
    this.pending = this.fetchSkills(false).then((skills) => {
      this.storeCache(skills);
      return skills;
    }).finally(() => {
      this.pending = null;
    });
    return this.pending;
  }
  invalidate() {
    this.cache = null;
    this.cacheExpiresAt = 0;
  }
  async fetchSkills(forceReload) {
    var _a3, _b2;
    const launchSpec = resolveCodexAppServerLaunchSpec(this.plugin, "codex");
    const process4 = new CodexAppServerProcess(launchSpec);
    process4.start();
    const transport = new CodexRpcTransport(process4);
    transport.start();
    try {
      const initializeResult = await initializeCodexAppServerTransport(transport);
      createCodexRuntimeContext(launchSpec, initializeResult);
      const result = await transport.request("skills/list", {
        cwds: [launchSpec.targetCwd],
        ...forceReload ? { forceReload: true } : {}
      });
      const entry = (_a3 = result.data.find((candidate) => candidate.cwd === launchSpec.targetCwd)) != null ? _a3 : result.data[0];
      return ((_b2 = entry == null ? void 0 : entry.skills) != null ? _b2 : []).map((skill) => {
        var _a4;
        return {
          ...skill,
          path: (_a4 = launchSpec.pathMapper.toHostPath(skill.path)) != null ? _a4 : skill.path
        };
      });
    } finally {
      transport.dispose();
      await process4.shutdown();
    }
  }
  storeCache(skills) {
    this.cache = skills;
    this.cacheExpiresAt = this.now() + this.ttlMs;
  }
};

// src/providers/codex/storage/CodexSkillStorage.ts
var path12 = __toESM(require("path"));
var CODEX_VAULT_SKILLS_PATH = ".codex/skills";
var AGENTS_VAULT_SKILLS_PATH = ".agents/skills";
var CODEX_SKILL_ROOT_OPTIONS = [
  { id: "vault-codex", label: CODEX_VAULT_SKILLS_PATH },
  { id: "vault-agents", label: AGENTS_VAULT_SKILLS_PATH }
];
var ROOT_PATH_BY_ID = {
  "vault-codex": CODEX_VAULT_SKILLS_PATH,
  "vault-agents": AGENTS_VAULT_SKILLS_PATH
};
var ROOT_ID_BY_PATH = new Map(
  Object.entries(ROOT_PATH_BY_ID).map(([rootId, rootPath]) => [rootPath, rootId])
);
var ALL_SCAN_ROOTS = ["vault-codex", "vault-agents"];
var SKILL_PERSISTENCE_PREFIX = "codex-skill";
function createCodexSkillPersistenceKey(state) {
  const parts = [SKILL_PERSISTENCE_PREFIX, state.rootId];
  if (state.currentName) {
    parts.push(encodeURIComponent(state.currentName));
  }
  return parts.join(":");
}
function parseCodexSkillPersistenceKey(persistenceKey) {
  if (!persistenceKey) {
    return null;
  }
  const legacyRootId = ROOT_ID_BY_PATH.get(persistenceKey);
  if (legacyRootId) {
    return { rootId: legacyRootId };
  }
  const [prefix, rootId, encodedName] = persistenceKey.split(":");
  if (prefix !== SKILL_PERSISTENCE_PREFIX) {
    return null;
  }
  if (rootId !== "vault-codex" && rootId !== "vault-agents") {
    return null;
  }
  return {
    rootId,
    ...encodedName ? { currentName: decodeURIComponent(encodedName) } : {}
  };
}
function resolveCodexSkillLocationFromPath(skillPath, vaultPath) {
  const usesWindowsPathSemantics = /^[A-Za-z]:[\\/]/.test(skillPath) || /^[A-Za-z]:[\\/]/.test(vaultPath) || skillPath.startsWith("\\\\") || vaultPath.startsWith("\\\\");
  const pathApi = usesWindowsPathSemantics ? path12.win32 : path12.posix;
  const normalizedSkillPath = pathApi.normalize(skillPath);
  const normalizedVaultPath = pathApi.normalize(vaultPath);
  for (const [rootId, rootPath] of Object.entries(ROOT_PATH_BY_ID)) {
    const rootDir = pathApi.normalize(pathApi.join(normalizedVaultPath, rootPath));
    const relative4 = pathApi.relative(rootDir, normalizedSkillPath);
    if (!relative4 || relative4.startsWith(`..${pathApi.sep}`) || relative4 === "..") {
      continue;
    }
    const parts = relative4.split(pathApi.sep);
    if (parts.length !== 2 || parts[1] !== "SKILL.md" || !parts[0]) {
      continue;
    }
    return {
      name: parts[0],
      rootId
    };
  }
  return null;
}
var CodexSkillStorage = class {
  constructor(vaultAdapter, homeAdapter) {
    this.vaultAdapter = vaultAdapter;
    this.homeAdapter = homeAdapter;
  }
  async scanAll() {
    const vaultSkills = await this.scanRoots(this.vaultAdapter, ALL_SCAN_ROOTS, "vault");
    const homeSkills = this.homeAdapter ? await this.scanRoots(this.homeAdapter, ALL_SCAN_ROOTS, "home") : [];
    const seen = new Set(vaultSkills.map((s4) => s4.name.toLowerCase()));
    const deduped = homeSkills.filter((s4) => !seen.has(s4.name.toLowerCase()));
    return [...vaultSkills, ...deduped];
  }
  async scanVault() {
    return this.scanRoots(this.vaultAdapter, ALL_SCAN_ROOTS, "vault");
  }
  async save(input) {
    var _a3;
    const targetRootId = (_a3 = input.rootId) != null ? _a3 : "vault-codex";
    const targetLocation = { rootId: targetRootId, name: input.name };
    const { dirPath, filePath } = this.buildLocationPaths(targetLocation);
    const previousLocation = input.previousLocation;
    await this.vaultAdapter.ensureFolder(dirPath);
    const markdown = serializeSlashCommandMarkdown(
      { name: input.name, description: input.description },
      input.content
    );
    await this.vaultAdapter.write(filePath, markdown);
    if (previousLocation && (previousLocation.rootId !== targetRootId || previousLocation.name !== input.name)) {
      await this.delete(previousLocation);
    }
  }
  async delete(location) {
    const { dirPath, filePath } = this.buildLocationPaths(location);
    await this.vaultAdapter.delete(filePath);
    await this.vaultAdapter.deleteFolder(dirPath);
  }
  async load(location) {
    const { filePath } = this.buildLocationPaths(location);
    try {
      const content = await this.vaultAdapter.read(filePath);
      const parsed = parseSlashCommandContent(content);
      return {
        name: location.name,
        description: parsed.description,
        content: parsed.promptContent,
        provenance: "vault",
        rootId: location.rootId
      };
    } catch (e2) {
      return null;
    }
  }
  async scanRoots(adapter, roots, provenance) {
    const results = [];
    for (const rootId of roots) {
      const rootPath = ROOT_PATH_BY_ID[rootId];
      try {
        const folders = await adapter.listFolders(rootPath);
        for (const folder of folders) {
          const skillName = folder.split("/").pop();
          const skillPath = `${rootPath}/${skillName}/SKILL.md`;
          try {
            const content = await adapter.read(skillPath);
            const parsed = parseSlashCommandContent(content);
            results.push({
              name: skillName,
              description: parsed.description,
              content: parsed.promptContent,
              provenance,
              rootId
            });
          } catch (e2) {
          }
        }
      } catch (e2) {
      }
    }
    return results;
  }
  buildLocationPaths(location) {
    const rootPath = ROOT_PATH_BY_ID[location.rootId];
    const dirPath = `${rootPath}/${location.name}`;
    return {
      dirPath,
      filePath: `${dirPath}/SKILL.md`
    };
  }
};

// src/providers/codex/commands/CodexSkillCatalog.ts
var CODEX_SKILL_ID_PREFIX = "codex-skill-";
var CODEX_COMPACT_COMMAND = {
  id: "codex-builtin-compact",
  providerId: "codex",
  kind: "command",
  name: "compact",
  description: "Compact conversation history",
  content: "",
  scope: "system",
  source: "builtin",
  isEditable: false,
  isDeletable: false,
  displayPrefix: "/",
  insertPrefix: "/"
};
function buildSkillId(skill, location) {
  if (location) {
    return `${CODEX_SKILL_ID_PREFIX}${location.rootId}-${location.name}`;
  }
  const encodedPath = encodeURIComponent(skill.path);
  return `${CODEX_SKILL_ID_PREFIX}${skill.scope}-${encodedPath}`;
}
function listedSkillToProviderEntry(skill, vaultPath) {
  const location = vaultPath ? resolveCodexSkillLocationFromPath(skill.path, vaultPath) : null;
  const isVault = skill.scope === "repo" && location !== null;
  return {
    id: buildSkillId(skill, isVault ? location : null),
    providerId: "codex",
    kind: "skill",
    name: skill.name,
    description: getCodexSkillDescription(skill),
    content: "",
    scope: isVault ? "vault" : "user",
    source: "user",
    isEditable: isVault,
    isDeletable: isVault,
    displayPrefix: "$",
    insertPrefix: "$",
    ...isVault ? {
      persistenceKey: createCodexSkillPersistenceKey({
        rootId: location.rootId,
        currentName: location.name
      })
    } : {}
  };
}
var CodexSkillCatalog = class {
  constructor(storage, listProvider, vaultPath) {
    this.storage = storage;
    this.listProvider = listProvider;
    this.vaultPath = vaultPath;
  }
  setRuntimeCommands(_commands) {
  }
  async listDropdownEntries(context) {
    const skills = (await this.listProvider.listSkills()).filter((skill) => skill.enabled).sort(compareCodexSkillPriority);
    const entries = skills.map((skill) => listedSkillToProviderEntry(skill, this.vaultPath));
    return context.includeBuiltIns ? [CODEX_COMPACT_COMMAND, ...entries] : entries;
  }
  async listVaultEntries() {
    var _a3;
    if (!this.vaultPath) {
      return [];
    }
    const listedSkills = (await this.listProvider.listSkills()).filter((skill) => skill.scope === "repo").sort(compareCodexSkillPriority);
    const entries = [];
    for (const listedSkill of listedSkills) {
      const location = resolveCodexSkillLocationFromPath(listedSkill.path, this.vaultPath);
      if (!location) {
        continue;
      }
      const storedSkill = await this.storage.load(location);
      if (!storedSkill) {
        continue;
      }
      entries.push({
        id: `${CODEX_SKILL_ID_PREFIX}${location.rootId}-${storedSkill.name}`,
        providerId: "codex",
        kind: "skill",
        name: storedSkill.name,
        description: (_a3 = storedSkill.description) != null ? _a3 : getCodexSkillDescription(listedSkill),
        content: storedSkill.content,
        scope: "vault",
        source: "user",
        isEditable: true,
        isDeletable: true,
        displayPrefix: "$",
        insertPrefix: "$",
        persistenceKey: createCodexSkillPersistenceKey({
          rootId: location.rootId,
          currentName: location.name
        })
      });
    }
    return entries;
  }
  async saveVaultEntry(entry) {
    const persistenceState = parseCodexSkillPersistenceKey(entry.persistenceKey);
    await this.storage.save({
      name: entry.name,
      description: entry.description,
      content: entry.content,
      rootId: persistenceState == null ? void 0 : persistenceState.rootId,
      previousLocation: (persistenceState == null ? void 0 : persistenceState.currentName) ? { rootId: persistenceState.rootId, name: persistenceState.currentName } : void 0
    });
    this.listProvider.invalidate();
  }
  async deleteVaultEntry(entry) {
    var _a3, _b2;
    const persistenceState = parseCodexSkillPersistenceKey(entry.persistenceKey);
    await this.storage.delete({
      name: (_a3 = persistenceState == null ? void 0 : persistenceState.currentName) != null ? _a3 : entry.name,
      rootId: (_b2 = persistenceState == null ? void 0 : persistenceState.rootId) != null ? _b2 : "vault-codex"
    });
    this.listProvider.invalidate();
  }
  getDropdownConfig() {
    return {
      providerId: "codex",
      triggerChars: ["/", "$"],
      builtInPrefix: "/",
      skillPrefix: "$",
      commandPrefix: "/"
    };
  }
  async refresh() {
    this.listProvider.invalidate();
    await this.listProvider.listSkills({ forceReload: true });
  }
};

// src/providers/codex/runtime/CodexCliResolver.ts
init_env();

// src/providers/codex/runtime/CodexBinaryLocator.ts
var fs12 = __toESM(require("fs"));
var path13 = __toESM(require("path"));
init_env();
init_path();
function isExistingFile2(filePath) {
  try {
    return fs12.statSync(filePath).isFile();
  } catch (e2) {
    return false;
  }
}
function resolveConfiguredPath2(configuredPath) {
  const trimmed = (configuredPath != null ? configuredPath : "").trim();
  if (!trimmed) {
    return null;
  }
  try {
    const expandedPath = expandHomePath(trimmed);
    return isExistingFile2(expandedPath) ? expandedPath : null;
  } catch (e2) {
    return null;
  }
}
function isWindowsStyleCliReference(value) {
  const trimmed = (value != null ? value : "").trim();
  if (!trimmed) {
    return false;
  }
  return /^[A-Za-z]:[\\/]/.test(trimmed) || trimmed.startsWith("\\\\") || /\.(?:exe|cmd|bat|ps1)$/i.test(trimmed);
}
function findCodexBinaryPath(additionalPath, platform = process.platform) {
  const binaryNames = platform === "win32" ? ["codex.exe", "codex.cmd", "codex"] : ["codex"];
  const searchEntries = parsePathEntries(getEnhancedPath(additionalPath));
  for (const dir of searchEntries) {
    if (!dir) continue;
    for (const binaryName of binaryNames) {
      const candidate = path13.join(dir, binaryName);
      if (isExistingFile2(candidate)) {
        return candidate;
      }
    }
  }
  return null;
}
function resolveCodexCliPath(hostnamePath, legacyPath, envText, options = {}) {
  var _a3;
  const hostPlatform = (_a3 = options.hostPlatform) != null ? _a3 : process.platform;
  if (hostPlatform === "win32" && options.installationMethod === "wsl") {
    const configuredCommand = [hostnamePath, legacyPath].map((value) => (value != null ? value : "").trim()).find((value) => value.length > 0 && !isWindowsStyleCliReference(value));
    return configuredCommand || "codex";
  }
  const configuredHostnamePath = resolveConfiguredPath2(hostnamePath);
  if (configuredHostnamePath) {
    return configuredHostnamePath;
  }
  const configuredLegacyPath = resolveConfiguredPath2(legacyPath);
  if (configuredLegacyPath) {
    return configuredLegacyPath;
  }
  const customEnv = parseEnvironmentVariables(envText || "");
  return findCodexBinaryPath(customEnv.PATH, hostPlatform);
}

// src/providers/codex/runtime/CodexCliResolver.ts
var CodexCliResolver = class {
  constructor() {
    this.resolvedPath = null;
    this.lastHostnamePath = "";
    this.lastLegacyPath = "";
    this.lastEnvText = "";
    this.lastInstallationMethod = "";
    this.cachedHostname = getHostnameKey();
  }
  resolveFromSettings(settings11) {
    var _a3;
    const codexSettings = getCodexProviderSettings(settings11);
    const hostnamePath = ((_a3 = codexSettings.cliPathsByHost[this.cachedHostname]) != null ? _a3 : "").trim();
    const legacyPath = codexSettings.cliPath.trim();
    const envText = getRuntimeEnvironmentText(settings11, "codex");
    const installationMethod = codexSettings.installationMethod;
    if (this.resolvedPath && hostnamePath === this.lastHostnamePath && legacyPath === this.lastLegacyPath && envText === this.lastEnvText && installationMethod === this.lastInstallationMethod) {
      return this.resolvedPath;
    }
    this.lastHostnamePath = hostnamePath;
    this.lastLegacyPath = legacyPath;
    this.lastEnvText = envText;
    this.lastInstallationMethod = installationMethod;
    this.resolvedPath = resolveCodexCliPath(hostnamePath, legacyPath, envText, {
      installationMethod
    });
    return this.resolvedPath;
  }
  resolve(hostnamePaths, legacyPath, envText, options = {}) {
    var _a3;
    const hostnamePath = ((_a3 = hostnamePaths == null ? void 0 : hostnamePaths[this.cachedHostname]) != null ? _a3 : "").trim();
    const normalizedLegacyPath = (legacyPath != null ? legacyPath : "").trim();
    return resolveCodexCliPath(hostnamePath, normalizedLegacyPath, envText, options);
  }
  reset() {
    this.resolvedPath = null;
    this.lastHostnamePath = "";
    this.lastLegacyPath = "";
    this.lastEnvText = "";
    this.lastInstallationMethod = "";
  }
};

// node_modules/smol-toml/dist/error.js
function getLineColFromPtr(string5, ptr) {
  let lines = string5.slice(0, ptr).split(/\r\n|\n|\r/g);
  return [lines.length, lines.pop().length + 1];
}
function makeCodeBlock(string5, line, column) {
  let lines = string5.split(/\r\n|\n|\r/g);
  let codeblock = "";
  let numberLen = (Math.log10(line + 1) | 0) + 1;
  for (let i2 = line - 1; i2 <= line + 1; i2++) {
    let l2 = lines[i2 - 1];
    if (!l2)
      continue;
    codeblock += i2.toString().padEnd(numberLen, " ");
    codeblock += ":  ";
    codeblock += l2;
    codeblock += "\n";
    if (i2 === line) {
      codeblock += " ".repeat(numberLen + column + 2);
      codeblock += "^\n";
    }
  }
  return codeblock;
}
var TomlError = class extends Error {
  constructor(message, options) {
    const [line, column] = getLineColFromPtr(options.toml, options.ptr);
    const codeblock = makeCodeBlock(options.toml, line, column);
    super(`Invalid TOML document: ${message}

${codeblock}`, options);
    __publicField(this, "line");
    __publicField(this, "column");
    __publicField(this, "codeblock");
    this.line = line;
    this.column = column;
    this.codeblock = codeblock;
  }
};

// node_modules/smol-toml/dist/util.js
function isEscaped(str, ptr) {
  let i2 = 0;
  while (str[ptr - ++i2] === "\\")
    ;
  return --i2 && i2 % 2;
}
function indexOfNewline(str, start = 0, end = str.length) {
  let idx = str.indexOf("\n", start);
  if (str[idx - 1] === "\r")
    idx--;
  return idx <= end ? idx : -1;
}
function skipComment(str, ptr) {
  for (let i2 = ptr; i2 < str.length; i2++) {
    let c = str[i2];
    if (c === "\n")
      return i2;
    if (c === "\r" && str[i2 + 1] === "\n")
      return i2 + 1;
    if (c < " " && c !== "	" || c === "\x7F") {
      throw new TomlError("control characters are not allowed in comments", {
        toml: str,
        ptr
      });
    }
  }
  return str.length;
}
function skipVoid(str, ptr, banNewLines, banComments) {
  let c;
  while (1) {
    while ((c = str[ptr]) === " " || c === "	" || !banNewLines && (c === "\n" || c === "\r" && str[ptr + 1] === "\n"))
      ptr++;
    if (banComments || c !== "#")
      break;
    ptr = skipComment(str, ptr);
  }
  return ptr;
}
function skipUntil(str, ptr, sep2, end, banNewLines = false) {
  if (!end) {
    ptr = indexOfNewline(str, ptr);
    return ptr < 0 ? str.length : ptr;
  }
  for (let i2 = ptr; i2 < str.length; i2++) {
    let c = str[i2];
    if (c === "#") {
      i2 = indexOfNewline(str, i2);
    } else if (c === sep2) {
      return i2 + 1;
    } else if (c === end || banNewLines && (c === "\n" || c === "\r" && str[i2 + 1] === "\n")) {
      return i2;
    }
  }
  throw new TomlError("cannot find end of structure", {
    toml: str,
    ptr
  });
}
function getStringEnd(str, seek) {
  let first = str[seek];
  let target = first === str[seek + 1] && str[seek + 1] === str[seek + 2] ? str.slice(seek, seek + 3) : first;
  seek += target.length - 1;
  do
    seek = str.indexOf(target, ++seek);
  while (seek > -1 && first !== "'" && isEscaped(str, seek));
  if (seek > -1) {
    seek += target.length;
    if (target.length > 1) {
      if (str[seek] === first)
        seek++;
      if (str[seek] === first)
        seek++;
    }
  }
  return seek;
}

// node_modules/smol-toml/dist/date.js
var DATE_TIME_RE = /^(\d{4}-\d{2}-\d{2})?[T ]?(?:(\d{2}):\d{2}(?::\d{2}(?:\.\d+)?)?)?(Z|[-+]\d{2}:\d{2})?$/i;
var _hasDate, _hasTime, _offset;
var _TomlDate = class _TomlDate extends Date {
  constructor(date7) {
    let hasDate = true;
    let hasTime = true;
    let offset = "Z";
    if (typeof date7 === "string") {
      let match = date7.match(DATE_TIME_RE);
      if (match) {
        if (!match[1]) {
          hasDate = false;
          date7 = `0000-01-01T${date7}`;
        }
        hasTime = !!match[2];
        hasTime && date7[10] === " " && (date7 = date7.replace(" ", "T"));
        if (match[2] && +match[2] > 23) {
          date7 = "";
        } else {
          offset = match[3] || null;
          date7 = date7.toUpperCase();
          if (!offset && hasTime)
            date7 += "Z";
        }
      } else {
        date7 = "";
      }
    }
    super(date7);
    __privateAdd(this, _hasDate, false);
    __privateAdd(this, _hasTime, false);
    __privateAdd(this, _offset, null);
    if (!isNaN(this.getTime())) {
      __privateSet(this, _hasDate, hasDate);
      __privateSet(this, _hasTime, hasTime);
      __privateSet(this, _offset, offset);
    }
  }
  isDateTime() {
    return __privateGet(this, _hasDate) && __privateGet(this, _hasTime);
  }
  isLocal() {
    return !__privateGet(this, _hasDate) || !__privateGet(this, _hasTime) || !__privateGet(this, _offset);
  }
  isDate() {
    return __privateGet(this, _hasDate) && !__privateGet(this, _hasTime);
  }
  isTime() {
    return __privateGet(this, _hasTime) && !__privateGet(this, _hasDate);
  }
  isValid() {
    return __privateGet(this, _hasDate) || __privateGet(this, _hasTime);
  }
  toISOString() {
    let iso = super.toISOString();
    if (this.isDate())
      return iso.slice(0, 10);
    if (this.isTime())
      return iso.slice(11, 23);
    if (__privateGet(this, _offset) === null)
      return iso.slice(0, -1);
    if (__privateGet(this, _offset) === "Z")
      return iso;
    let offset = +__privateGet(this, _offset).slice(1, 3) * 60 + +__privateGet(this, _offset).slice(4, 6);
    offset = __privateGet(this, _offset)[0] === "-" ? offset : -offset;
    let offsetDate = new Date(this.getTime() - offset * 6e4);
    return offsetDate.toISOString().slice(0, -1) + __privateGet(this, _offset);
  }
  static wrapAsOffsetDateTime(jsDate, offset = "Z") {
    let date7 = new _TomlDate(jsDate);
    __privateSet(date7, _offset, offset);
    return date7;
  }
  static wrapAsLocalDateTime(jsDate) {
    let date7 = new _TomlDate(jsDate);
    __privateSet(date7, _offset, null);
    return date7;
  }
  static wrapAsLocalDate(jsDate) {
    let date7 = new _TomlDate(jsDate);
    __privateSet(date7, _hasTime, false);
    __privateSet(date7, _offset, null);
    return date7;
  }
  static wrapAsLocalTime(jsDate) {
    let date7 = new _TomlDate(jsDate);
    __privateSet(date7, _hasDate, false);
    __privateSet(date7, _offset, null);
    return date7;
  }
};
_hasDate = new WeakMap();
_hasTime = new WeakMap();
_offset = new WeakMap();
var TomlDate = _TomlDate;

// node_modules/smol-toml/dist/primitive.js
var INT_REGEX = /^((0x[0-9a-fA-F](_?[0-9a-fA-F])*)|(([+-]|0[ob])?\d(_?\d)*))$/;
var FLOAT_REGEX = /^[+-]?\d(_?\d)*(\.\d(_?\d)*)?([eE][+-]?\d(_?\d)*)?$/;
var LEADING_ZERO = /^[+-]?0[0-9_]/;
var ESCAPE_REGEX = /^[0-9a-f]{2,8}$/i;
var ESC_MAP = {
  b: "\b",
  t: "	",
  n: "\n",
  f: "\f",
  r: "\r",
  e: "\x1B",
  '"': '"',
  "\\": "\\"
};
function parseString(str, ptr = 0, endPtr = str.length) {
  let isLiteral = str[ptr] === "'";
  let isMultiline = str[ptr++] === str[ptr] && str[ptr] === str[ptr + 1];
  if (isMultiline) {
    endPtr -= 2;
    if (str[ptr += 2] === "\r")
      ptr++;
    if (str[ptr] === "\n")
      ptr++;
  }
  let tmp = 0;
  let isEscape;
  let parsed = "";
  let sliceStart = ptr;
  while (ptr < endPtr - 1) {
    let c = str[ptr++];
    if (c === "\n" || c === "\r" && str[ptr] === "\n") {
      if (!isMultiline) {
        throw new TomlError("newlines are not allowed in strings", {
          toml: str,
          ptr: ptr - 1
        });
      }
    } else if (c < " " && c !== "	" || c === "\x7F") {
      throw new TomlError("control characters are not allowed in strings", {
        toml: str,
        ptr: ptr - 1
      });
    }
    if (isEscape) {
      isEscape = false;
      if (c === "x" || c === "u" || c === "U") {
        let code = str.slice(ptr, ptr += c === "x" ? 2 : c === "u" ? 4 : 8);
        if (!ESCAPE_REGEX.test(code)) {
          throw new TomlError("invalid unicode escape", {
            toml: str,
            ptr: tmp
          });
        }
        try {
          parsed += String.fromCodePoint(parseInt(code, 16));
        } catch (e2) {
          throw new TomlError("invalid unicode escape", {
            toml: str,
            ptr: tmp
          });
        }
      } else if (isMultiline && (c === "\n" || c === " " || c === "	" || c === "\r")) {
        ptr = skipVoid(str, ptr - 1, true);
        if (str[ptr] !== "\n" && str[ptr] !== "\r") {
          throw new TomlError("invalid escape: only line-ending whitespace may be escaped", {
            toml: str,
            ptr: tmp
          });
        }
        ptr = skipVoid(str, ptr);
      } else if (c in ESC_MAP) {
        parsed += ESC_MAP[c];
      } else {
        throw new TomlError("unrecognized escape sequence", {
          toml: str,
          ptr: tmp
        });
      }
      sliceStart = ptr;
    } else if (!isLiteral && c === "\\") {
      tmp = ptr - 1;
      isEscape = true;
      parsed += str.slice(sliceStart, tmp);
    }
  }
  return parsed + str.slice(sliceStart, endPtr - 1);
}
function parseValue(value, toml, ptr, integersAsBigInt) {
  if (value === "true")
    return true;
  if (value === "false")
    return false;
  if (value === "-inf")
    return -Infinity;
  if (value === "inf" || value === "+inf")
    return Infinity;
  if (value === "nan" || value === "+nan" || value === "-nan")
    return NaN;
  if (value === "-0")
    return integersAsBigInt ? /* @__PURE__ */ BigInt("0") : 0;
  let isInt = INT_REGEX.test(value);
  if (isInt || FLOAT_REGEX.test(value)) {
    if (LEADING_ZERO.test(value)) {
      throw new TomlError("leading zeroes are not allowed", {
        toml,
        ptr
      });
    }
    value = value.replace(/_/g, "");
    let numeric = +value;
    if (isNaN(numeric)) {
      throw new TomlError("invalid number", {
        toml,
        ptr
      });
    }
    if (isInt) {
      if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {
        throw new TomlError("integer value cannot be represented losslessly", {
          toml,
          ptr
        });
      }
      if (isInt || integersAsBigInt === true)
        numeric = BigInt(value);
    }
    return numeric;
  }
  const date7 = new TomlDate(value);
  if (!date7.isValid()) {
    throw new TomlError("invalid value", {
      toml,
      ptr
    });
  }
  return date7;
}

// node_modules/smol-toml/dist/extract.js
function sliceAndTrimEndOf(str, startPtr, endPtr) {
  let value = str.slice(startPtr, endPtr);
  let commentIdx = value.indexOf("#");
  if (commentIdx > -1) {
    skipComment(str, commentIdx);
    value = value.slice(0, commentIdx);
  }
  return [value.trimEnd(), commentIdx];
}
function extractValue(str, ptr, end, depth, integersAsBigInt) {
  if (depth === 0) {
    throw new TomlError("document contains excessively nested structures. aborting.", {
      toml: str,
      ptr
    });
  }
  let c = str[ptr];
  if (c === "[" || c === "{") {
    let [value, endPtr2] = c === "[" ? parseArray(str, ptr, depth, integersAsBigInt) : parseInlineTable(str, ptr, depth, integersAsBigInt);
    if (end) {
      endPtr2 = skipVoid(str, endPtr2);
      if (str[endPtr2] === ",")
        endPtr2++;
      else if (str[endPtr2] !== end) {
        throw new TomlError("expected comma or end of structure", {
          toml: str,
          ptr: endPtr2
        });
      }
    }
    return [value, endPtr2];
  }
  let endPtr;
  if (c === '"' || c === "'") {
    endPtr = getStringEnd(str, ptr);
    let parsed = parseString(str, ptr, endPtr);
    if (end) {
      endPtr = skipVoid(str, endPtr);
      if (str[endPtr] && str[endPtr] !== "," && str[endPtr] !== end && str[endPtr] !== "\n" && str[endPtr] !== "\r") {
        throw new TomlError("unexpected character encountered", {
          toml: str,
          ptr: endPtr
        });
      }
      endPtr += +(str[endPtr] === ",");
    }
    return [parsed, endPtr];
  }
  endPtr = skipUntil(str, ptr, ",", end);
  let slice = sliceAndTrimEndOf(str, ptr, endPtr - +(str[endPtr - 1] === ","));
  if (!slice[0]) {
    throw new TomlError("incomplete key-value declaration: no value specified", {
      toml: str,
      ptr
    });
  }
  if (end && slice[1] > -1) {
    endPtr = skipVoid(str, ptr + slice[1]);
    endPtr += +(str[endPtr] === ",");
  }
  return [
    parseValue(slice[0], str, ptr, integersAsBigInt),
    endPtr
  ];
}

// node_modules/smol-toml/dist/struct.js
var KEY_PART_RE = /^[a-zA-Z0-9-_]+[ \t]*$/;
function parseKey(str, ptr, end = "=") {
  let dot = ptr - 1;
  let parsed = [];
  let endPtr = str.indexOf(end, ptr);
  if (endPtr < 0) {
    throw new TomlError("incomplete key-value: cannot find end of key", {
      toml: str,
      ptr
    });
  }
  do {
    let c = str[ptr = ++dot];
    if (c !== " " && c !== "	") {
      if (c === '"' || c === "'") {
        if (c === str[ptr + 1] && c === str[ptr + 2]) {
          throw new TomlError("multiline strings are not allowed in keys", {
            toml: str,
            ptr
          });
        }
        let eos = getStringEnd(str, ptr);
        if (eos < 0) {
          throw new TomlError("unfinished string encountered", {
            toml: str,
            ptr
          });
        }
        dot = str.indexOf(".", eos);
        let strEnd = str.slice(eos, dot < 0 || dot > endPtr ? endPtr : dot);
        let newLine = indexOfNewline(strEnd);
        if (newLine > -1) {
          throw new TomlError("newlines are not allowed in keys", {
            toml: str,
            ptr: ptr + dot + newLine
          });
        }
        if (strEnd.trimStart()) {
          throw new TomlError("found extra tokens after the string part", {
            toml: str,
            ptr: eos
          });
        }
        if (endPtr < eos) {
          endPtr = str.indexOf(end, eos);
          if (endPtr < 0) {
            throw new TomlError("incomplete key-value: cannot find end of key", {
              toml: str,
              ptr
            });
          }
        }
        parsed.push(parseString(str, ptr, eos));
      } else {
        dot = str.indexOf(".", ptr);
        let part = str.slice(ptr, dot < 0 || dot > endPtr ? endPtr : dot);
        if (!KEY_PART_RE.test(part)) {
          throw new TomlError("only letter, numbers, dashes and underscores are allowed in keys", {
            toml: str,
            ptr
          });
        }
        parsed.push(part.trimEnd());
      }
    }
  } while (dot + 1 && dot < endPtr);
  return [parsed, skipVoid(str, endPtr + 1, true, true)];
}
function parseInlineTable(str, ptr, depth, integersAsBigInt) {
  let res = {};
  let seen = /* @__PURE__ */ new Set();
  let c;
  ptr++;
  while ((c = str[ptr++]) !== "}" && c) {
    if (c === ",") {
      throw new TomlError("expected value, found comma", {
        toml: str,
        ptr: ptr - 1
      });
    } else if (c === "#")
      ptr = skipComment(str, ptr);
    else if (c !== " " && c !== "	" && c !== "\n" && c !== "\r") {
      let k10;
      let t2 = res;
      let hasOwn = false;
      let [key, keyEndPtr] = parseKey(str, ptr - 1);
      for (let i2 = 0; i2 < key.length; i2++) {
        if (i2)
          t2 = hasOwn ? t2[k10] : t2[k10] = {};
        k10 = key[i2];
        if ((hasOwn = Object.hasOwn(t2, k10)) && (typeof t2[k10] !== "object" || seen.has(t2[k10]))) {
          throw new TomlError("trying to redefine an already defined value", {
            toml: str,
            ptr
          });
        }
        if (!hasOwn && k10 === "__proto__") {
          Object.defineProperty(t2, k10, { enumerable: true, configurable: true, writable: true });
        }
      }
      if (hasOwn) {
        throw new TomlError("trying to redefine an already defined value", {
          toml: str,
          ptr
        });
      }
      let [value, valueEndPtr] = extractValue(str, keyEndPtr, "}", depth - 1, integersAsBigInt);
      seen.add(value);
      t2[k10] = value;
      ptr = valueEndPtr;
    }
  }
  if (!c) {
    throw new TomlError("unfinished table encountered", {
      toml: str,
      ptr
    });
  }
  return [res, ptr];
}
function parseArray(str, ptr, depth, integersAsBigInt) {
  let res = [];
  let c;
  ptr++;
  while ((c = str[ptr++]) !== "]" && c) {
    if (c === ",") {
      throw new TomlError("expected value, found comma", {
        toml: str,
        ptr: ptr - 1
      });
    } else if (c === "#")
      ptr = skipComment(str, ptr);
    else if (c !== " " && c !== "	" && c !== "\n" && c !== "\r") {
      let e2 = extractValue(str, ptr - 1, "]", depth - 1, integersAsBigInt);
      res.push(e2[0]);
      ptr = e2[1];
    }
  }
  if (!c) {
    throw new TomlError("unfinished array encountered", {
      toml: str,
      ptr
    });
  }
  return [res, ptr];
}

// node_modules/smol-toml/dist/parse.js
function peekTable(key, table, meta3, type) {
  var _a3, _b2;
  let t2 = table;
  let m2 = meta3;
  let k10;
  let hasOwn = false;
  let state;
  for (let i2 = 0; i2 < key.length; i2++) {
    if (i2) {
      t2 = hasOwn ? t2[k10] : t2[k10] = {};
      m2 = (state = m2[k10]).c;
      if (type === 0 && (state.t === 1 || state.t === 2)) {
        return null;
      }
      if (state.t === 2) {
        let l2 = t2.length - 1;
        t2 = t2[l2];
        m2 = m2[l2].c;
      }
    }
    k10 = key[i2];
    if ((hasOwn = Object.hasOwn(t2, k10)) && ((_a3 = m2[k10]) == null ? void 0 : _a3.t) === 0 && ((_b2 = m2[k10]) == null ? void 0 : _b2.d)) {
      return null;
    }
    if (!hasOwn) {
      if (k10 === "__proto__") {
        Object.defineProperty(t2, k10, { enumerable: true, configurable: true, writable: true });
        Object.defineProperty(m2, k10, { enumerable: true, configurable: true, writable: true });
      }
      m2[k10] = {
        t: i2 < key.length - 1 && type === 2 ? 3 : type,
        d: false,
        i: 0,
        c: {}
      };
    }
  }
  state = m2[k10];
  if (state.t !== type && !(type === 1 && state.t === 3)) {
    return null;
  }
  if (type === 2) {
    if (!state.d) {
      state.d = true;
      t2[k10] = [];
    }
    t2[k10].push(t2 = {});
    state.c[state.i++] = state = { t: 1, d: false, i: 0, c: {} };
  }
  if (state.d) {
    return null;
  }
  state.d = true;
  if (type === 1) {
    t2 = hasOwn ? t2[k10] : t2[k10] = {};
  } else if (type === 0 && hasOwn) {
    return null;
  }
  return [k10, t2, state.c];
}
function parse3(toml, { maxDepth = 1e3, integersAsBigInt } = {}) {
  let res = {};
  let meta3 = {};
  let tbl = res;
  let m2 = meta3;
  for (let ptr = skipVoid(toml, 0); ptr < toml.length; ) {
    if (toml[ptr] === "[") {
      let isTableArray = toml[++ptr] === "[";
      let k10 = parseKey(toml, ptr += +isTableArray, "]");
      if (isTableArray) {
        if (toml[k10[1] - 1] !== "]") {
          throw new TomlError("expected end of table declaration", {
            toml,
            ptr: k10[1] - 1
          });
        }
        k10[1]++;
      }
      let p = peekTable(
        k10[0],
        res,
        meta3,
        isTableArray ? 2 : 1
        /* Type.EXPLICIT */
      );
      if (!p) {
        throw new TomlError("trying to redefine an already defined table or value", {
          toml,
          ptr
        });
      }
      m2 = p[2];
      tbl = p[1];
      ptr = k10[1];
    } else {
      let k10 = parseKey(toml, ptr);
      let p = peekTable(
        k10[0],
        tbl,
        m2,
        0
        /* Type.DOTTED */
      );
      if (!p) {
        throw new TomlError("trying to redefine an already defined table or value", {
          toml,
          ptr
        });
      }
      let v2 = extractValue(toml, k10[1], void 0, maxDepth, integersAsBigInt);
      p[1][p[0]] = v2[0];
      ptr = v2[1];
    }
    ptr = skipVoid(toml, ptr, true);
    if (toml[ptr] && toml[ptr] !== "\n" && toml[ptr] !== "\r") {
      throw new TomlError("each key-value declaration must be followed by an end-of-line", {
        toml,
        ptr
      });
    }
    ptr = skipVoid(toml, ptr);
  }
  return res;
}

// node_modules/smol-toml/dist/stringify.js
var BARE_KEY = /^[a-z0-9-_]+$/i;
function extendedTypeOf(obj) {
  let type = typeof obj;
  if (type === "object") {
    if (Array.isArray(obj))
      return "array";
    if (obj instanceof Date)
      return "date";
  }
  return type;
}
function isArrayOfTables(obj) {
  for (let i2 = 0; i2 < obj.length; i2++) {
    if (extendedTypeOf(obj[i2]) !== "object")
      return false;
  }
  return obj.length != 0;
}
function formatString(s4) {
  return JSON.stringify(s4).replace(/\x7f/g, "\\u007f");
}
function stringifyValue(val, type, depth, numberAsFloat) {
  if (depth === 0) {
    throw new Error("Could not stringify the object: maximum object depth exceeded");
  }
  if (type === "number") {
    if (isNaN(val))
      return "nan";
    if (val === Infinity)
      return "inf";
    if (val === -Infinity)
      return "-inf";
    if (numberAsFloat && Number.isInteger(val))
      return val.toFixed(1);
    return val.toString();
  }
  if (type === "bigint" || type === "boolean") {
    return val.toString();
  }
  if (type === "string") {
    return formatString(val);
  }
  if (type === "date") {
    if (isNaN(val.getTime())) {
      throw new TypeError("cannot serialize invalid date");
    }
    return val.toISOString();
  }
  if (type === "object") {
    return stringifyInlineTable(val, depth, numberAsFloat);
  }
  if (type === "array") {
    return stringifyArray(val, depth, numberAsFloat);
  }
}
function stringifyInlineTable(obj, depth, numberAsFloat) {
  let keys = Object.keys(obj);
  if (keys.length === 0)
    return "{}";
  let res = "{ ";
  for (let i2 = 0; i2 < keys.length; i2++) {
    let k10 = keys[i2];
    if (i2)
      res += ", ";
    res += BARE_KEY.test(k10) ? k10 : formatString(k10);
    res += " = ";
    res += stringifyValue(obj[k10], extendedTypeOf(obj[k10]), depth - 1, numberAsFloat);
  }
  return res + " }";
}
function stringifyArray(array2, depth, numberAsFloat) {
  if (array2.length === 0)
    return "[]";
  let res = "[ ";
  for (let i2 = 0; i2 < array2.length; i2++) {
    if (i2)
      res += ", ";
    if (array2[i2] === null || array2[i2] === void 0) {
      throw new TypeError("arrays cannot contain null or undefined values");
    }
    res += stringifyValue(array2[i2], extendedTypeOf(array2[i2]), depth - 1, numberAsFloat);
  }
  return res + " ]";
}
function stringifyArrayTable(array2, key, depth, numberAsFloat) {
  if (depth === 0) {
    throw new Error("Could not stringify the object: maximum object depth exceeded");
  }
  let res = "";
  for (let i2 = 0; i2 < array2.length; i2++) {
    res += `${res && "\n"}[[${key}]]
`;
    res += stringifyTable(0, array2[i2], key, depth, numberAsFloat);
  }
  return res;
}
function stringifyTable(tableKey, obj, prefix, depth, numberAsFloat) {
  if (depth === 0) {
    throw new Error("Could not stringify the object: maximum object depth exceeded");
  }
  let preamble = "";
  let tables = "";
  let keys = Object.keys(obj);
  for (let i2 = 0; i2 < keys.length; i2++) {
    let k10 = keys[i2];
    if (obj[k10] !== null && obj[k10] !== void 0) {
      let type = extendedTypeOf(obj[k10]);
      if (type === "symbol" || type === "function") {
        throw new TypeError(`cannot serialize values of type '${type}'`);
      }
      let key = BARE_KEY.test(k10) ? k10 : formatString(k10);
      if (type === "array" && isArrayOfTables(obj[k10])) {
        tables += (tables && "\n") + stringifyArrayTable(obj[k10], prefix ? `${prefix}.${key}` : key, depth - 1, numberAsFloat);
      } else if (type === "object") {
        let tblKey = prefix ? `${prefix}.${key}` : key;
        tables += (tables && "\n") + stringifyTable(tblKey, obj[k10], tblKey, depth - 1, numberAsFloat);
      } else {
        preamble += key;
        preamble += " = ";
        preamble += stringifyValue(obj[k10], type, depth, numberAsFloat);
        preamble += "\n";
      }
    }
  }
  if (tableKey && (preamble || !tables))
    preamble = preamble ? `[${tableKey}]
${preamble}` : `[${tableKey}]`;
  return preamble && tables ? `${preamble}
${tables}` : preamble || tables;
}
function stringify(obj, { maxDepth = 1e3, numbersAsFloat = false } = {}) {
  if (extendedTypeOf(obj) !== "object") {
    throw new TypeError("stringify can only be called with an object");
  }
  let str = stringifyTable(0, obj, "", maxDepth, numbersAsFloat);
  if (str[str.length - 1] !== "\n")
    return str + "\n";
  return str;
}

// src/providers/codex/types/subagent.ts
var CODEX_SUBAGENT_KNOWN_KEYS = /* @__PURE__ */ new Set([
  "name",
  "description",
  "developer_instructions",
  "nickname_candidates",
  "model",
  "model_reasoning_effort",
  "sandbox_mode"
]);

// src/providers/codex/storage/CodexSubagentStorage.ts
var CODEX_AGENTS_PATH = ".codex/agents";
var SUBAGENT_PERSISTENCE_PREFIX = "codex-subagent";
function createCodexSubagentPersistenceKey(location) {
  return `${SUBAGENT_PERSISTENCE_PREFIX}:${encodeURIComponent(location.fileName)}`;
}
function parseCodexSubagentPersistenceKey(persistenceKey) {
  if (!persistenceKey) {
    return null;
  }
  if (persistenceKey.startsWith(`${CODEX_AGENTS_PATH}/`) && persistenceKey.endsWith(".toml")) {
    return { fileName: persistenceKey.slice(CODEX_AGENTS_PATH.length + 1) };
  }
  const [prefix, encodedFileName] = persistenceKey.split(":");
  if (prefix !== SUBAGENT_PERSISTENCE_PREFIX || !encodedFileName) {
    return null;
  }
  const fileName = decodeURIComponent(encodedFileName);
  return fileName.endsWith(".toml") ? { fileName } : null;
}
var CodexSubagentStorage = class {
  constructor(vaultAdapter) {
    this.vaultAdapter = vaultAdapter;
  }
  async loadAll() {
    return this.scanAdapter(this.vaultAdapter);
  }
  async load(agent) {
    const filePath = this.resolveCurrentPath(agent);
    try {
      if (!await this.vaultAdapter.exists(filePath)) return null;
      const content = await this.vaultAdapter.read(filePath);
      return parseSubagentToml(content, filePath);
    } catch (e2) {
      return null;
    }
  }
  async save(agent, previous) {
    const filePath = this.resolveTargetPath(agent, previous);
    const previousPath = previous ? this.resolveCurrentPath(previous) : null;
    await this.vaultAdapter.ensureFolder(CODEX_AGENTS_PATH);
    const content = serializeSubagentToml(agent);
    await this.vaultAdapter.write(filePath, content);
    if (previousPath && previousPath !== filePath) {
      await this.vaultAdapter.delete(previousPath);
    }
  }
  async delete(agent) {
    const filePath = this.resolveCurrentPath(agent);
    await this.vaultAdapter.delete(filePath);
  }
  resolveCurrentPath(agent) {
    const persistedLocation = parseCodexSubagentPersistenceKey(agent.persistenceKey);
    if (persistedLocation) {
      return `${CODEX_AGENTS_PATH}/${persistedLocation.fileName}`;
    }
    return `${CODEX_AGENTS_PATH}/${agent.name}.toml`;
  }
  resolveTargetPath(agent, previous) {
    if (previous && previous.name === agent.name) {
      return this.resolveCurrentPath(previous);
    }
    return `${CODEX_AGENTS_PATH}/${agent.name}.toml`;
  }
  async scanAdapter(adapter) {
    const results = [];
    try {
      const files = await adapter.listFiles(CODEX_AGENTS_PATH);
      for (const filePath of files) {
        if (!filePath.endsWith(".toml")) continue;
        try {
          const content = await adapter.read(filePath);
          const agent = parseSubagentToml(content, filePath);
          if (agent) results.push(agent);
        } catch (e2) {
        }
      }
    } catch (e2) {
    }
    return results;
  }
};
function parseSubagentToml(content, filePath) {
  var _a3;
  let parsed;
  try {
    parsed = parse3(content);
  } catch (e2) {
    return null;
  }
  const name = typeof parsed.name === "string" ? parsed.name : void 0;
  const description = typeof parsed.description === "string" ? parsed.description : void 0;
  const developerInstructions = typeof parsed.developer_instructions === "string" ? parsed.developer_instructions : void 0;
  if (!name || !description || !developerInstructions) return null;
  const result = {
    name,
    description,
    developerInstructions,
    persistenceKey: createCodexSubagentPersistenceKey({
      fileName: filePath.startsWith(`${CODEX_AGENTS_PATH}/`) ? filePath.slice(CODEX_AGENTS_PATH.length + 1) : (_a3 = filePath.split("/").pop()) != null ? _a3 : filePath
    })
  };
  if (typeof parsed.model === "string") {
    result.model = parsed.model;
  }
  if (typeof parsed.model_reasoning_effort === "string") {
    result.modelReasoningEffort = parsed.model_reasoning_effort;
  }
  if (typeof parsed.sandbox_mode === "string") {
    result.sandboxMode = parsed.sandbox_mode;
  }
  if (Array.isArray(parsed.nickname_candidates)) {
    const candidates = parsed.nickname_candidates.filter(
      (v2) => typeof v2 === "string"
    );
    if (candidates.length > 0) result.nicknameCandidates = candidates;
  }
  const extraFields = {};
  for (const [key, value] of Object.entries(parsed)) {
    if (!CODEX_SUBAGENT_KNOWN_KEYS.has(key)) {
      extraFields[key] = value;
    }
  }
  if (Object.keys(extraFields).length > 0) {
    result.extraFields = extraFields;
  }
  return result;
}
function serializeSubagentToml(agent) {
  const doc = {
    name: agent.name,
    description: agent.description,
    developer_instructions: agent.developerInstructions
  };
  if (agent.nicknameCandidates && agent.nicknameCandidates.length > 0) {
    doc.nickname_candidates = agent.nicknameCandidates;
  }
  if (agent.model) {
    doc.model = agent.model;
  }
  if (agent.modelReasoningEffort) {
    doc.model_reasoning_effort = agent.modelReasoningEffort;
  }
  if (agent.sandboxMode) {
    doc.sandbox_mode = agent.sandboxMode;
  }
  if (agent.extraFields) {
    for (const [key, value] of Object.entries(agent.extraFields)) {
      doc[key] = value;
    }
  }
  return stringify(doc);
}

// src/providers/codex/ui/CodexSettingsTab.ts
var fs13 = __toESM(require("fs"));
var import_obsidian17 = require("obsidian");
init_env();
init_path();

// src/providers/codex/modelOptions.ts
function createCustomCodexModelOption(modelId, description) {
  return {
    value: modelId,
    label: formatCodexModelLabel(modelId),
    description
  };
}
function getConfiguredEnvModel(settings11) {
  var _a3;
  const modelId = (_a3 = getRuntimeEnvironmentVariables(settings11, "codex").OPENAI_MODEL) == null ? void 0 : _a3.trim();
  return modelId ? modelId : null;
}
function getConfiguredEnvCustomModel(settings11) {
  const modelId = getConfiguredEnvModel(settings11);
  return modelId && !DEFAULT_CODEX_MODEL_SET.has(modelId) ? modelId : null;
}
function parseConfiguredCustomModelIds2(value) {
  const modelIds = [];
  const seen = /* @__PURE__ */ new Set();
  for (const line of value.split(/\r?\n/)) {
    const modelId = line.trim();
    if (!modelId || seen.has(modelId)) {
      continue;
    }
    seen.add(modelId);
    modelIds.push(modelId);
  }
  return modelIds;
}
function getCodexModelOptions(settings11) {
  const models = [...DEFAULT_CODEX_MODELS];
  const seenValues = new Set(models.map((model) => model.value));
  const envModel = getConfiguredEnvCustomModel(settings11);
  if (envModel) {
    seenValues.add(envModel);
    models.unshift(createCustomCodexModelOption(envModel, "Custom (env)"));
  }
  const codexSettings = getCodexProviderSettings(settings11);
  for (const modelId of parseConfiguredCustomModelIds2(codexSettings.customModels)) {
    if (seenValues.has(modelId)) {
      continue;
    }
    seenValues.add(modelId);
    models.push(createCustomCodexModelOption(modelId, "Custom model"));
  }
  return models;
}
function resolveCodexModelSelection(settings11, currentModel) {
  var _a3, _b2;
  const envModel = getConfiguredEnvModel(settings11);
  if (envModel) {
    return envModel;
  }
  const modelOptions = getCodexModelOptions(settings11);
  if (currentModel && modelOptions.some((option) => option.value === currentModel)) {
    return currentModel;
  }
  return (_b2 = (_a3 = modelOptions[0]) == null ? void 0 : _a3.value) != null ? _b2 : DEFAULT_CODEX_PRIMARY_MODEL;
}

// src/providers/codex/ui/CodexSkillSettings.ts
var import_obsidian15 = require("obsidian");
var CodexSkillModal = class extends import_obsidian15.Modal {
  constructor(app, existing, onSave) {
    var _a3, _b2;
    super(app);
    this.existing = existing;
    this.onSave = onSave;
    this._selectedRootId = (_b2 = (_a3 = parseCodexSkillPersistenceKey(existing == null ? void 0 : existing.persistenceKey)) == null ? void 0 : _a3.rootId) != null ? _b2 : "vault-codex";
  }
  /** Exposed for unit tests only. */
  getTestInputs() {
    return {
      nameInput: this._nameInput,
      descInput: this._descInput,
      contentArea: this._contentArea,
      setDirectory: (rootId) => {
        this._selectedRootId = rootId;
      },
      triggerSave: this._triggerSave
    };
  }
  onOpen() {
    var _a3;
    this.setTitle(this.existing ? "Edit Codex Skill" : "Add Codex Skill");
    this.modalEl.addClass("claudian-sp-modal");
    const { contentEl } = this;
    new import_obsidian15.Setting(contentEl).setName("Directory").setDesc("Where to store the skill").addDropdown((dropdown) => {
      for (const opt of CODEX_SKILL_ROOT_OPTIONS) {
        dropdown.addOption(opt.id, opt.label);
      }
      dropdown.setValue(this._selectedRootId);
      dropdown.onChange((value) => {
        this._selectedRootId = value;
      });
    });
    new import_obsidian15.Setting(contentEl).setName("Skill name").setDesc('The name used after $ (e.g., "analyze" for $analyze)').addText((text) => {
      var _a4;
      this._nameInput = text.inputEl;
      text.setValue(((_a4 = this.existing) == null ? void 0 : _a4.name) || "").setPlaceholder("analyze-code");
    });
    new import_obsidian15.Setting(contentEl).setName("Description").setDesc("Optional description shown in dropdown").addText((text) => {
      var _a4;
      this._descInput = text.inputEl;
      text.setValue(((_a4 = this.existing) == null ? void 0 : _a4.description) || "");
    });
    new import_obsidian15.Setting(contentEl).setName("Instructions").setDesc("The skill instructions (SKILL.md content)");
    const contentArea = contentEl.createEl("textarea", {
      cls: "claudian-sp-content-area",
      attr: { rows: "10", placeholder: "Analyze the code for..." }
    });
    contentArea.value = ((_a3 = this.existing) == null ? void 0 : _a3.content) || "";
    this._contentArea = contentArea;
    const doSave = async () => {
      var _a4, _b2;
      const name = this._nameInput.value.trim();
      const nameError = validateCommandName(name);
      if (nameError) {
        new import_obsidian15.Notice(nameError);
        return;
      }
      const content = this._contentArea.value;
      if (!content.trim()) {
        new import_obsidian15.Notice("Instructions are required");
        return;
      }
      const entry = {
        id: ((_a4 = this.existing) == null ? void 0 : _a4.id) || `codex-skill-${name}`,
        providerId: "codex",
        kind: "skill",
        name,
        description: this._descInput.value.trim() || void 0,
        content,
        scope: "vault",
        source: "user",
        isEditable: true,
        isDeletable: true,
        displayPrefix: "$",
        insertPrefix: "$",
        persistenceKey: createCodexSkillPersistenceKey({
          rootId: this._selectedRootId,
          ...((_b2 = this.existing) == null ? void 0 : _b2.name) ? { currentName: this.existing.name } : {}
        })
      };
      try {
        await this.onSave(entry);
      } catch (e2) {
        new import_obsidian15.Notice("Failed to save Codex skill");
        return;
      }
      this.close();
    };
    this._triggerSave = doSave;
    const buttonContainer = contentEl.createDiv({ cls: "claudian-sp-modal-buttons" });
    const cancelBtn = buttonContainer.createEl("button", {
      text: "Cancel",
      cls: "claudian-cancel-btn"
    });
    cancelBtn.addEventListener("click", () => this.close());
    const saveBtn = buttonContainer.createEl("button", {
      text: "Save",
      cls: "claudian-save-btn"
    });
    saveBtn.addEventListener("click", doSave);
  }
  onClose() {
    this.contentEl.empty();
  }
};
var CodexSkillSettings = class {
  constructor(containerEl, catalog, app) {
    this.entries = [];
    this.containerEl = containerEl;
    this.catalog = catalog;
    this.app = app;
    this.render();
  }
  async deleteEntry(entry) {
    await this.catalog.deleteVaultEntry(entry);
    await this.render();
  }
  async refresh() {
    await this.catalog.refresh();
    await this.render();
  }
  async render() {
    this.containerEl.empty();
    try {
      this.entries = await this.catalog.listVaultEntries();
    } catch (e2) {
      this.entries = [];
    }
    const headerEl = this.containerEl.createDiv({ cls: "claudian-sp-header" });
    headerEl.createSpan({ text: "Codex Skills", cls: "claudian-sp-label" });
    const actionsEl = headerEl.createDiv({ cls: "claudian-sp-header-actions" });
    const refreshBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Refresh" }
    });
    (0, import_obsidian15.setIcon)(refreshBtn, "refresh-cw");
    refreshBtn.addEventListener("click", () => {
      void this.refresh();
    });
    const addBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Add" }
    });
    (0, import_obsidian15.setIcon)(addBtn, "plus");
    addBtn.addEventListener("click", () => this.openModal(null));
    if (this.entries.length === 0) {
      const emptyEl = this.containerEl.createDiv({ cls: "claudian-sp-empty-state" });
      emptyEl.setText("No Codex skills in vault. Click + to create one.");
      return;
    }
    const listEl = this.containerEl.createDiv({ cls: "claudian-sp-list" });
    for (const entry of this.entries) {
      this.renderItem(listEl, entry);
    }
  }
  renderItem(listEl, entry) {
    const itemEl = listEl.createDiv({ cls: "claudian-sp-item" });
    const infoEl = itemEl.createDiv({ cls: "claudian-sp-info" });
    const headerRow = infoEl.createDiv({ cls: "claudian-sp-item-header" });
    const nameEl = headerRow.createSpan({ cls: "claudian-sp-item-name" });
    nameEl.setText(`$${entry.name}`);
    headerRow.createSpan({ text: "skill", cls: "claudian-slash-item-badge" });
    if (entry.description) {
      const descEl = infoEl.createDiv({ cls: "claudian-sp-item-desc" });
      descEl.setText(entry.description);
    }
    const actionsEl = itemEl.createDiv({ cls: "claudian-sp-item-actions" });
    if (entry.isEditable) {
      const editBtn = actionsEl.createEl("button", {
        cls: "claudian-settings-action-btn",
        attr: { "aria-label": "Edit" }
      });
      (0, import_obsidian15.setIcon)(editBtn, "pencil");
      editBtn.addEventListener("click", () => this.openModal(entry));
    }
    if (entry.isDeletable) {
      const deleteBtn = actionsEl.createEl("button", {
        cls: "claudian-settings-action-btn claudian-settings-delete-btn",
        attr: { "aria-label": "Delete" }
      });
      (0, import_obsidian15.setIcon)(deleteBtn, "trash-2");
      deleteBtn.addEventListener("click", async () => {
        try {
          await this.deleteEntry(entry);
          new import_obsidian15.Notice(`Codex skill "$${entry.name}" deleted`);
        } catch (e2) {
          new import_obsidian15.Notice("Failed to delete Codex skill");
        }
      });
    }
  }
  openModal(existing) {
    if (!this.app) return;
    const modal = new CodexSkillModal(
      this.app,
      existing,
      async (entry) => {
        await this.catalog.saveVaultEntry(entry);
        await this.render();
        new import_obsidian15.Notice(`Codex skill "$${entry.name}" ${existing ? "updated" : "created"}`);
      }
    );
    modal.open();
  }
};

// src/providers/codex/ui/CodexSubagentSettings.ts
var import_obsidian16 = require("obsidian");
var REASONING_EFFORT_OPTIONS = [
  { value: "", label: "Inherit" },
  { value: "low", label: "Low" },
  { value: "medium", label: "Medium" },
  { value: "high", label: "High" },
  { value: "xhigh", label: "Extra High" }
];
var SANDBOX_MODE_OPTIONS = [
  { value: "", label: "Inherit" },
  { value: "read-only", label: "Read-only" },
  { value: "danger-full-access", label: "Danger full access" },
  { value: "workspace-write", label: "Workspace write" }
];
var MAX_NAME_LENGTH = 64;
var CODEX_AGENT_NAME_PATTERN = /^[a-z0-9_-]+$/;
var CODEX_NICKNAME_PATTERN = /^[A-Za-z0-9 _-]+$/;
function validateCodexSubagentName(name) {
  if (!name) return "Subagent name is required";
  if (name.length > MAX_NAME_LENGTH) return `Subagent name must be ${MAX_NAME_LENGTH} characters or fewer`;
  if (!CODEX_AGENT_NAME_PATTERN.test(name)) return "Subagent name can only contain lowercase letters, numbers, hyphens, and underscores";
  return null;
}
function validateCodexNicknameCandidates(candidates) {
  const normalized = candidates.map((candidate) => candidate.trim()).filter(Boolean);
  if (normalized.length === 0) return null;
  const seen = /* @__PURE__ */ new Set();
  for (const candidate of normalized) {
    if (!CODEX_NICKNAME_PATTERN.test(candidate)) {
      return "Nickname candidates can only contain ASCII letters, numbers, spaces, hyphens, and underscores";
    }
    const dedupeKey = candidate.toLowerCase();
    if (seen.has(dedupeKey)) {
      return "Nickname candidates must be unique";
    }
    seen.add(dedupeKey);
  }
  return null;
}
var CodexSubagentModal = class extends import_obsidian16.Modal {
  constructor(app, existing, allAgents, onSave) {
    var _a3, _b2;
    super(app);
    this._reasoningEffort = "";
    this._sandboxMode = "";
    this.existing = existing;
    this.allAgents = allAgents;
    this.onSave = onSave;
    this._reasoningEffort = (_a3 = existing == null ? void 0 : existing.modelReasoningEffort) != null ? _a3 : "";
    this._sandboxMode = (_b2 = existing == null ? void 0 : existing.sandboxMode) != null ? _b2 : "";
  }
  getTestInputs() {
    return {
      nameInput: this._nameInput,
      descInput: this._descInput,
      instructionsArea: this._instructionsArea,
      nicknamesInput: this._nicknamesInput,
      modelInput: this._modelInput,
      setReasoningEffort: (v2) => {
        this._reasoningEffort = v2;
      },
      setSandboxMode: (v2) => {
        this._sandboxMode = v2;
      },
      triggerSave: this._triggerSave
    };
  }
  onOpen() {
    var _a3, _b2, _c, _d2, _e, _f, _g;
    this.setTitle(this.existing ? "Edit Codex Subagent" : "Add Codex Subagent");
    this.modalEl.addClass("claudian-sp-modal");
    const { contentEl } = this;
    new import_obsidian16.Setting(contentEl).setName("Name").setDesc("Agent name Codex uses when spawning (lowercase, hyphens, underscores)").addText((text) => {
      var _a4, _b3;
      this._nameInput = text.inputEl;
      text.setValue((_b3 = (_a4 = this.existing) == null ? void 0 : _a4.name) != null ? _b3 : "").setPlaceholder("code_reviewer");
    });
    new import_obsidian16.Setting(contentEl).setName("Description").setDesc("When Codex should use this agent").addText((text) => {
      var _a4, _b3;
      this._descInput = text.inputEl;
      text.setValue((_b3 = (_a4 = this.existing) == null ? void 0 : _a4.description) != null ? _b3 : "").setPlaceholder("Reviews code for correctness and security");
    });
    const details = contentEl.createEl("details", { cls: "claudian-sp-advanced-section" });
    details.createEl("summary", {
      text: "Advanced options",
      cls: "claudian-sp-advanced-summary"
    });
    if (((_a3 = this.existing) == null ? void 0 : _a3.model) || ((_b2 = this.existing) == null ? void 0 : _b2.modelReasoningEffort) || ((_c = this.existing) == null ? void 0 : _c.sandboxMode) || ((_e = (_d2 = this.existing) == null ? void 0 : _d2.nicknameCandidates) == null ? void 0 : _e.length)) {
      details.open = true;
    }
    new import_obsidian16.Setting(details).setName("Model").setDesc("Model override (leave empty to inherit)").addText((text) => {
      var _a4, _b3;
      this._modelInput = text.inputEl;
      text.setValue((_b3 = (_a4 = this.existing) == null ? void 0 : _a4.model) != null ? _b3 : "").setPlaceholder(DEFAULT_CODEX_PRIMARY_MODEL);
    });
    new import_obsidian16.Setting(details).setName("Reasoning effort").setDesc("Model reasoning effort level").addDropdown((dropdown) => {
      for (const opt of REASONING_EFFORT_OPTIONS) {
        dropdown.addOption(opt.value, opt.label);
      }
      dropdown.setValue(this._reasoningEffort);
      dropdown.onChange((v2) => {
        this._reasoningEffort = v2;
      });
    });
    new import_obsidian16.Setting(details).setName("Sandbox mode").setDesc("Sandbox restriction for this agent").addDropdown((dropdown) => {
      for (const opt of SANDBOX_MODE_OPTIONS) {
        dropdown.addOption(opt.value, opt.label);
      }
      dropdown.setValue(this._sandboxMode);
      dropdown.onChange((v2) => {
        this._sandboxMode = v2;
      });
    });
    new import_obsidian16.Setting(details).setName("Nickname candidates").setDesc("Comma-separated display nicknames (e.g., Atlas, Delta, Echo)").addText((text) => {
      var _a4, _b3, _c2;
      this._nicknamesInput = text.inputEl;
      text.setValue((_c2 = (_b3 = (_a4 = this.existing) == null ? void 0 : _a4.nicknameCandidates) == null ? void 0 : _b3.join(", ")) != null ? _c2 : "");
    });
    new import_obsidian16.Setting(contentEl).setName("Developer instructions").setDesc("Core instructions that define the agent's behavior");
    const instructionsArea = contentEl.createEl("textarea", {
      cls: "claudian-sp-content-area",
      attr: {
        rows: "10",
        placeholder: "Review code like an owner.\nPrioritize correctness, security, and missing test coverage."
      }
    });
    instructionsArea.value = (_g = (_f = this.existing) == null ? void 0 : _f.developerInstructions) != null ? _g : "";
    this._instructionsArea = instructionsArea;
    const doSave = async () => {
      var _a4, _b3;
      const name = this._nameInput.value.trim();
      const nameError = validateCodexSubagentName(name);
      if (nameError) {
        new import_obsidian16.Notice(nameError);
        return;
      }
      const description = this._descInput.value.trim();
      if (!description) {
        new import_obsidian16.Notice("Description is required");
        return;
      }
      const developerInstructions = this._instructionsArea.value;
      if (!developerInstructions.trim()) {
        new import_obsidian16.Notice("Developer instructions are required");
        return;
      }
      const nicknameCandidates = this._nicknamesInput.value.split(",").map((s4) => s4.trim()).filter(Boolean);
      const nicknameError = validateCodexNicknameCandidates(nicknameCandidates);
      if (nicknameError) {
        new import_obsidian16.Notice(nicknameError);
        return;
      }
      const duplicate = this.allAgents.find(
        (a2) => {
          var _a5;
          return a2.name.toLowerCase() === name.toLowerCase() && a2.persistenceKey !== ((_a5 = this.existing) == null ? void 0 : _a5.persistenceKey);
        }
      );
      if (duplicate) {
        new import_obsidian16.Notice(`A subagent named "${name}" already exists`);
        return;
      }
      const agent = {
        name,
        description,
        developerInstructions,
        nicknameCandidates: nicknameCandidates.length > 0 ? nicknameCandidates : void 0,
        model: this._modelInput.value.trim() || void 0,
        modelReasoningEffort: this._reasoningEffort || void 0,
        sandboxMode: this._sandboxMode || void 0,
        persistenceKey: (_a4 = this.existing) == null ? void 0 : _a4.persistenceKey,
        extraFields: (_b3 = this.existing) == null ? void 0 : _b3.extraFields
      };
      try {
        await this.onSave(agent);
      } catch (err) {
        const message = err instanceof Error ? err.message : "Unknown error";
        new import_obsidian16.Notice(`Failed to save subagent: ${message}`);
        return;
      }
      this.close();
    };
    this._triggerSave = doSave;
    const buttonContainer = contentEl.createDiv({ cls: "claudian-sp-modal-buttons" });
    const cancelBtn = buttonContainer.createEl("button", {
      text: "Cancel",
      cls: "claudian-cancel-btn"
    });
    cancelBtn.addEventListener("click", () => this.close());
    const saveBtn = buttonContainer.createEl("button", {
      text: "Save",
      cls: "claudian-save-btn"
    });
    saveBtn.addEventListener("click", doSave);
  }
  onClose() {
    this.contentEl.empty();
  }
};
var CodexSubagentSettings = class {
  constructor(containerEl, storage, app, onChanged) {
    this.agents = [];
    this.containerEl = containerEl;
    this.storage = storage;
    this.app = app;
    this.onChanged = onChanged;
    this.render();
  }
  async render() {
    this.containerEl.empty();
    try {
      this.agents = await this.storage.loadAll();
    } catch (e2) {
      this.agents = [];
    }
    const headerEl = this.containerEl.createDiv({ cls: "claudian-sp-header" });
    headerEl.createSpan({ text: "Codex Subagents", cls: "claudian-sp-label" });
    const actionsEl = headerEl.createDiv({ cls: "claudian-sp-header-actions" });
    const refreshBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Refresh" }
    });
    (0, import_obsidian16.setIcon)(refreshBtn, "refresh-cw");
    refreshBtn.addEventListener("click", () => {
      void this.render();
    });
    const addBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Add" }
    });
    (0, import_obsidian16.setIcon)(addBtn, "plus");
    addBtn.addEventListener("click", () => this.openModal(null));
    if (this.agents.length === 0) {
      const emptyEl = this.containerEl.createDiv({ cls: "claudian-sp-empty-state" });
      emptyEl.setText("No Codex subagents in vault. Click + to create one.");
      return;
    }
    const listEl = this.containerEl.createDiv({ cls: "claudian-sp-list" });
    for (const agent of this.agents) {
      this.renderItem(listEl, agent);
    }
  }
  renderItem(listEl, agent) {
    const itemEl = listEl.createDiv({ cls: "claudian-sp-item" });
    const infoEl = itemEl.createDiv({ cls: "claudian-sp-info" });
    const headerRow = infoEl.createDiv({ cls: "claudian-sp-item-header" });
    const nameEl = headerRow.createSpan({ cls: "claudian-sp-item-name" });
    nameEl.setText(agent.name);
    if (agent.model) {
      headerRow.createSpan({ text: agent.model, cls: "claudian-slash-item-badge" });
    }
    if (agent.description) {
      const descEl = infoEl.createDiv({ cls: "claudian-sp-item-desc" });
      descEl.setText(agent.description);
    }
    const actionsEl = itemEl.createDiv({ cls: "claudian-sp-item-actions" });
    const editBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Edit" }
    });
    (0, import_obsidian16.setIcon)(editBtn, "pencil");
    editBtn.addEventListener("click", () => this.openModal(agent));
    const deleteBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn claudian-settings-delete-btn",
      attr: { "aria-label": "Delete" }
    });
    (0, import_obsidian16.setIcon)(deleteBtn, "trash-2");
    deleteBtn.addEventListener("click", async () => {
      var _a3;
      if (!this.app) return;
      const confirmed = await confirmDelete(
        this.app,
        `Delete subagent "${agent.name}"?`
      );
      if (!confirmed) return;
      try {
        await this.storage.delete(agent);
        await this.render();
        (_a3 = this.onChanged) == null ? void 0 : _a3.call(this);
        new import_obsidian16.Notice(`Subagent "${agent.name}" deleted`);
      } catch (e2) {
        new import_obsidian16.Notice("Failed to delete subagent");
      }
    });
  }
  openModal(existing) {
    if (!this.app) return;
    const modal = new CodexSubagentModal(
      this.app,
      existing,
      this.agents,
      async (agent) => {
        var _a3;
        await this.storage.save(agent, existing);
        await this.render();
        (_a3 = this.onChanged) == null ? void 0 : _a3.call(this);
        new import_obsidian16.Notice(
          existing ? `Subagent "${agent.name}" updated` : `Subagent "${agent.name}" created`
        );
      }
    );
    modal.open();
  }
};

// src/providers/codex/ui/CodexSettingsTab.ts
var codexSettingsTabRenderer = {
  render(container, context) {
    const codexWorkspace = getCodexWorkspaceServices();
    const settingsBag = context.plugin.settings;
    const codexSettings = getCodexProviderSettings(settingsBag);
    const hostnameKey = getHostnameKey();
    const isWindowsHost = process.platform === "win32";
    let installationMethod = codexSettings.installationMethod;
    const reconcileActiveCodexModelSelection = () => {
      const activeProvider = settingsBag.settingsProvider;
      if (activeProvider !== "codex") {
        return;
      }
      const currentModel = typeof settingsBag.model === "string" ? settingsBag.model : "";
      const nextModel = resolveCodexModelSelection(settingsBag, currentModel);
      if (!nextModel || nextModel === currentModel) {
        return;
      }
      settingsBag.model = nextModel;
    };
    new import_obsidian17.Setting(container).setName(t("settings.setup")).setHeading();
    new import_obsidian17.Setting(container).setName("Enable Codex provider").setDesc("When enabled, Codex models appear in the model selector for new conversations. Existing Codex sessions are preserved.").addToggle(
      (toggle) => toggle.setValue(codexSettings.enabled).onChange(async (value) => {
        updateCodexProviderSettings(settingsBag, { enabled: value });
        await context.plugin.saveSettings();
        context.refreshModelSelectors();
      })
    );
    if (isWindowsHost) {
      new import_obsidian17.Setting(container).setName("Installation method").setDesc("How Claudian should launch Codex on Windows. Native Windows uses a Windows executable path. WSL launches the Linux CLI inside a selected distro.").addDropdown((dropdown) => {
        dropdown.addOption("native-windows", "Native Windows").addOption("wsl", "WSL").setValue(installationMethod).onChange(async (value) => {
          installationMethod = value === "wsl" ? "wsl" : "native-windows";
          updateCodexProviderSettings(settingsBag, { installationMethod });
          refreshInstallationMethodUI();
          await context.plugin.saveSettings();
        });
      });
    }
    const getCliPathCopy = () => {
      if (!isWindowsHost) {
        return {
          desc: "Custom path to the local Codex CLI. Leave empty for auto-detection from PATH.",
          placeholder: "/usr/local/bin/codex"
        };
      }
      if (installationMethod === "wsl") {
        return {
          desc: "Linux-side Codex command or absolute path to run inside WSL. Leave empty for PATH lookup inside the selected distro.",
          placeholder: "codex"
        };
      }
      return {
        desc: "Custom path to the local Codex CLI. Leave empty for auto-detection from PATH. Use the native Windows executable path, usually `codex.exe`.",
        placeholder: "C:\\Users\\you\\AppData\\Roaming\\npm\\codex.exe"
      };
    };
    const shouldValidateCliPathAsFile = () => !isWindowsHost || installationMethod !== "wsl";
    const cliPathSetting = new import_obsidian17.Setting(container).setName(`Codex CLI path (${hostnameKey})`).setDesc(getCliPathCopy().desc);
    const validationEl = container.createDiv({ cls: "claudian-cli-path-validation" });
    validationEl.style.color = "var(--text-error)";
    validationEl.style.fontSize = "0.85em";
    validationEl.style.marginTop = "-0.5em";
    validationEl.style.marginBottom = "0.5em";
    validationEl.style.display = "none";
    const validatePath = (value) => {
      const trimmed = value.trim();
      if (!trimmed) return null;
      if (!shouldValidateCliPathAsFile()) {
        if (isWindowsStyleCliReference(trimmed)) {
          return "WSL mode expects a Linux command or Linux absolute path, not a Windows executable path.";
        }
        return null;
      }
      const expandedPath = expandHomePath(trimmed);
      if (!fs13.existsSync(expandedPath)) {
        return t("settings.cliPath.validation.notExist");
      }
      const stat = fs13.statSync(expandedPath);
      if (!stat.isFile()) {
        return t("settings.cliPath.validation.isDirectory");
      }
      return null;
    };
    const updateCliPathValidation = (value, inputEl) => {
      const error48 = validatePath(value);
      if (error48) {
        validationEl.setText(error48);
        validationEl.style.display = "block";
        if (inputEl) {
          inputEl.style.borderColor = "var(--text-error)";
        }
        return false;
      }
      validationEl.style.display = "none";
      if (inputEl) {
        inputEl.style.borderColor = "";
      }
      return true;
    };
    const cliPathsByHost = { ...codexSettings.cliPathsByHost };
    let cliPathInputEl = null;
    let wslDistroSettingEl = null;
    let wslDistroInputEl = null;
    const refreshInstallationMethodUI = () => {
      const cliCopy = getCliPathCopy();
      cliPathSetting.setDesc(cliCopy.desc);
      if (cliPathInputEl) {
        cliPathInputEl.placeholder = cliCopy.placeholder;
        updateCliPathValidation(cliPathInputEl.value, cliPathInputEl);
      }
      if (wslDistroSettingEl) {
        wslDistroSettingEl.style.display = installationMethod === "wsl" ? "" : "none";
      }
      if (wslDistroInputEl) {
        wslDistroInputEl.disabled = installationMethod !== "wsl";
      }
    };
    const persistCliPath = async (value) => {
      var _a3;
      const isValid2 = updateCliPathValidation(value, cliPathInputEl != null ? cliPathInputEl : void 0);
      if (!isValid2) {
        return false;
      }
      const trimmed = value.trim();
      if (trimmed) {
        cliPathsByHost[hostnameKey] = trimmed;
      } else {
        delete cliPathsByHost[hostnameKey];
      }
      updateCodexProviderSettings(settingsBag, { cliPathsByHost: { ...cliPathsByHost } });
      await context.plugin.saveSettings();
      const view = context.plugin.getView();
      await ((_a3 = view == null ? void 0 : view.getTabManager()) == null ? void 0 : _a3.broadcastToAllTabs(
        (service) => Promise.resolve(service.cleanup())
      ));
      return true;
    };
    const currentValue = codexSettings.cliPathsByHost[hostnameKey] || "";
    cliPathSetting.addText((text) => {
      text.setPlaceholder(getCliPathCopy().placeholder).setValue(currentValue).onChange(async (value) => {
        await persistCliPath(value);
      });
      text.inputEl.addClass("claudian-settings-cli-path-input");
      text.inputEl.style.width = "100%";
      cliPathInputEl = text.inputEl;
      updateCliPathValidation(currentValue, text.inputEl);
    });
    if (isWindowsHost) {
      const wslDistroSetting = new import_obsidian17.Setting(container).setName("WSL distro override").setDesc("Optional advanced override. Leave empty to infer the distro from a \\\\wsl$ workspace path when possible, otherwise use the default WSL distro.");
      wslDistroSettingEl = wslDistroSetting.settingEl;
      wslDistroSetting.addText((text) => {
        text.setPlaceholder("Ubuntu").setValue(codexSettings.wslDistroOverride).onChange(async (value) => {
          updateCodexProviderSettings(settingsBag, { wslDistroOverride: value });
          await context.plugin.saveSettings();
        });
        text.inputEl.addClass("claudian-settings-cli-path-input");
        text.inputEl.style.width = "100%";
        text.inputEl.disabled = installationMethod !== "wsl";
        wslDistroInputEl = text.inputEl;
      });
    }
    refreshInstallationMethodUI();
    new import_obsidian17.Setting(container).setName(t("settings.safety")).setHeading();
    new import_obsidian17.Setting(container).setName(t("settings.codexSafeMode.name")).setDesc(t("settings.codexSafeMode.desc")).addDropdown((dropdown) => {
      dropdown.addOption("workspace-write", "workspace-write").addOption("read-only", "read-only").setValue(codexSettings.safeMode).onChange(async (value) => {
        updateCodexProviderSettings(
          settingsBag,
          { safeMode: value }
        );
        await context.plugin.saveSettings();
      });
    });
    new import_obsidian17.Setting(container).setName(t("settings.models")).setHeading();
    const SUMMARY_OPTIONS = [
      { value: "auto", label: "Auto" },
      { value: "concise", label: "Concise" },
      { value: "detailed", label: "Detailed" },
      { value: "none", label: "Off" }
    ];
    new import_obsidian17.Setting(container).setName("Custom models").setDesc("Append additional Codex model IDs to the picker, one per line. OPENAI_MODEL still takes precedence when set.").addTextArea((text) => {
      let pendingCustomModels = codexSettings.customModels;
      let savedCustomModels = codexSettings.customModels;
      const reconcileInactiveCodexProjection = (previousCustomModels) => {
        if (settingsBag.settingsProvider === "codex") {
          return false;
        }
        const savedProviderModel = settingsBag.savedProviderModel && typeof settingsBag.savedProviderModel === "object" ? settingsBag.savedProviderModel : {};
        const currentSavedModel = typeof savedProviderModel.codex === "string" ? savedProviderModel.codex : "";
        if (!currentSavedModel) {
          return false;
        }
        const previousCustomModelIds = new Set(parseConfiguredCustomModelIds2(previousCustomModels));
        if (!previousCustomModelIds.has(currentSavedModel)) {
          return false;
        }
        const nextSavedModel = resolveCodexModelSelection(settingsBag, currentSavedModel);
        if (!nextSavedModel || nextSavedModel === currentSavedModel) {
          return false;
        }
        settingsBag.savedProviderModel = {
          ...savedProviderModel,
          codex: nextSavedModel
        };
        return true;
      };
      const commitCustomModels = async () => {
        const previousCustomModels = savedCustomModels;
        const previousModel = typeof settingsBag.model === "string" ? settingsBag.model : "";
        const previousTitleModel = typeof settingsBag.titleGenerationModel === "string" ? settingsBag.titleGenerationModel : "";
        if (pendingCustomModels !== savedCustomModels) {
          updateCodexProviderSettings(settingsBag, { customModels: pendingCustomModels });
          savedCustomModels = pendingCustomModels;
        }
        reconcileActiveCodexModelSelection();
        const didReconcileInactiveProjection = reconcileInactiveCodexProjection(previousCustomModels);
        const didReconcileTitleModel = ProviderSettingsCoordinator.reconcileTitleGenerationModelSelection(settingsBag);
        const nextModel = typeof settingsBag.model === "string" ? settingsBag.model : "";
        const nextTitleModel = typeof settingsBag.titleGenerationModel === "string" ? settingsBag.titleGenerationModel : "";
        const didModelSelectionChange = previousModel !== nextModel;
        const didCustomModelsChange = previousCustomModels !== savedCustomModels;
        if (!didCustomModelsChange && !didModelSelectionChange && !didReconcileInactiveProjection && !didReconcileTitleModel && previousTitleModel === nextTitleModel) {
          return;
        }
        await context.plugin.saveSettings();
        context.refreshModelSelectors();
      };
      text.setPlaceholder("gpt-5.4\ngpt-5.3-codex-spark").setValue(codexSettings.customModels).onChange((value) => {
        pendingCustomModels = value;
      });
      text.inputEl.rows = 4;
      text.inputEl.cols = 40;
      text.inputEl.addEventListener("blur", () => {
        void commitCustomModels();
      });
    });
    new import_obsidian17.Setting(container).setName("Reasoning summary").setDesc("Show a summary of the model's reasoning process in the thinking block.").addDropdown((dropdown) => {
      for (const opt of SUMMARY_OPTIONS) {
        dropdown.addOption(opt.value, opt.label);
      }
      dropdown.setValue(codexSettings.reasoningSummary);
      dropdown.onChange(async (value) => {
        updateCodexProviderSettings(
          settingsBag,
          { reasoningSummary: value }
        );
        await context.plugin.saveSettings();
      });
    });
    const codexCatalog = codexWorkspace.commandCatalog;
    if (codexCatalog) {
      new import_obsidian17.Setting(container).setName("Codex Skills").setHeading();
      const skillsDesc = container.createDiv({ cls: "claudian-sp-settings-desc" });
      skillsDesc.createEl("p", {
        cls: "setting-item-description",
        text: "Manage vault-level Codex skills stored in .codex/skills/ or .agents/skills/. Home-level skills are excluded here."
      });
      const skillsContainer = container.createDiv({ cls: "claudian-slash-commands-container" });
      new CodexSkillSettings(skillsContainer, codexCatalog, context.plugin.app);
    }
    context.renderHiddenProviderCommandSetting(container, "codex", {
      name: "Hidden Skills",
      desc: "Hide specific Codex skills from the dropdown. Enter skill names without the leading $, one per line.",
      placeholder: "analyze\nexplain\nfix"
    });
    new import_obsidian17.Setting(container).setName("Codex Subagents").setHeading();
    const subagentDesc = container.createDiv({ cls: "claudian-sp-settings-desc" });
    subagentDesc.createEl("p", {
      cls: "setting-item-description",
      text: "Manage vault-level Codex subagents stored in .codex/agents/. Each TOML file defines one custom agent."
    });
    const subagentContainer = container.createDiv({ cls: "claudian-slash-commands-container" });
    new CodexSubagentSettings(subagentContainer, codexWorkspace.subagentStorage, context.plugin.app, () => {
      var _a3;
      void ((_a3 = codexWorkspace.refreshAgentMentions) == null ? void 0 : _a3.call(codexWorkspace));
    });
    new import_obsidian17.Setting(container).setName(t("settings.mcpServers.name")).setHeading();
    const mcpNotice = container.createDiv({ cls: "claudian-mcp-settings-desc" });
    const mcpDesc = mcpNotice.createEl("p", { cls: "setting-item-description" });
    mcpDesc.appendText("Codex manages MCP servers via its own CLI. Configure with ");
    mcpDesc.createEl("code", { text: "codex mcp" });
    mcpDesc.appendText(" and they will be available in Claudian. ");
    mcpDesc.createEl("a", {
      text: "Learn more",
      href: "https://developers.openai.com/codex/mcp"
    });
    renderEnvironmentSettingsSection({
      container,
      plugin: context.plugin,
      scope: "provider:codex",
      heading: t("settings.environment"),
      name: "Codex environment",
      desc: "Codex-owned runtime variables only. Use this for OPENAI_* and CODEX_* settings. If Codex auto-detection needs help, add its install directory to shared PATH instead of this provider section.",
      placeholder: `OPENAI_API_KEY=your-key
OPENAI_BASE_URL=https://api.openai.com/v1
OPENAI_MODEL=${DEFAULT_CODEX_PRIMARY_MODEL}
CODEX_SANDBOX=workspace-write`,
      renderCustomContextLimits: (target) => context.renderCustomContextLimits(target, "codex")
    });
  }
};

// src/providers/codex/app/CodexWorkspaceServices.ts
function createCodexCliResolver() {
  return new CodexCliResolver();
}
async function createCodexWorkspaceServices(plugin, vaultAdapter, homeAdapter) {
  const subagentStorage = new CodexSubagentStorage(vaultAdapter);
  const agentMentionProvider = new CodexAgentMentionProvider(subagentStorage);
  await agentMentionProvider.loadAgents();
  const skillListProvider = new CodexSkillListingService(plugin);
  const commandCatalog = new CodexSkillCatalog(
    new CodexSkillStorage(
      vaultAdapter,
      homeAdapter
    ),
    skillListProvider,
    getVaultPath(plugin.app)
  );
  return {
    subagentStorage,
    commandCatalog,
    agentMentionProvider,
    cliResolver: createCodexCliResolver(),
    settingsTabRenderer: codexSettingsTabRenderer,
    refreshAgentMentions: async () => {
      await agentMentionProvider.loadAgents();
    }
  };
}
var codexWorkspaceRegistration = {
  initialize: async ({ plugin, vaultAdapter, homeAdapter }) => createCodexWorkspaceServices(
    plugin,
    vaultAdapter,
    homeAdapter
  )
};
function getCodexWorkspaceServices() {
  return ProviderWorkspaceRegistry.requireServices("codex");
}

// src/core/auxiliary/QueryBackedInlineEditService.ts
var QueryBackedInlineEditService = class {
  constructor(runner) {
    this.runner = runner;
    this.abortController = null;
    this.hasConversation = false;
  }
  setModelOverride(model) {
    const trimmed = model == null ? void 0 : model.trim();
    this.modelOverride = trimmed ? trimmed : void 0;
  }
  resetConversation() {
    this.runner.reset();
    this.hasConversation = false;
  }
  async editText(request) {
    this.resetConversation();
    return this.sendMessage(buildInlineEditPrompt(request));
  }
  async continueConversation(message, contextFiles) {
    if (!this.hasConversation) {
      return { success: false, error: "No active conversation to continue" };
    }
    let prompt = message;
    if (contextFiles && contextFiles.length > 0) {
      prompt = appendContextFiles(message, contextFiles);
    }
    return this.sendMessage(prompt);
  }
  cancel() {
    var _a3;
    (_a3 = this.abortController) == null ? void 0 : _a3.abort();
    this.abortController = null;
  }
  async sendMessage(prompt) {
    this.abortController = new AbortController();
    try {
      const text = await this.runner.query({
        abortController: this.abortController,
        model: this.modelOverride,
        systemPrompt: getInlineEditSystemPrompt()
      }, prompt);
      this.hasConversation = true;
      return parseInlineEditResponse(text);
    } catch (error48) {
      return {
        success: false,
        error: error48 instanceof Error ? error48.message : "Unknown error"
      };
    } finally {
      this.abortController = null;
    }
  }
};

// src/providers/codex/runtime/CodexAuxQueryRunner.ts
var CodexAuxQueryRunner = class {
  constructor(plugin) {
    this.plugin = plugin;
    this.process = null;
    this.transport = null;
    this.threadId = null;
    this.launchSpec = null;
  }
  async query(config2, prompt) {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i;
    if (!this.process || !this.transport) {
      await this.startProcess();
    }
    if (!this.threadId) {
      const model = (_a3 = config2.model) != null ? _a3 : this.resolveProviderModel();
      const result = await this.transport.request("thread/start", {
        model,
        cwd: (_c = (_b2 = this.launchSpec) == null ? void 0 : _b2.targetCwd) != null ? _c : process.cwd(),
        approvalPolicy: "never",
        sandbox: "read-only",
        baseInstructions: config2.systemPrompt,
        experimentalRawEvents: false,
        persistExtendedHistory: false
      });
      this.threadId = result.thread.id;
    }
    let accumulatedText = "";
    let turnError = null;
    let resolveWait = null;
    const donePromise = new Promise((resolve8) => {
      resolveWait = resolve8;
    });
    this.transport.onNotification("item/agentMessage/delta", (params) => {
      var _a4;
      const p = params;
      accumulatedText += p.delta;
      (_a4 = config2.onTextChunk) == null ? void 0 : _a4.call(config2, accumulatedText);
    });
    this.transport.onNotification("turn/completed", (params) => {
      const p = params;
      if (p.turn.status === "failed" && p.turn.error) {
        turnError = p.turn.error.message;
      }
      resolveWait == null ? void 0 : resolveWait();
    });
    this.transport.onNotification("error", (params) => {
      const p = params;
      if (!p.willRetry) {
        turnError = p.error.message;
        resolveWait == null ? void 0 : resolveWait();
      }
    });
    const exitHandler = () => {
      if (!turnError) turnError = "Codex app-server process exited unexpectedly";
      resolveWait == null ? void 0 : resolveWait();
    };
    this.process.onExit(exitHandler);
    let turnId = null;
    const abortHandler = () => {
      if (this.transport && this.threadId && turnId) {
        this.transport.request("turn/interrupt", {
          threadId: this.threadId,
          turnId
        }).catch(() => {
        });
      }
      resolveWait == null ? void 0 : resolveWait();
    };
    (_d2 = config2.abortController) == null ? void 0 : _d2.signal.addEventListener("abort", abortHandler, { once: true });
    if ((_e = config2.abortController) == null ? void 0 : _e.signal.aborted) {
      config2.abortController.signal.removeEventListener("abort", abortHandler);
      (_f = this.process) == null ? void 0 : _f.offExit(exitHandler);
      throw new Error("Cancelled");
    }
    const turnResult = await this.transport.request("turn/start", {
      threadId: this.threadId,
      input: [{ type: "text", text: prompt }],
      model: config2.model
    });
    turnId = turnResult.turn.id;
    try {
      await donePromise;
    } finally {
      (_g = config2.abortController) == null ? void 0 : _g.signal.removeEventListener("abort", abortHandler);
      (_h = this.process) == null ? void 0 : _h.offExit(exitHandler);
    }
    if ((_i = config2.abortController) == null ? void 0 : _i.signal.aborted) {
      throw new Error("Cancelled");
    }
    if (turnError) {
      throw new Error(turnError);
    }
    return accumulatedText;
  }
  reset() {
    this.threadId = null;
    this.launchSpec = null;
    if (this.transport) {
      this.transport.dispose();
      this.transport = null;
    }
    if (this.process) {
      this.process.shutdown().catch(() => {
      });
      this.process = null;
    }
  }
  resolveProviderModel() {
    var _a3;
    const providerSettings = ProviderSettingsCoordinator.getProviderSettingsSnapshot(
      this.plugin.settings,
      "codex"
    );
    return (_a3 = providerSettings.model) != null ? _a3 : DEFAULT_CODEX_PRIMARY_MODEL;
  }
  async startProcess() {
    this.launchSpec = resolveCodexAppServerLaunchSpec(this.plugin, "codex");
    this.process = new CodexAppServerProcess(this.launchSpec);
    this.process.start();
    this.transport = new CodexRpcTransport(this.process);
    this.transport.start();
    const initializeResult = await this.transport.request("initialize", {
      clientInfo: { name: "claudian-aux", version: "1.0.0" },
      capabilities: { experimentalApi: true }
    });
    createCodexRuntimeContext(this.launchSpec, initializeResult);
    this.transport.notify("initialized");
  }
};

// src/providers/codex/auxiliary/CodexInlineEditService.ts
var CodexInlineEditService = class extends QueryBackedInlineEditService {
  constructor(plugin) {
    super(new CodexAuxQueryRunner(plugin));
  }
};

// src/core/auxiliary/QueryBackedInstructionRefineService.ts
var QueryBackedInstructionRefineService = class {
  constructor(runner) {
    this.runner = runner;
    this.abortController = null;
    this.existingInstructions = "";
    this.hasConversation = false;
  }
  setModelOverride(model) {
    const trimmed = model == null ? void 0 : model.trim();
    this.modelOverride = trimmed ? trimmed : void 0;
  }
  resetConversation() {
    this.runner.reset();
    this.hasConversation = false;
  }
  async refineInstruction(rawInstruction, existingInstructions, onProgress) {
    this.resetConversation();
    this.existingInstructions = existingInstructions;
    return this.sendMessage(`Please refine this instruction: "${rawInstruction}"`, onProgress);
  }
  async continueConversation(message, onProgress) {
    if (!this.hasConversation) {
      return { success: false, error: "No active conversation to continue" };
    }
    return this.sendMessage(message, onProgress);
  }
  cancel() {
    var _a3;
    (_a3 = this.abortController) == null ? void 0 : _a3.abort();
    this.abortController = null;
  }
  async sendMessage(prompt, onProgress) {
    this.abortController = new AbortController();
    try {
      const text = await this.runner.query({
        abortController: this.abortController,
        model: this.modelOverride,
        onTextChunk: onProgress ? (accumulatedText) => onProgress(parseInstructionRefineResponse(accumulatedText)) : void 0,
        systemPrompt: buildRefineSystemPrompt(this.existingInstructions)
      }, prompt);
      this.hasConversation = true;
      return parseInstructionRefineResponse(text);
    } catch (error48) {
      return {
        success: false,
        error: error48 instanceof Error ? error48.message : "Unknown error"
      };
    } finally {
      this.abortController = null;
    }
  }
};

// src/providers/codex/auxiliary/CodexInstructionRefineService.ts
var CodexInstructionRefineService = class extends QueryBackedInstructionRefineService {
  constructor(plugin) {
    super(new CodexAuxQueryRunner(plugin));
  }
};

// src/providers/codex/auxiliary/CodexTaskResultInterpreter.ts
var CodexTaskResultInterpreter = class {
  hasAsyncLaunchMarker(_toolUseResult) {
    return false;
  }
  extractAgentId(_toolUseResult) {
    return null;
  }
  extractStructuredResult(_toolUseResult) {
    return null;
  }
  resolveTerminalStatus(_toolUseResult, fallbackStatus) {
    return fallbackStatus;
  }
  extractTagValue(_payload, _tagName) {
    return null;
  }
};

// src/core/auxiliary/QueryBackedTitleGenerationService.ts
var QueryBackedTitleGenerationService = class {
  constructor(options) {
    this.options = options;
    this.activeGenerations = /* @__PURE__ */ new Map();
  }
  async generateTitle(conversationId, userMessage, callback) {
    var _a3, _b2;
    const existing = this.activeGenerations.get(conversationId);
    if (existing) {
      existing.abortController.abort();
      existing.runner.reset();
    }
    const abortController = new AbortController();
    const runner = this.options.createRunner();
    const generation = { abortController, runner };
    this.activeGenerations.set(conversationId, generation);
    try {
      const text = await runner.query({
        abortController,
        model: (_b2 = (_a3 = this.options).resolveModel) == null ? void 0 : _b2.call(_a3),
        systemPrompt: TITLE_GENERATION_SYSTEM_PROMPT
      }, buildTitleGenerationPrompt(userMessage));
      const title = parseTitleGenerationResponse(text);
      await this.safeCallback(
        callback,
        conversationId,
        title ? { success: true, title } : { success: false, error: "Failed to parse title from response" }
      );
    } catch (error48) {
      await this.safeCallback(callback, conversationId, {
        success: false,
        error: error48 instanceof Error ? error48.message : "Unknown error"
      });
    } finally {
      runner.reset();
      if (this.activeGenerations.get(conversationId) === generation) {
        this.activeGenerations.delete(conversationId);
      }
    }
  }
  cancel() {
    for (const active of this.activeGenerations.values()) {
      active.abortController.abort();
      active.runner.reset();
    }
    this.activeGenerations.clear();
  }
  async safeCallback(callback, conversationId, result) {
    try {
      await callback(conversationId, result);
    } catch (e2) {
    }
  }
};

// src/providers/codex/ui/CodexChatUIConfig.ts
var EFFORT_LEVELS2 = [
  { value: "low", label: "Low" },
  { value: "medium", label: "Medium" },
  { value: "high", label: "High" },
  { value: "xhigh", label: "XHigh" }
];
var CODEX_PERMISSION_MODE_TOGGLE = {
  inactiveValue: "normal",
  inactiveLabel: "Safe",
  activeValue: "yolo",
  activeLabel: "YOLO",
  planValue: "plan",
  planLabel: "Plan"
};
var CODEX_SERVICE_TIER_TOGGLE = {
  inactiveValue: "default",
  inactiveLabel: "Standard",
  activeValue: "fast",
  activeLabel: "Fast",
  description: FAST_TIER_CODEX_DESCRIPTION
};
var DEFAULT_CONTEXT_WINDOW = 2e5;
function looksLikeCodexModel(model) {
  return /^gpt-/i.test(model) || /^o\d/i.test(model);
}
var codexChatUIConfig = {
  getModelOptions(settings11) {
    return getCodexModelOptions(settings11);
  },
  ownsModel(model, settings11) {
    if (this.getModelOptions(settings11).some((option) => option.value === model)) {
      return true;
    }
    return looksLikeCodexModel(model);
  },
  isAdaptiveReasoningModel(_model, _settings) {
    return true;
  },
  getReasoningOptions(_model, _settings) {
    return [...EFFORT_LEVELS2];
  },
  getDefaultReasoningValue(_model, _settings) {
    return "medium";
  },
  getContextWindowSize() {
    return DEFAULT_CONTEXT_WINDOW;
  },
  isDefaultModel(model) {
    return DEFAULT_CODEX_MODEL_SET.has(model);
  },
  applyModelDefaults(model, settings11) {
    if (!settings11 || typeof settings11 !== "object") {
      return;
    }
    applyCodexModelDefaults(model, settings11);
  },
  normalizeModelVariant(model, settings11) {
    if (getCodexModelOptions(settings11).some((option) => option.value === model)) {
      return model;
    }
    return DEFAULT_CODEX_PRIMARY_MODEL;
  },
  getCustomModelIds(envVars) {
    const ids = /* @__PURE__ */ new Set();
    if (envVars.OPENAI_MODEL && !DEFAULT_CODEX_MODEL_SET.has(envVars.OPENAI_MODEL)) {
      ids.add(envVars.OPENAI_MODEL);
    }
    return ids;
  },
  getPermissionModeToggle() {
    return CODEX_PERMISSION_MODE_TOGGLE;
  },
  getServiceTierToggle(settings11) {
    return settings11.model === FAST_TIER_CODEX_MODEL ? CODEX_SERVICE_TIER_TOGGLE : null;
  },
  getProviderIcon() {
    return OPENAI_PROVIDER_ICON;
  }
};

// src/providers/codex/auxiliary/CodexTitleGenerationService.ts
var CodexTitleGenerationService = class extends QueryBackedTitleGenerationService {
  constructor(plugin) {
    super({
      createRunner: () => new CodexAuxQueryRunner(plugin),
      resolveModel: () => {
        const settings11 = plugin.settings;
        const titleModel = typeof settings11.titleGenerationModel === "string" ? settings11.titleGenerationModel : "";
        return codexChatUIConfig.ownsModel(titleModel, settings11) ? titleModel : void 0;
      }
    });
  }
};

// src/providers/codex/capabilities.ts
var CODEX_PROVIDER_CAPABILITIES = Object.freeze({
  providerId: "codex",
  supportsPersistentRuntime: true,
  supportsNativeHistory: true,
  supportsPlanMode: true,
  supportsRewind: false,
  supportsFork: true,
  supportsProviderCommands: false,
  supportsImageAttachments: true,
  supportsInstructionMode: true,
  supportsMcpTools: false,
  supportsTurnSteer: true,
  reasoningControl: "effort"
});

// src/providers/codex/env/CodexSettingsReconciler.ts
init_env();

// src/providers/codex/types/index.ts
function getCodexState(providerState) {
  return providerState != null ? providerState : {};
}

// src/providers/codex/env/CodexSettingsReconciler.ts
var ENV_HASH_KEYS = ["OPENAI_MODEL", "OPENAI_BASE_URL", "OPENAI_API_KEY"];
function computeCodexEnvHash(envText) {
  const envVars = parseEnvironmentVariables(envText || "");
  return ENV_HASH_KEYS.filter((key) => envVars[key]).map((key) => `${key}=${envVars[key]}`).sort().join("|");
}
var codexSettingsReconciler = {
  reconcileModelWithEnvironment(settings11, conversations) {
    const envText = getRuntimeEnvironmentText(settings11, "codex");
    const currentHash = computeCodexEnvHash(envText);
    const savedHash = getCodexProviderSettings(settings11).environmentHash;
    if (currentHash === savedHash) {
      return { changed: false, invalidatedConversations: [] };
    }
    const invalidatedConversations = [];
    for (const conv of conversations) {
      const state = getCodexState(conv.providerState);
      if (conv.providerId === "codex" && (conv.sessionId || state.threadId)) {
        conv.sessionId = null;
        conv.providerState = void 0;
        invalidatedConversations.push(conv);
      }
    }
    const currentModel = typeof settings11.model === "string" ? settings11.model : "";
    const nextModel = resolveCodexModelSelection(settings11, currentModel);
    if (nextModel) {
      settings11.model = nextModel;
    }
    updateCodexProviderSettings(settings11, { environmentHash: currentHash });
    return { changed: true, invalidatedConversations };
  },
  normalizeModelVariantSettings(settings11) {
    const model = settings11.model;
    if (!model) {
      return false;
    }
    const normalizedModel = codexChatUIConfig.normalizeModelVariant(model, settings11);
    if (normalizedModel === model) {
      return false;
    }
    settings11.model = normalizedModel;
    return true;
  }
};

// src/providers/codex/history/CodexHistoryStore.ts
var fs14 = __toESM(require("fs"));
var os9 = __toESM(require("os"));
var path14 = __toESM(require("path"));

// src/providers/codex/normalization/codexToolNormalization.ts
var TOOL_NAME_MAP = {
  command_execution: "Bash",
  shell_command: "Bash",
  shell: "Bash",
  exec_command: "Bash",
  update_plan: "TodoWrite",
  request_user_input: "AskUserQuestion",
  view_image: "Read",
  web_search: "WebSearch",
  web_search_call: "WebSearch",
  file_change: "apply_patch"
};
var NATIVE_TOOLS = /* @__PURE__ */ new Set([
  "apply_patch",
  "write_stdin",
  "spawn_agent",
  "send_input",
  "wait",
  "wait_agent",
  "resume_agent",
  "close_agent"
]);
function normalizeCodexToolName(rawName) {
  var _a3;
  if (!rawName) return "tool";
  if (NATIVE_TOOLS.has(rawName)) return rawName;
  return (_a3 = TOOL_NAME_MAP[rawName]) != null ? _a3 : rawName;
}
function normalizeCodexToolInput(rawName, input) {
  var _a3, _b2, _c, _d2;
  switch (rawName) {
    case "command_execution":
    case "shell_command":
    case "shell":
    case "exec_command":
      return { command: normalizeCommandValue((_b2 = (_a3 = input.command) != null ? _a3 : input.cmd) != null ? _b2 : "") };
    case "update_plan":
      return { todos: normalizeUpdatePlanTodos(input) };
    case "request_user_input":
      return { questions: normalizeQuestions(input) };
    case "view_image":
      return {
        ...input,
        file_path: (_d2 = (_c = input.path) != null ? _c : input.file_path) != null ? _d2 : ""
      };
    case "web_search":
    case "web_search_call":
      return normalizeWebSearchInput(input);
    case "apply_patch":
      return normalizeApplyPatchInput(input);
    default:
      return input;
  }
}
function normalizeUpdatePlanTodos(input) {
  const plan = input.plan;
  if (!Array.isArray(plan)) return [];
  return plan.map((entry) => {
    var _a3, _b2, _c, _d2, _e;
    if (!entry || typeof entry !== "object") return { id: "", title: "", status: "pending" };
    const item = entry;
    const text = String((_c = (_b2 = (_a3 = item.step) != null ? _a3 : item.title) != null ? _b2 : item.content) != null ? _c : "");
    return {
      id: String((_d2 = item.id) != null ? _d2 : ""),
      content: text,
      activeForm: text,
      status: String((_e = item.status) != null ? _e : "pending")
    };
  });
}
function normalizeQuestions(input) {
  const questions = input.questions;
  if (!Array.isArray(questions)) return [];
  return questions.map((entry, index) => {
    var _a3, _b2;
    if (!entry || typeof entry !== "object") {
      return {
        question: `Question ${index + 1}`,
        header: `Q${index + 1}`,
        options: [],
        multiSelect: false
      };
    }
    const item = entry;
    const options = Array.isArray(item.options) ? item.options.map((option) => {
      if (typeof option === "string") {
        return { label: option, description: "" };
      }
      if (!option || typeof option !== "object") {
        return null;
      }
      const raw = option;
      const label = typeof raw.label === "string" ? raw.label : "";
      const description = typeof raw.description === "string" ? raw.description : "";
      if (!label) return null;
      return { label, description };
    }).filter((option) => option !== null) : [];
    return {
      question: String((_a3 = item.question) != null ? _a3 : `Question ${index + 1}`),
      ...item.id ? { id: String(item.id) } : {},
      header: typeof item.header === "string" && item.header.trim() ? String(item.header) : `Q${index + 1}`,
      options,
      multiSelect: Boolean((_b2 = item.multiSelect) != null ? _b2 : item.multi_select)
    };
  });
}
function normalizeCommandValue(value) {
  if (typeof value === "string") return value;
  if (Array.isArray(value)) {
    return value.map((entry) => typeof entry === "string" ? entry : String(entry)).join(" ").trim();
  }
  return value == null ? "" : String(value);
}
function normalizeWebSearchInput(input) {
  var _a3;
  const action = input.action && typeof input.action === "object" ? input.action : {};
  const queries = normalizeStringArray2((_a3 = action.queries) != null ? _a3 : input.queries);
  const query = firstNonEmptyString(action.query, input.query, queries[0]);
  const url2 = firstNonEmptyString(action.url, input.url);
  const pattern = firstNonEmptyString(action.pattern, input.pattern);
  const explicitType = firstNonEmptyString(action.type, input.actionType, input.action_type);
  const actionType = explicitType || (url2 && pattern ? "find_in_page" : url2 ? "open_page" : query || queries.length > 0 ? "search" : "");
  const normalized = {};
  if (actionType) normalized.actionType = actionType;
  if (query) normalized.query = query;
  if (queries.length > 0) normalized.queries = queries;
  if (url2) normalized.url = url2;
  if (pattern) normalized.pattern = pattern;
  return normalized;
}
function normalizeApplyPatchInput(input) {
  const patch = firstNonEmptyString(input.patch, input.raw, input.value);
  if (!patch) return input;
  const normalized = { ...input, patch };
  delete normalized.raw;
  delete normalized.value;
  return normalized;
}
function firstNonEmptyString(...values) {
  for (const value of values) {
    if (typeof value === "string" && value.trim()) {
      return value;
    }
  }
  return "";
}
function normalizeStringArray2(value) {
  if (!Array.isArray(value)) return [];
  const uniqueValues = /* @__PURE__ */ new Set();
  for (const entry of value) {
    if (typeof entry !== "string") continue;
    const trimmed = entry.trim();
    if (!trimmed) continue;
    uniqueValues.add(trimmed);
  }
  return [...uniqueValues];
}
function normalizeCodexMcpToolName(server, tool) {
  const serverName = typeof server === "string" ? server : "";
  const toolName = typeof tool === "string" ? tool : "";
  if (!serverName && !toolName) return "tool";
  return `mcp__${serverName}__${toolName}`;
}
function normalizeCodexMcpToolInput(rawArguments) {
  if (typeof rawArguments === "string") {
    return parseCodexArguments(rawArguments);
  }
  if (rawArguments && typeof rawArguments === "object" && !Array.isArray(rawArguments)) {
    return rawArguments;
  }
  return {};
}
function normalizeCodexMcpToolState(rawStatus, resultPayload, rawError) {
  const status = typeof rawStatus === "string" ? rawStatus : "";
  const error48 = typeof rawError === "string" ? rawError : "";
  const resultText = extractCodexMcpResultText(resultPayload);
  const isTerminalStatus = status === "completed" || status === "failed" || status === "error" || status === "cancelled";
  const isTerminal2 = isTerminalStatus || Boolean(error48) || Boolean(resultText);
  const isError = Boolean(error48) || status === "failed" || status === "error" || status === "cancelled";
  let result = error48 || resultText;
  if (!result && isTerminalStatus) {
    result = status === "completed" ? "Completed" : "Failed";
  }
  return {
    isTerminal: isTerminal2,
    isError,
    status: isTerminal2 ? isError ? "error" : "completed" : "running",
    ...result ? { result } : {}
  };
}
function extractCodexMcpResultText(resultPayload) {
  if (!resultPayload || typeof resultPayload !== "object") return "";
  const content = resultPayload.content;
  if (!Array.isArray(content)) return "";
  return content.map((item) => typeof (item == null ? void 0 : item.text) === "string" ? item.text : "").filter(Boolean).join("\n");
}
var TERMINAL_RESULT_TOOLS = /* @__PURE__ */ new Set([
  "Bash",
  "write_stdin"
]);
function normalizeCodexToolResult(normalizedName, rawResult) {
  if (!rawResult) return rawResult;
  if (!TERMINAL_RESULT_TOOLS.has(normalizedName)) return rawResult;
  return unwrapTerminalResult(rawResult);
}
function unwrapTerminalResult(raw) {
  let result = raw;
  const trimmed = result.trim();
  if (trimmed.startsWith("{")) {
    try {
      const parsed = JSON.parse(trimmed);
      if (typeof parsed.output === "string") {
        result = parsed.output;
      }
    } catch (e2) {
    }
  }
  const outputMarker = "Output:\n";
  const markerIndex = result.indexOf(outputMarker);
  if (markerIndex >= 0) {
    result = result.slice(markerIndex + outputMarker.length);
  }
  return result;
}
function isCodexToolOutputError(output) {
  const exitCodeMatch = output.match(/(?:Exit code:|Process exited with code)\s*(\d+)/i);
  if (exitCodeMatch) {
    return Number(exitCodeMatch[1]) !== 0;
  }
  const trimmed = output.trim();
  if (/^[Ee]rror:/.test(trimmed)) return true;
  if (trimmed.startsWith("{")) {
    try {
      const parsed = JSON.parse(trimmed);
      if ("error" in parsed) return true;
    } catch (e2) {
    }
  }
  return false;
}
function parseCodexArguments(raw) {
  if (!raw) return {};
  try {
    const parsed = JSON.parse(raw);
    if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
      return parsed;
    }
    return { value: parsed };
  } catch (e2) {
    return { raw };
  }
}

// src/providers/codex/history/CodexHistoryStore.ts
function newBubble(timestamp) {
  return {
    contentChunks: [],
    thinkingChunks: [],
    toolCalls: [],
    toolIndexesById: /* @__PURE__ */ new Map(),
    contentBlocks: [],
    startedAt: timestamp,
    lastEventAt: timestamp,
    interrupted: false
  };
}
function newTurnState(id, timestamp) {
  return {
    id,
    startedAt: timestamp,
    lastEventAt: timestamp,
    userChunks: [],
    assistantBubbles: [],
    activeBubbleIndex: null
  };
}
function createPersistedParseContext() {
  return {
    turns: /* @__PURE__ */ new Map(),
    turnOrder: [],
    currentTurnId: null,
    toolCallToTurn: /* @__PURE__ */ new Map(),
    turnCounter: 0
  };
}
function ensureTurn(turns, turnOrder, preferredTurnId, currentTurnId, timestamp) {
  const id = currentTurnId != null ? currentTurnId : preferredTurnId;
  const existing = turns.get(id);
  if (existing) {
    if (timestamp > 0 && timestamp > existing.lastEventAt) {
      existing.lastEventAt = timestamp;
    }
    return existing;
  }
  const turn = newTurnState(id, timestamp);
  turns.set(id, turn);
  turnOrder.push(id);
  return turn;
}
function ensureAssistantBubble(turn, timestamp) {
  if (turn.activeBubbleIndex !== null) {
    const bubble2 = turn.assistantBubbles[turn.activeBubbleIndex];
    if (timestamp > 0 && timestamp > bubble2.lastEventAt) {
      bubble2.lastEventAt = timestamp;
    }
    return bubble2;
  }
  const bubble = newBubble(timestamp);
  turn.assistantBubbles.push(bubble);
  turn.activeBubbleIndex = turn.assistantBubbles.length - 1;
  return bubble;
}
function closeAssistantBubble(turn) {
  turn.activeBubbleIndex = null;
}
function pushToolInvocation(bubble, toolCall) {
  const existingIndex = bubble.toolIndexesById.get(toolCall.id);
  if (existingIndex !== void 0) {
    bubble.toolCalls[existingIndex] = toolCall;
    return;
  }
  bubble.toolIndexesById.set(toolCall.id, bubble.toolCalls.length);
  bubble.toolCalls.push(toolCall);
  bubble.contentBlocks.push({ type: "tool_use", toolId: toolCall.id });
}
function appendUniqueChunk(chunks, value) {
  const trimmed = value.trim();
  if (!trimmed) return;
  if (chunks[chunks.length - 1] === trimmed) return;
  chunks.push(trimmed);
}
function replaceLatestChunk(chunks, value) {
  const trimmed = value.trim();
  if (!trimmed) return;
  chunks.length = 0;
  chunks.push(trimmed);
}
function appendUserChunk(turn, value, timestamp) {
  const chunkCountBefore = turn.userChunks.length;
  appendUniqueChunk(turn.userChunks, value);
  if (turn.userChunks.length > chunkCountBefore && !turn.userTimestamp && timestamp > 0) {
    turn.userTimestamp = timestamp;
  }
}
function newTurn(timestamp = 0) {
  return {
    assistantText: "",
    thinkingText: "",
    toolCalls: [],
    contentBlocks: [],
    interrupted: false,
    timestamp
  };
}
function flushTurn(turn, messages, msgIndex) {
  if (!turn.assistantText && !turn.thinkingText && turn.toolCalls.length === 0) {
    return msgIndex;
  }
  const msg = {
    id: `codex-msg-${msgIndex}`,
    role: "assistant",
    content: turn.assistantText,
    timestamp: turn.timestamp || Date.now(),
    toolCalls: turn.toolCalls.length > 0 ? turn.toolCalls : void 0,
    contentBlocks: turn.contentBlocks.length > 0 ? turn.contentBlocks : void 0
  };
  if (turn.interrupted) {
    msg.isInterrupt = true;
  }
  messages.push(msg);
  return msgIndex + 1;
}
function setTextBlock(turn, content) {
  const index = turn.contentBlocks.findIndex((block) => block.type === "text");
  if (index === -1) {
    turn.contentBlocks.push({ type: "text", content });
    return;
  }
  turn.contentBlocks[index] = { type: "text", content };
}
function setThinkingBlock(turn, content) {
  const normalized = content.trim();
  if (!normalized) {
    return;
  }
  turn.thinkingText = normalized;
  const index = turn.contentBlocks.findIndex((block) => block.type === "thinking");
  if (index === -1) {
    turn.contentBlocks.push({ type: "thinking", content: normalized });
    return;
  }
  turn.contentBlocks[index] = { type: "thinking", content: normalized };
}
function parseTimestamp(value) {
  if (typeof value !== "string") {
    return 0;
  }
  const parsed = Date.parse(value);
  return Number.isFinite(parsed) ? parsed : 0;
}
function parseSessionRecord(line) {
  let parsed;
  try {
    parsed = JSON.parse(line);
  } catch (e2) {
    return null;
  }
  return {
    timestamp: parseTimestamp(parsed.timestamp),
    type: parsed.type,
    event: parsed.event,
    payload: parsed.payload
  };
}
var CODEX_SYSTEM_MESSAGE_PREFIXES = [
  "# AGENTS.md instructions",
  "<environment_context>",
  "<subagent_notification>",
  "<skill>"
];
var CODEX_BRACKET_CONTEXT_PATTERN = /\n\[(?:Current note|Editor selection from|Browser selection from|Canvas selection from)\b/;
function isCodexSystemMessage(text) {
  const trimmed = text.trimStart();
  return CODEX_SYSTEM_MESSAGE_PREFIXES.some((prefix) => trimmed.startsWith(prefix));
}
function extractCodexDisplayContent(text) {
  if (!text) return void 0;
  const bracketMatch = text.match(CODEX_BRACKET_CONTEXT_PATTERN);
  if ((bracketMatch == null ? void 0 : bracketMatch.index) !== void 0) {
    return text.substring(0, bracketMatch.index).trim();
  }
  return void 0;
}
function extractMessageText(content) {
  if (!Array.isArray(content)) {
    return "";
  }
  return content.map((part) => typeof (part == null ? void 0 : part.text) === "string" ? part.text : "").join("");
}
function joinTextParts(parts) {
  return parts.map((part) => {
    if (typeof part === "string") return part;
    return typeof (part == null ? void 0 : part.text) === "string" ? part.text : "";
  }).map((part) => part.trim()).filter(Boolean).join("\n\n").trim();
}
function extractReasoningText(payload) {
  if ("summary" in payload && Array.isArray(payload.summary) && payload.summary.length > 0) {
    return joinTextParts(payload.summary);
  }
  if ("content" in payload && Array.isArray(payload.content) && payload.content.length > 0) {
    return joinTextParts(payload.content);
  }
  return typeof payload.text === "string" ? payload.text.trim() : "";
}
function processLegacyItem(eventType, item, turn) {
  var _a3, _b2, _c, _d2, _e, _f;
  switch (item.type) {
    case "agent_message":
      if (eventType === "item.completed" || eventType === "item.updated") {
        if (item.text) {
          turn.assistantText = item.text;
          setTextBlock(turn, item.text);
        }
      }
      break;
    case "reasoning":
      if (eventType === "item.completed" || eventType === "item.updated") {
        if (item.text) {
          setThinkingBlock(turn, item.text);
        }
      }
      break;
    case "command_execution":
      if (eventType === "item.started") {
        turn.toolCalls.push({
          id: item.id,
          name: normalizeCodexToolName(item.type),
          input: normalizeCodexToolInput(item.type, { command: (_a3 = item.command) != null ? _a3 : "" }),
          status: "running"
        });
        turn.contentBlocks.push({ type: "tool_use", toolId: item.id });
      } else if (eventType === "item.completed") {
        const tc = turn.toolCalls.find((tool) => tool.id === item.id);
        if (tc) {
          const rawOutput = (_b2 = item.aggregated_output) != null ? _b2 : "";
          tc.result = normalizeCodexToolResult(tc.name, rawOutput);
          tc.status = item.exit_code === 0 ? "completed" : "error";
        }
      }
      break;
    case "file_change": {
      const changes = (_c = item.changes) != null ? _c : [];
      if (eventType === "item.started" || eventType === "item.completed") {
        const existing = turn.toolCalls.find((tool) => tool.id === item.id);
        if (!existing) {
          const paths = changes.map((change) => `${change.kind}: ${change.path}`).join(", ");
          turn.toolCalls.push({
            id: item.id,
            name: normalizeCodexToolName("file_change"),
            input: { changes },
            status: item.status === "completed" ? "completed" : "error",
            result: paths ? `Applied: ${paths}` : "Applied"
          });
          turn.contentBlocks.push({ type: "tool_use", toolId: item.id });
        } else if (eventType === "item.completed") {
          existing.status = item.status === "completed" ? "completed" : "error";
        }
      }
      break;
    }
    case "web_search":
      if (eventType === "item.started") {
        turn.toolCalls.push({
          id: item.id,
          name: normalizeCodexToolName(item.type),
          input: normalizeCodexToolInput(item.type, { query: (_d2 = item.query) != null ? _d2 : "" }),
          status: "running"
        });
        turn.contentBlocks.push({ type: "tool_use", toolId: item.id });
      } else if (eventType === "item.completed") {
        const tc = turn.toolCalls.find((tool) => tool.id === item.id);
        if (tc) {
          tc.result = "Search complete";
          tc.status = "completed";
        }
      }
      break;
    case "mcp_tool_call":
      if (eventType === "item.started") {
        const server = (_e = item.server) != null ? _e : "";
        const tool = (_f = item.tool) != null ? _f : "";
        turn.toolCalls.push({
          id: item.id,
          name: `mcp__${server}__${tool}`,
          input: {},
          status: "running"
        });
        turn.contentBlocks.push({ type: "tool_use", toolId: item.id });
      } else if (eventType === "item.completed") {
        const tc = turn.toolCalls.find((tool) => tool.id === item.id);
        if (tc) {
          tc.status = item.status === "completed" ? "completed" : "error";
          tc.result = item.status === "completed" ? "Completed" : "Failed";
        }
      }
      break;
    default:
      break;
  }
}
function nextTurnId(ctx) {
  ctx.turnCounter += 1;
  return `turn-${ctx.turnCounter}`;
}
function processPersistedToolCall(payload, timestamp, ctx) {
  var _a3;
  const callId = payload.call_id;
  if (!callId) return;
  const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
  const bubble = ensureAssistantBubble(turn, timestamp);
  const rawArgs = (_a3 = payload.arguments) != null ? _a3 : payload.input;
  const parsedArgs = parseCodexArguments(rawArgs);
  const normalizedName = normalizeCodexToolName(payload.name);
  const normalizedInput = normalizeCodexToolInput(payload.name, parsedArgs);
  const toolCall = {
    id: callId,
    name: normalizedName,
    input: normalizedInput,
    status: "running"
  };
  pushToolInvocation(bubble, toolCall);
  ctx.toolCallToTurn.set(callId, {
    turnId: turn.id,
    bubbleIndex: turn.activeBubbleIndex
  });
}
function processPersistedToolOutput(payload, timestamp, ctx) {
  const callId = payload.call_id;
  if (!callId) return;
  const rawOutput = typeof payload.output === "string" ? payload.output : Array.isArray(payload.output) ? JSON.stringify(payload.output) : "";
  const origin = ctx.toolCallToTurn.get(callId);
  if (origin) {
    const originTurn = ctx.turns.get(origin.turnId);
    if (originTurn && origin.bubbleIndex < originTurn.assistantBubbles.length) {
      const originBubble = originTurn.assistantBubbles[origin.bubbleIndex];
      const existing = originBubble.toolCalls.find((tool) => tool.id === callId);
      if (existing) {
        existing.result = normalizePersistedToolOutput(existing, payload.output, rawOutput);
        existing.status = isCodexToolOutputError(rawOutput) ? "error" : "completed";
        return;
      }
    }
  }
  const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
  const bubble = ensureAssistantBubble(turn, timestamp);
  const normalizedResult = normalizeCodexToolResult("tool", rawOutput);
  pushToolInvocation(bubble, {
    id: callId,
    name: "tool",
    input: {},
    status: isCodexToolOutputError(rawOutput) ? "error" : "completed",
    result: normalizedResult
  });
}
function normalizePersistedToolOutput(toolCall, rawOutputValue, rawOutputText) {
  if (Array.isArray(rawOutputValue) && toolCall.name === "Read") {
    const filePath = toolCall.input.file_path;
    if (typeof filePath === "string" && filePath) {
      return filePath;
    }
  }
  return normalizeCodexToolResult(toolCall.name, rawOutputText);
}
function processPersistedWebSearchCall(payload, timestamp, lineIndex, ctx) {
  var _a3;
  const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
  const bubble = ensureAssistantBubble(turn, timestamp);
  const callId = payload.call_id || `tail-ws-${lineIndex}`;
  if (bubble.toolIndexesById.has(callId)) return;
  const input = normalizeCodexToolInput("web_search_call", {
    action: (_a3 = payload.action) != null ? _a3 : {}
  });
  const isTerminal2 = payload.status === "completed" || payload.status === "failed" || payload.status === "error" || payload.status === "cancelled";
  const toolCall = {
    id: callId,
    name: "WebSearch",
    input,
    status: isTerminal2 ? payload.status === "completed" ? "completed" : "error" : "running",
    ...isTerminal2 ? { result: "Search complete" } : {}
  };
  pushToolInvocation(bubble, toolCall);
  ctx.toolCallToTurn.set(callId, {
    turnId: turn.id,
    bubbleIndex: turn.assistantBubbles.indexOf(bubble)
  });
}
function processPersistedMcpToolCall(payload, timestamp, ctx) {
  const callId = payload.call_id;
  if (!callId) return;
  const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
  const bubble = ensureAssistantBubble(turn, timestamp);
  if (bubble.toolIndexesById.has(callId)) return;
  const normalizedInput = normalizeCodexMcpToolInput(payload.arguments);
  const normalizedState = normalizeCodexMcpToolState(payload.status, payload.result, payload.error);
  const toolCall = {
    id: callId,
    name: normalizeCodexMcpToolName(payload.server, payload.tool),
    input: normalizedInput,
    status: normalizedState.status,
    ...normalizedState.result ? { result: normalizedState.result } : {}
  };
  pushToolInvocation(bubble, toolCall);
  ctx.toolCallToTurn.set(callId, {
    turnId: turn.id,
    bubbleIndex: turn.activeBubbleIndex
  });
}
function processPersistedPayload(payload, timestamp, lineIndex, ctx) {
  if (!(payload == null ? void 0 : payload.type)) {
    return;
  }
  switch (payload.type) {
    case "message": {
      const messagePayload = payload;
      const text = extractMessageText(messagePayload.content);
      if (messagePayload.role === "user") {
        if (isCodexSystemMessage(text)) break;
        if (ctx.currentTurnId) {
          const prevTurn = ctx.turns.get(ctx.currentTurnId);
          if (prevTurn) closeAssistantBubble(prevTurn);
        }
        ctx.currentTurnId = null;
        const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), null, timestamp);
        ctx.currentTurnId = turn.id;
        if (text) {
          appendUserChunk(turn, text, timestamp);
        }
      } else if (messagePayload.role === "assistant") {
        const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
        const bubble = ensureAssistantBubble(turn, timestamp);
        if (text) {
          appendUniqueChunk(bubble.contentChunks, text);
        }
      }
      break;
    }
    case "reasoning": {
      const reasoningPayload = payload;
      const text = extractReasoningText(reasoningPayload);
      if (!text) break;
      const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
      const bubble = ensureAssistantBubble(turn, timestamp);
      appendUniqueChunk(bubble.thinkingChunks, text);
      break;
    }
    case "function_call":
    case "custom_tool_call":
      processPersistedToolCall(payload, timestamp, ctx);
      break;
    case "function_call_output":
    case "custom_tool_call_output":
      processPersistedToolOutput(payload, timestamp, ctx);
      break;
    case "web_search_call":
      processPersistedWebSearchCall(payload, timestamp, lineIndex, ctx);
      break;
    case "mcp_tool_call":
      processPersistedMcpToolCall(payload, timestamp, ctx);
      break;
    case "compaction":
      break;
    default:
      break;
  }
}
function applyCompactedReplacementHistory(payload, timestamp, ctx) {
  ctx.turns.clear();
  ctx.turnOrder.length = 0;
  ctx.currentTurnId = null;
  ctx.toolCallToTurn.clear();
  ctx.turnCounter = 0;
  const replacementHistory = Array.isArray(payload == null ? void 0 : payload.replacement_history) ? payload.replacement_history : [];
  for (const [index, item] of replacementHistory.entries()) {
    processPersistedPayload(item, timestamp + index, index, ctx);
  }
  if (ctx.currentTurnId) {
    const turn = ctx.turns.get(ctx.currentTurnId);
    if (turn) {
      closeAssistantBubble(turn);
    }
    ctx.currentTurnId = null;
  }
}
function extractServerTurnId(payload) {
  const turnId = payload.turn_id;
  return typeof turnId === "string" ? turnId : void 0;
}
function processEventMsg(payload, timestamp, ctx) {
  if (!(payload == null ? void 0 : payload.type)) return;
  switch (payload.type) {
    case "task_started": {
      const serverTurnId = extractServerTurnId(payload);
      const id = nextTurnId(ctx);
      const turn = ensureTurn(ctx.turns, ctx.turnOrder, id, null, timestamp);
      turn.startedAt = timestamp;
      if (serverTurnId) turn.serverTurnId = serverTurnId;
      ctx.currentTurnId = turn.id;
      break;
    }
    case "task_complete": {
      if (ctx.currentTurnId) {
        const turn = ctx.turns.get(ctx.currentTurnId);
        if (turn) {
          turn.completedAt = timestamp;
          turn.completed = true;
          closeAssistantBubble(turn);
          const serverTurnId = extractServerTurnId(payload);
          if (serverTurnId && !turn.serverTurnId) turn.serverTurnId = serverTurnId;
        }
      }
      ctx.currentTurnId = null;
      break;
    }
    case "turn_aborted": {
      if (ctx.currentTurnId) {
        const turn = ctx.turns.get(ctx.currentTurnId);
        if (turn) {
          const bubble = ensureAssistantBubble(turn, timestamp);
          bubble.interrupted = true;
          closeAssistantBubble(turn);
          turn.completedAt = timestamp;
        }
      }
      ctx.currentTurnId = null;
      break;
    }
    case "user_message": {
      const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
      const msg = payload.message;
      if (typeof msg === "string" && msg.trim()) {
        appendUserChunk(turn, msg, timestamp);
      }
      break;
    }
    case "agent_message": {
      const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
      const bubble = ensureAssistantBubble(turn, timestamp);
      const msg = payload.message;
      if (typeof msg === "string") {
        appendUniqueChunk(bubble.contentChunks, msg);
      }
      break;
    }
    case "agent_reasoning": {
      const text = extractReasoningText(payload);
      if (!text) break;
      const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
      const bubble = ensureAssistantBubble(turn, timestamp);
      appendUniqueChunk(bubble.thinkingChunks, text);
      break;
    }
    case "context_compacted": {
      if (ctx.currentTurnId) {
        const prevTurn = ctx.turns.get(ctx.currentTurnId);
        if (prevTurn) closeAssistantBubble(prevTurn);
      }
      const id = nextTurnId(ctx);
      const turn = ensureTurn(ctx.turns, ctx.turnOrder, id, null, timestamp);
      const bubble = ensureAssistantBubble(turn, timestamp);
      bubble.contentBlocks.push({ type: "context_compacted" });
      closeAssistantBubble(turn);
      ctx.currentTurnId = null;
      break;
    }
    default:
      break;
  }
}
function flushBubbleTurnMessages(turn, msgIndex) {
  const messages = [];
  const userText = turn.userChunks.join("\n").trim();
  if (userText && !isCodexSystemMessage(userText)) {
    const displayContent = extractCodexDisplayContent(userText);
    messages.push({
      id: `codex-msg-${msgIndex}`,
      role: "user",
      content: userText,
      ...displayContent !== void 0 ? { displayContent } : {},
      ...turn.serverTurnId ? { userMessageId: turn.serverTurnId } : {},
      timestamp: turn.userTimestamp || turn.startedAt || Date.now()
    });
    msgIndex += 1;
  }
  let lastAssistantTimestamp = 0;
  const assistantMessages = [];
  for (const bubble of turn.assistantBubbles) {
    const contentText = bubble.contentChunks.join("\n\n");
    const thinkingText = bubble.thinkingChunks.join("\n\n");
    const hasContent = contentText.trim().length > 0;
    const hasThinking = thinkingText.trim().length > 0;
    const hasToolCalls = bubble.toolCalls.length > 0;
    const hasCompactBoundary = bubble.contentBlocks.some((b10) => b10.type === "context_compacted");
    if (!hasContent && !hasThinking && !hasToolCalls && !hasCompactBoundary) {
      if (bubble.interrupted) {
        messages.push({
          id: `codex-msg-${msgIndex}`,
          role: "assistant",
          content: "",
          timestamp: bubble.startedAt || turn.startedAt || Date.now(),
          isInterrupt: true
        });
        msgIndex += 1;
      }
      continue;
    }
    const contentBlocks = [];
    if (hasThinking) {
      contentBlocks.push({ type: "thinking", content: thinkingText.trim() });
    }
    contentBlocks.push(...bubble.contentBlocks);
    if (hasContent) {
      contentBlocks.push({ type: "text", content: contentText.trim() });
    }
    const msg = {
      id: `codex-msg-${msgIndex}`,
      role: "assistant",
      content: contentText.trim(),
      timestamp: bubble.startedAt || turn.startedAt || Date.now(),
      toolCalls: hasToolCalls ? bubble.toolCalls : void 0,
      contentBlocks: contentBlocks.length > 0 ? contentBlocks : void 0
    };
    if (bubble.interrupted) {
      msg.isInterrupt = true;
    }
    if (bubble.lastEventAt > lastAssistantTimestamp) {
      lastAssistantTimestamp = bubble.lastEventAt;
    }
    assistantMessages.push(msg);
    messages.push(msg);
    msgIndex += 1;
  }
  if (assistantMessages.length > 0 && turn.userTimestamp && lastAssistantTimestamp > turn.userTimestamp) {
    const durationMs = lastAssistantTimestamp - turn.userTimestamp;
    const lastMsg = assistantMessages[assistantMessages.length - 1];
    lastMsg.durationSeconds = Math.round(durationMs / 1e3);
  }
  if (turn.serverTurnId && turn.completed && assistantMessages.length > 0) {
    const lastNonInterrupt = [...assistantMessages].reverse().find((m2) => !m2.isInterrupt);
    if (lastNonInterrupt) {
      lastNonInterrupt.assistantMessageId = turn.serverTurnId;
    }
  }
  return { messages, nextMsgIndex: msgIndex };
}
var SAFE_SESSION_ID_PATTERN = /^[A-Za-z0-9_-]+$/;
function getPathModuleForSessionPath(sessionPath) {
  return sessionPath.includes("\\") || /^[A-Za-z]:/.test(sessionPath) ? path14.win32 : path14.posix;
}
function deriveCodexSessionsRootFromSessionPath(sessionFilePath) {
  if (!sessionFilePath) {
    return null;
  }
  const pathModule = getPathModuleForSessionPath(sessionFilePath);
  let current = pathModule.dirname(pathModule.normalize(sessionFilePath));
  let previous = null;
  while (current && current !== previous) {
    if (pathModule.basename(current).toLowerCase() === "sessions") {
      return current;
    }
    previous = current;
    current = pathModule.dirname(current);
  }
  return null;
}
function deriveCodexMemoriesDirFromSessionsRoot(sessionsDir) {
  if (!sessionsDir) {
    return null;
  }
  const pathModule = getPathModuleForSessionPath(sessionsDir);
  return pathModule.join(pathModule.dirname(sessionsDir), "memories");
}
function findCodexSessionFile(threadId, root = path14.join(os9.homedir(), ".codex", "sessions")) {
  if (!threadId || !SAFE_SESSION_ID_PATTERN.test(threadId) || !fs14.existsSync(root)) {
    return null;
  }
  const directPath = path14.join(root, `${threadId}.jsonl`);
  if (fs14.existsSync(directPath)) {
    return directPath;
  }
  const stack = [root];
  while (stack.length > 0) {
    const current = stack.pop();
    if (!current) {
      continue;
    }
    let entries;
    try {
      entries = fs14.readdirSync(current, { withFileTypes: true });
    } catch (e2) {
      continue;
    }
    for (const entry of entries) {
      const fullPath = path14.join(current, entry.name);
      if (entry.isDirectory()) {
        stack.push(fullPath);
        continue;
      }
      if (entry.isFile() && entry.name.endsWith(`-${threadId}.jsonl`)) {
        return fullPath;
      }
    }
  }
  return null;
}
function parseCodexSessionFile(filePath) {
  let content;
  try {
    content = fs14.readFileSync(filePath, "utf-8");
  } catch (e2) {
    return [];
  }
  return parseCodexSessionContent(content);
}
function parseCodexSessionContent(content) {
  const turns = parseCodexSessionTurns(content);
  return turns.flatMap((t2) => t2.messages);
}
function parseCodexSessionTurns(content) {
  const records = content.split("\n").filter((line) => line.trim()).map(parseSessionRecord).filter((record2) => record2 !== null);
  let hasLegacy = false;
  let hasModern = false;
  for (const record2 of records) {
    if (record2.type === "event") hasLegacy = true;
    else if (record2.type === "event_msg" || record2.type === "response_item" || record2.type === "compacted") hasModern = true;
    if (hasLegacy && hasModern) break;
  }
  if (hasLegacy && !hasModern) {
    const messages = parseLegacySession(records);
    return messages.length > 0 ? [{ turnId: null, messages }] : [];
  }
  return parseModernSessionTurns(records);
}
function parseLegacySession(records) {
  const messages = [];
  let turn = newTurn();
  let msgIndex = 0;
  for (const parsed of records) {
    if (parsed.type === "event" && parsed.event) {
      const event = parsed.event;
      switch (event.type) {
        case "turn.started":
          if (turn.assistantText || turn.thinkingText || turn.toolCalls.length > 0) {
            msgIndex = flushTurn(turn, messages, msgIndex);
          }
          turn = newTurn();
          break;
        case "item.started":
        case "item.updated":
        case "item.completed":
          if (event.item) {
            processLegacyItem(event.type, event.item, turn);
          }
          break;
        case "turn.completed":
          msgIndex = flushTurn(turn, messages, msgIndex);
          turn = newTurn();
          break;
        case "turn.failed":
          turn.interrupted = true;
          msgIndex = flushTurn(turn, messages, msgIndex);
          turn = newTurn();
          break;
        default:
          break;
      }
    }
  }
  flushTurn(turn, messages, msgIndex);
  return messages;
}
function parseModernSessionTurns(records) {
  const ctx = createPersistedParseContext();
  for (const [lineIndex, parsed] of records.entries()) {
    const timestamp = parsed.timestamp;
    if (parsed.type === "event" && parsed.event) {
      processLegacyEventInModernContext(parsed.event, timestamp, ctx);
      continue;
    }
    if (parsed.type === "event_msg") {
      processEventMsg(parsed.payload, timestamp, ctx);
      continue;
    }
    if (parsed.type === "compacted") {
      applyCompactedReplacementHistory(parsed.payload, timestamp, ctx);
      continue;
    }
    if (parsed.type === "response_item") {
      processPersistedPayload(parsed.payload, timestamp, lineIndex, ctx);
    }
  }
  return flushBubbleTurnsGrouped(ctx.turns, ctx.turnOrder);
}
function flushBubbleTurnsGrouped(turns, turnOrder) {
  var _a3;
  const result = [];
  let messageOffset = 0;
  for (const turnId of turnOrder) {
    const turn = turns.get(turnId);
    if (!turn) continue;
    const { messages: turnMessages, nextMsgIndex } = flushBubbleTurnMessages(turn, messageOffset);
    if (turnMessages.length === 0) continue;
    messageOffset = nextMsgIndex;
    result.push({
      turnId: (_a3 = turn.serverTurnId) != null ? _a3 : null,
      messages: turnMessages
    });
  }
  return result;
}
function findToolCallOrigin(ctx, callId) {
  var _a3;
  const origin = ctx.toolCallToTurn.get(callId);
  if (!origin) {
    return null;
  }
  const turn = ctx.turns.get(origin.turnId);
  if (!turn || origin.bubbleIndex >= turn.assistantBubbles.length) {
    return null;
  }
  return (_a3 = turn.assistantBubbles[origin.bubbleIndex].toolCalls.find((tool) => tool.id === callId)) != null ? _a3 : null;
}
function trackToolCallOrigin(ctx, callId, turn) {
  ctx.toolCallToTurn.set(callId, {
    turnId: turn.id,
    bubbleIndex: turn.activeBubbleIndex
  });
}
function ensureModernLegacyToolCall(ctx, timestamp, item, build) {
  const existing = findToolCallOrigin(ctx, item.id);
  if (existing) {
    return existing;
  }
  const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
  const bubble = ensureAssistantBubble(turn, timestamp);
  const toolCall = build();
  pushToolInvocation(bubble, toolCall);
  trackToolCallOrigin(ctx, item.id, turn);
  return toolCall;
}
function processLegacyItemInModernContext(eventType, item, timestamp, ctx) {
  var _a3, _b2;
  switch (item.type) {
    case "agent_message": {
      if ((eventType === "item.updated" || eventType === "item.completed") && item.text) {
        const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
        const bubble = ensureAssistantBubble(turn, timestamp);
        replaceLatestChunk(bubble.contentChunks, item.text);
      }
      break;
    }
    case "reasoning": {
      if ((eventType === "item.updated" || eventType === "item.completed") && item.text) {
        const turn = ensureTurn(ctx.turns, ctx.turnOrder, nextTurnId(ctx), ctx.currentTurnId, timestamp);
        const bubble = ensureAssistantBubble(turn, timestamp);
        replaceLatestChunk(bubble.thinkingChunks, item.text);
      }
      break;
    }
    case "command_execution": {
      if (eventType === "item.started") {
        ensureModernLegacyToolCall(ctx, timestamp, item, () => {
          var _a4;
          return {
            id: item.id,
            name: normalizeCodexToolName(item.type),
            input: normalizeCodexToolInput(item.type, { command: (_a4 = item.command) != null ? _a4 : "" }),
            status: "running"
          };
        });
        break;
      }
      if (eventType === "item.completed") {
        const toolCall = ensureModernLegacyToolCall(ctx, timestamp, item, () => {
          var _a4;
          return {
            id: item.id,
            name: normalizeCodexToolName(item.type),
            input: normalizeCodexToolInput(item.type, { command: (_a4 = item.command) != null ? _a4 : "" }),
            status: "running"
          };
        });
        const rawOutput = (_a3 = item.aggregated_output) != null ? _a3 : "";
        toolCall.result = normalizeCodexToolResult(toolCall.name, rawOutput);
        toolCall.status = item.exit_code === 0 ? "completed" : "error";
      }
      break;
    }
    case "file_change": {
      if (eventType !== "item.started" && eventType !== "item.completed") {
        break;
      }
      const changes = (_b2 = item.changes) != null ? _b2 : [];
      const toolCall = ensureModernLegacyToolCall(ctx, timestamp, item, () => ({
        id: item.id,
        name: normalizeCodexToolName("file_change"),
        input: { changes },
        status: "running"
      }));
      if (eventType === "item.completed") {
        const paths = changes.map((change) => `${change.kind}: ${change.path}`).join(", ");
        toolCall.result = paths ? `Applied: ${paths}` : "Applied";
        toolCall.status = item.status === "completed" ? "completed" : "error";
      }
      break;
    }
    case "web_search": {
      if (eventType === "item.started") {
        ensureModernLegacyToolCall(ctx, timestamp, item, () => {
          var _a4;
          return {
            id: item.id,
            name: normalizeCodexToolName(item.type),
            input: normalizeCodexToolInput(item.type, { query: (_a4 = item.query) != null ? _a4 : "" }),
            status: "running"
          };
        });
        break;
      }
      if (eventType === "item.completed") {
        const toolCall = ensureModernLegacyToolCall(ctx, timestamp, item, () => {
          var _a4;
          return {
            id: item.id,
            name: normalizeCodexToolName(item.type),
            input: normalizeCodexToolInput(item.type, { query: (_a4 = item.query) != null ? _a4 : "" }),
            status: "running"
          };
        });
        toolCall.result = "Search complete";
        toolCall.status = "completed";
      }
      break;
    }
    case "mcp_tool_call": {
      if (eventType === "item.started") {
        ensureModernLegacyToolCall(ctx, timestamp, item, () => {
          var _a4, _b3;
          return {
            id: item.id,
            name: `mcp__${(_a4 = item.server) != null ? _a4 : ""}__${(_b3 = item.tool) != null ? _b3 : ""}`,
            input: {},
            status: "running"
          };
        });
        break;
      }
      if (eventType === "item.completed") {
        const toolCall = ensureModernLegacyToolCall(ctx, timestamp, item, () => {
          var _a4, _b3;
          return {
            id: item.id,
            name: `mcp__${(_a4 = item.server) != null ? _a4 : ""}__${(_b3 = item.tool) != null ? _b3 : ""}`,
            input: {},
            status: "running"
          };
        });
        toolCall.status = item.status === "completed" ? "completed" : "error";
        toolCall.result = item.status === "completed" ? "Completed" : "Failed";
      }
      break;
    }
    default:
      break;
  }
}
function processLegacyEventInModernContext(event, timestamp, ctx) {
  switch (event.type) {
    case "turn.started": {
      if (ctx.currentTurnId) {
        const previousTurn = ctx.turns.get(ctx.currentTurnId);
        if (previousTurn) {
          closeAssistantBubble(previousTurn);
        }
      }
      const id = nextTurnId(ctx);
      ensureTurn(ctx.turns, ctx.turnOrder, id, null, timestamp);
      ctx.currentTurnId = id;
      break;
    }
    case "turn.completed": {
      if (ctx.currentTurnId) {
        const turn = ctx.turns.get(ctx.currentTurnId);
        if (turn) closeAssistantBubble(turn);
      }
      ctx.currentTurnId = null;
      break;
    }
    case "turn.failed": {
      if (ctx.currentTurnId) {
        const turn = ctx.turns.get(ctx.currentTurnId);
        if (turn) {
          const bubble = ensureAssistantBubble(turn, timestamp);
          bubble.interrupted = true;
          closeAssistantBubble(turn);
        }
      }
      ctx.currentTurnId = null;
      break;
    }
    case "item.started":
    case "item.updated":
    case "item.completed":
      if (event.item) {
        processLegacyItemInModernContext(event.type, event.item, timestamp, ctx);
      }
      break;
    default:
      break;
  }
}

// src/providers/codex/history/CodexConversationHistoryService.ts
function readSessionTurns(sessionFilePath) {
  let content;
  try {
    content = require("fs").readFileSync(sessionFilePath, "utf-8");
  } catch (e2) {
    return [];
  }
  return parseCodexSessionTurns(content);
}
var CodexConversationHistoryService = class {
  constructor() {
    this.hydratedConversationPaths = /* @__PURE__ */ new Map();
  }
  async hydrateConversationHistory(conversation, _vaultPath) {
    var _a3, _b2, _c, _d2, _e, _f, _g;
    const state = getCodexState(conversation.providerState);
    const transcriptRootPath = (_a3 = state.transcriptRootPath) != null ? _a3 : deriveCodexSessionsRootFromSessionPath(state.sessionFilePath);
    if (this.isPendingForkConversation(conversation) && conversation.messages.length > 0) {
      return;
    }
    if (this.isPendingForkConversation(conversation)) {
      const sourceSessionFile = this.resolveSourceSessionFile(state);
      if (!sourceSessionFile) return;
      const turns = readSessionTurns(sourceSessionFile);
      const resumeAt = state.forkSource.resumeAt;
      const truncated = this.truncateTurnsAtCheckpoint(turns, resumeAt);
      if (!truncated) {
        this.hydratedConversationPaths.delete(conversation.id);
        return;
      }
      conversation.messages = truncated.flatMap((t2) => t2.messages);
      return;
    }
    if (state.forkSource && state.threadId) {
      const sourceSessionFile = this.resolveSourceSessionFile(state);
      const forkSessionFile = (_b2 = state.sessionFilePath) != null ? _b2 : state.threadId ? findCodexSessionFile(state.threadId, transcriptRootPath != null ? transcriptRootPath : void 0) : null;
      if (sourceSessionFile && forkSessionFile) {
        const sourceTurns = readSessionTurns(sourceSessionFile);
        const forkTurns = readSessionTurns(forkSessionFile);
        const resumeAt = state.forkSource.resumeAt;
        const sourcePrefix = this.truncateTurnsAtCheckpoint(sourceTurns, resumeAt);
        if (!sourcePrefix) {
          this.hydratedConversationPaths.delete(conversation.id);
          return;
        }
        const sourceTurnIds = new Set(sourceTurns.map((t2) => t2.turnId).filter(Boolean));
        const forkOnlyTurns = forkTurns.filter((t2) => !t2.turnId || !sourceTurnIds.has(t2.turnId));
        const messages = [
          ...sourcePrefix.flatMap((t2) => t2.messages),
          ...forkOnlyTurns.flatMap((t2) => t2.messages)
        ];
        if (messages.length === 0) {
          this.hydratedConversationPaths.delete(conversation.id);
          return;
        }
        conversation.messages = messages;
        this.hydratedConversationPaths.set(conversation.id, `fork::${state.threadId}`);
        return;
      }
    }
    const threadId = (_d2 = (_c = state.threadId) != null ? _c : conversation.sessionId) != null ? _d2 : null;
    const sessionFilePath = (_e = state.sessionFilePath) != null ? _e : threadId ? findCodexSessionFile(threadId, transcriptRootPath != null ? transcriptRootPath : void 0) : null;
    const resolvedTranscriptRootPath = transcriptRootPath != null ? transcriptRootPath : deriveCodexSessionsRootFromSessionPath(sessionFilePath);
    if (!sessionFilePath) {
      this.hydratedConversationPaths.delete(conversation.id);
      return;
    }
    const hydrationKey = `${threadId != null ? threadId : ""}::${sessionFilePath}`;
    if (conversation.messages.length > 0 && this.hydratedConversationPaths.get(conversation.id) === hydrationKey) {
      return;
    }
    if (sessionFilePath !== state.sessionFilePath) {
      conversation.providerState = {
        ...(_f = conversation.providerState) != null ? _f : {},
        ...threadId ? { threadId } : {},
        sessionFilePath,
        ...resolvedTranscriptRootPath ? { transcriptRootPath: resolvedTranscriptRootPath } : {}
      };
    } else if (resolvedTranscriptRootPath && resolvedTranscriptRootPath !== state.transcriptRootPath) {
      conversation.providerState = {
        ...(_g = conversation.providerState) != null ? _g : {},
        ...threadId ? { threadId } : {},
        transcriptRootPath: resolvedTranscriptRootPath
      };
    }
    const sdkMessages = parseCodexSessionFile(sessionFilePath);
    if (sdkMessages.length === 0) {
      this.hydratedConversationPaths.delete(conversation.id);
      return;
    }
    conversation.messages = sdkMessages;
    this.hydratedConversationPaths.set(conversation.id, hydrationKey);
  }
  async deleteConversationSession(_conversation, _vaultPath) {
  }
  resolveSessionIdForConversation(conversation) {
    var _a3, _b2, _c, _d2;
    if (!conversation) return null;
    const state = getCodexState(conversation.providerState);
    return (_d2 = (_c = (_a3 = state.threadId) != null ? _a3 : conversation.sessionId) != null ? _c : (_b2 = state.forkSource) == null ? void 0 : _b2.sessionId) != null ? _d2 : null;
  }
  isPendingForkConversation(conversation) {
    const state = getCodexState(conversation.providerState);
    return !!state.forkSource && !state.threadId && !conversation.sessionId;
  }
  buildForkProviderState(sourceSessionId, resumeAt, sourceProviderState) {
    var _a3;
    const sourceState = getCodexState(sourceProviderState);
    const sourceTranscriptRootPath = (_a3 = sourceState.transcriptRootPath) != null ? _a3 : deriveCodexSessionsRootFromSessionPath(sourceState.sessionFilePath);
    const providerState = {
      forkSource: { sessionId: sourceSessionId, resumeAt },
      ...sourceState.sessionFilePath ? { forkSourceSessionFilePath: sourceState.sessionFilePath } : {},
      ...sourceTranscriptRootPath ? { forkSourceTranscriptRootPath: sourceTranscriptRootPath } : {}
    };
    return providerState;
  }
  buildPersistedProviderState(conversation) {
    const entries = Object.entries(getCodexState(conversation.providerState)).filter(([, value]) => value !== void 0);
    return entries.length > 0 ? Object.fromEntries(entries) : void 0;
  }
  // ---------------------------------------------------------------------------
  // Private helpers
  // ---------------------------------------------------------------------------
  resolveSourceSessionFile(state) {
    var _a3, _b2;
    if (!state.forkSource) return null;
    const sourceTranscriptRootPath = (_a3 = state.forkSourceTranscriptRootPath) != null ? _a3 : deriveCodexSessionsRootFromSessionPath(state.forkSourceSessionFilePath);
    return (_b2 = state.forkSourceSessionFilePath) != null ? _b2 : findCodexSessionFile(state.forkSource.sessionId, sourceTranscriptRootPath != null ? sourceTranscriptRootPath : void 0);
  }
  truncateTurnsAtCheckpoint(turns, resumeAt) {
    const checkpointIndex = turns.findIndex((turn) => turn.turnId === resumeAt);
    if (checkpointIndex < 0) {
      return null;
    }
    return turns.slice(0, checkpointIndex + 1);
  }
};

// src/providers/codex/normalization/codexSubagentNormalization.ts
function parseJsonObject(raw) {
  if (!raw) return null;
  try {
    const parsed = JSON.parse(raw);
    if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
      return parsed;
    }
  } catch (e2) {
    return null;
  }
  return null;
}
function extractCodexSpawnResult(raw) {
  const parsed = parseJsonObject(raw);
  if (!parsed) return {};
  return {
    agentId: typeof parsed.agent_id === "string" ? parsed.agent_id : void 0,
    nickname: typeof parsed.nickname === "string" ? parsed.nickname : void 0
  };
}
function extractCodexWaitResult(raw) {
  const parsed = parseJsonObject(raw);
  if (!parsed) {
    return { statuses: {}, timedOut: false };
  }
  const rawStatuses = parsed.status;
  const statuses = {};
  if (rawStatuses && typeof rawStatuses === "object" && !Array.isArray(rawStatuses)) {
    for (const [agentId, value] of Object.entries(rawStatuses)) {
      if (!value || typeof value !== "object" || Array.isArray(value)) continue;
      const status = value;
      statuses[agentId] = {
        completed: typeof status.completed === "string" ? status.completed : void 0,
        error: typeof status.error === "string" ? status.error : void 0,
        failed: typeof status.failed === "string" ? status.failed : void 0
      };
    }
  }
  return {
    statuses,
    timedOut: parsed.timed_out === true
  };
}
function getCodexSubagentPrompt(input) {
  return typeof input.message === "string" ? input.message : "";
}
function getCodexSubagentModel(input) {
  return typeof input.model === "string" ? input.model : "";
}
function getCodexSubagentDescription(nickname, model) {
  if (nickname && model) return `${nickname} (${model})`;
  if (nickname) return nickname;
  if (model) return `Codex subagent (${model})`;
  return "Codex subagent";
}
function resolveCodexWaitCompletion(spawnResult, siblingToolCalls) {
  var _a3;
  for (const toolCall of siblingToolCalls) {
    if (toolCall.name !== TOOL_WAIT && toolCall.name !== TOOL_WAIT_AGENT) {
      continue;
    }
    const waitResult = extractCodexWaitResult(toolCall.result);
    const statusEntries = Object.entries(waitResult.statuses);
    if (statusEntries.length === 0 && !waitResult.timedOut) {
      continue;
    }
    let agentStatus;
    if (spawnResult.agentId) {
      agentStatus = waitResult.statuses[spawnResult.agentId];
    } else if (statusEntries.length === 1) {
      agentStatus = statusEntries[0][1];
    }
    if (agentStatus == null ? void 0 : agentStatus.completed) {
      return { status: "completed", result: agentStatus.completed };
    }
    const failure = (_a3 = agentStatus == null ? void 0 : agentStatus.error) != null ? _a3 : agentStatus == null ? void 0 : agentStatus.failed;
    if (failure) {
      return { status: "error", result: failure };
    }
    if (waitResult.timedOut) {
      return { status: "error", result: "Timed out" };
    }
  }
  return { status: "running" };
}
function buildCodexSubagentInfo(spawnToolCall, siblingToolCalls = []) {
  const prompt = getCodexSubagentPrompt(spawnToolCall.input);
  const model = getCodexSubagentModel(spawnToolCall.input);
  const spawnResult = extractCodexSpawnResult(spawnToolCall.result);
  const description = getCodexSubagentDescription(spawnResult.nickname, model);
  if (spawnToolCall.status === "error") {
    return {
      id: spawnToolCall.id,
      description,
      prompt,
      mode: "sync",
      isExpanded: false,
      status: "error",
      result: spawnToolCall.result,
      toolCalls: []
    };
  }
  const completion = resolveCodexWaitCompletion(spawnResult, siblingToolCalls);
  return {
    id: spawnToolCall.id,
    description,
    prompt,
    mode: "sync",
    isExpanded: false,
    status: completion.status,
    result: completion.result,
    toolCalls: [],
    ...spawnResult.agentId ? { agentId: spawnResult.agentId } : {}
  };
}
var codexSubagentLifecycleAdapter = {
  isHiddenTool(name) {
    return name === TOOL_WAIT || name === TOOL_WAIT_AGENT || name === TOOL_CLOSE_AGENT;
  },
  isSpawnTool(name) {
    return name === TOOL_SPAWN_AGENT;
  },
  isWaitTool(name) {
    return name === TOOL_WAIT || name === TOOL_WAIT_AGENT;
  },
  isCloseTool(name) {
    return name === TOOL_CLOSE_AGENT;
  },
  resolveSpawnToolIds(waitToolCall, agentIdToSpawnId) {
    const spawnIds = /* @__PURE__ */ new Set();
    const waitResult = extractCodexWaitResult(waitToolCall.result);
    for (const agentId of Object.keys(waitResult.statuses)) {
      const spawnId = agentIdToSpawnId.get(agentId);
      if (spawnId) {
        spawnIds.add(spawnId);
      }
    }
    const targets = Array.isArray(waitToolCall.input.targets) ? waitToolCall.input.targets : Array.isArray(waitToolCall.input.ids) ? waitToolCall.input.ids : [];
    for (const target of targets) {
      if (typeof target !== "string") continue;
      const spawnId = agentIdToSpawnId.get(target);
      if (spawnId) {
        spawnIds.add(spawnId);
      }
    }
    return [...spawnIds];
  },
  buildSubagentInfo(spawnToolCall, siblingToolCalls = []) {
    return buildCodexSubagentInfo(spawnToolCall, siblingToolCalls);
  },
  extractSpawnResult(raw) {
    return extractCodexSpawnResult(raw);
  },
  extractWaitResult(raw) {
    return extractCodexWaitResult(raw);
  }
};

// src/providers/codex/runtime/CodexChatRuntime.ts
var fs16 = __toESM(require("fs"));
var os10 = __toESM(require("os"));
var path15 = __toESM(require("path"));
init_path();

// src/providers/codex/prompt/encodeCodexTurn.ts
function isCompactCommand2(text) {
  return /^\/compact(\s|$)/i.test(text);
}
function encodeCodexTurn(request) {
  var _a3, _b2, _c;
  const isCompact = isCompactCommand2(request.text);
  if (isCompact) {
    return {
      request,
      persistedContent: request.text,
      prompt: request.text,
      isCompact: true,
      mcpMentions: /* @__PURE__ */ new Set()
    };
  }
  const sections = [];
  sections.push(request.text);
  if (request.currentNotePath) {
    sections.push(`
[Current note: ${request.currentNotePath}]`);
  }
  if ((_a3 = request.editorSelection) == null ? void 0 : _a3.selectedText) {
    sections.push(
      `
[Editor selection from ${request.editorSelection.notePath || "current note"}:
${request.editorSelection.selectedText}
]`
    );
  }
  if ((_b2 = request.browserSelection) == null ? void 0 : _b2.selectedText) {
    sections.push(
      `
[Browser selection from ${(_c = request.browserSelection.url) != null ? _c : "unknown page"}:
${request.browserSelection.selectedText}
]`
    );
  }
  if (request.canvasSelection) {
    const nodeList = request.canvasSelection.nodeIds.join(", ");
    if (nodeList) {
      sections.push(
        `
[Canvas selection from ${request.canvasSelection.canvasPath}:
${nodeList}
]`
      );
    }
  }
  const prompt = sections.join("");
  return {
    request,
    persistedContent: request.text,
    prompt,
    isCompact: false,
    mcpMentions: /* @__PURE__ */ new Set()
  };
}

// src/providers/codex/runtime/CodexNotificationRouter.ts
var COLLAB_AGENT_TOOL_MAP = {
  spawnAgent: "spawn_agent",
  wait: "wait",
  sendInput: "send_input",
  resumeAgent: "resume_agent",
  closeAgent: "close_agent"
};
var CodexNotificationRouter = class {
  constructor(emit, onTurnMetadata) {
    this.emit = emit;
    this.onTurnMetadata = onTurnMetadata;
    this.seenWebSearchIds = /* @__PURE__ */ new Set();
    this.planUpdateCounter = 0;
    this.isPlanTurn = false;
    this.sawPlanDelta = false;
    this.startedUserMessageIds = /* @__PURE__ */ new Set();
    this.startedAgentMessageIds = /* @__PURE__ */ new Set();
    this.agentMessageDeltaIds = /* @__PURE__ */ new Set();
  }
  beginTurn(params) {
    this.isPlanTurn = params.isPlanTurn;
    this.sawPlanDelta = false;
    this.startedUserMessageIds.clear();
    this.startedAgentMessageIds.clear();
    this.agentMessageDeltaIds.clear();
  }
  endTurn() {
    this.isPlanTurn = false;
    this.sawPlanDelta = false;
    this.startedUserMessageIds.clear();
    this.startedAgentMessageIds.clear();
    this.agentMessageDeltaIds.clear();
  }
  handleNotification(method, params) {
    switch (method) {
      case "item/agentMessage/delta":
        this.onAgentMessageDelta(params);
        break;
      case "item/started":
        this.onItemStarted(params);
        break;
      case "item/completed":
        this.onItemCompleted(params);
        break;
      case "item/reasoning/summaryTextDelta":
        this.onReasoningSummaryDelta(params);
        break;
      case "item/reasoning/textDelta":
        this.onReasoningTextDelta(params);
        break;
      case "item/reasoning/summaryPartAdded":
        break;
      case "item/plan/delta":
        this.onPlanDelta(params);
        break;
      case "item/commandExecution/outputDelta":
      case "item/fileChange/outputDelta":
        this.onOutputDelta(params);
        break;
      case "thread/tokenUsage/updated":
        this.onTokenUsageUpdated(params);
        break;
      case "turn/plan/updated":
        this.onPlanUpdated(params);
        break;
      case "turn/completed":
        this.onTurnCompleted(params);
        break;
      case "error":
        this.onError(params);
        break;
      default:
        break;
    }
  }
  onAgentMessageDelta(params) {
    this.agentMessageDeltaIds.add(params.itemId);
    this.emit({ type: "text", content: params.delta });
  }
  onReasoningSummaryDelta(params) {
    this.emit({ type: "thinking", content: params.delta });
  }
  onReasoningTextDelta(params) {
    this.emit({ type: "thinking", content: params.delta });
  }
  onPlanDelta(params) {
    this.sawPlanDelta = true;
    this.emit({ type: "text", content: params.delta });
  }
  onItemStarted(params) {
    const item = params.item;
    switch (item.type) {
      case "userMessage":
        this.emitUserMessageBoundary(item);
        break;
      case "agentMessage":
        this.emitAgentMessageBoundary(item);
        break;
      case "reasoning":
        break;
      case "commandExecution":
        this.emitToolUseFromCommand(item);
        break;
      case "fileChange":
        this.emitToolUseFromFileChange(item);
        break;
      case "imageView":
        this.emitToolUseFromImageView(item);
        break;
      case "webSearch":
        this.emitToolUseFromWebSearch(item);
        break;
      case "collabAgentToolCall":
        this.emitToolUseFromCollabAgent(item);
        break;
      case "mcpToolCall":
        this.emitToolUseFromMcp(item);
        break;
      default:
        break;
    }
  }
  onItemCompleted(params) {
    const item = params.item;
    switch (item.type) {
      case "userMessage":
        if (!this.startedUserMessageIds.has(item.id)) {
          this.emitUserMessageBoundary(item);
        }
        break;
      case "agentMessage":
        this.completeAgentMessage(item);
        break;
      case "commandExecution":
        this.emitToolResultFromCommand(item);
        break;
      case "fileChange":
        this.emitToolResultFromFileChange(item);
        break;
      case "imageView":
        this.emitToolResultFromImageView(item);
        break;
      case "webSearch":
        this.emitToolResultFromWebSearch(item);
        break;
      case "collabAgentToolCall":
        this.emitToolResultFromCollabAgent(item);
        break;
      case "mcpToolCall":
        this.emitToolResultFromMcp(item);
        break;
      case "contextCompaction":
        this.emitContextCompactionBoundary(item);
        break;
      default:
        break;
    }
  }
  // -- commandExecution -------------------------------------------------------
  emitToolUseFromCommand(item) {
    var _a3, _b2, _c;
    const rawAction = (_c = (_b2 = (_a3 = item.commandActions) == null ? void 0 : _a3[0]) == null ? void 0 : _b2.command) != null ? _c : item.command;
    const normalizedName = normalizeCodexToolName("command_execution");
    const input = normalizeCodexToolInput("command_execution", { command: rawAction });
    this.emit({ type: "tool_use", id: item.id, name: normalizedName, input });
  }
  emitToolResultFromCommand(item) {
    var _a3;
    const output = (_a3 = item.aggregatedOutput) != null ? _a3 : "";
    const normalizedName = normalizeCodexToolName("command_execution");
    const content = normalizeCodexToolResult(normalizedName, output);
    const isError = item.exitCode !== null && item.exitCode !== 0;
    this.emit({ type: "tool_result", id: item.id, content, isError });
  }
  // -- fileChange -------------------------------------------------------------
  emitToolUseFromFileChange(item) {
    var _a3;
    this.emit({
      type: "tool_use",
      id: item.id,
      name: normalizeCodexToolName("file_change"),
      input: { changes: (_a3 = item.changes) != null ? _a3 : [] }
    });
  }
  emitToolResultFromFileChange(item) {
    var _a3;
    const paths = ((_a3 = item.changes) != null ? _a3 : []).map((c) => c.path).join(", ");
    this.emit({
      type: "tool_result",
      id: item.id,
      content: paths || "File change completed",
      isError: false
    });
  }
  // -- imageView --------------------------------------------------------------
  emitToolUseFromImageView(item) {
    this.emit({
      type: "tool_use",
      id: item.id,
      name: normalizeCodexToolName("view_image"),
      input: normalizeCodexToolInput("view_image", { path: item.path })
    });
  }
  emitToolResultFromImageView(item) {
    this.emit({ type: "tool_result", id: item.id, content: item.path, isError: false });
  }
  // -- webSearch --------------------------------------------------------------
  emitToolUseFromWebSearch(item) {
    var _a3, _b2, _c, _d2, _e;
    if (this.seenWebSearchIds.has(item.id)) return;
    this.seenWebSearchIds.add(item.id);
    this.emit({
      type: "tool_use",
      id: item.id,
      name: "WebSearch",
      input: normalizeCodexToolInput("web_search", {
        query: (_a3 = item.query) != null ? _a3 : "",
        queries: (_b2 = item.queries) != null ? _b2 : [],
        url: (_c = item.url) != null ? _c : "",
        pattern: (_d2 = item.pattern) != null ? _d2 : "",
        action: (_e = item.action) != null ? _e : {}
      })
    });
  }
  emitToolResultFromWebSearch(item) {
    this.emit({
      type: "tool_result",
      id: item.id,
      content: "Search complete",
      isError: item.status === "failed" || item.status === "error"
    });
  }
  // -- collabAgentToolCall ----------------------------------------------------
  emitToolUseFromCollabAgent(item) {
    var _a3, _b2;
    const toolName = (_a3 = COLLAB_AGENT_TOOL_MAP[item.tool]) != null ? _a3 : item.tool;
    this.emit({
      type: "tool_use",
      id: item.id,
      name: toolName,
      input: (_b2 = item.arguments) != null ? _b2 : {}
    });
  }
  emitToolResultFromCollabAgent(item) {
    var _a3;
    const resultText = item.result && typeof item.result === "object" ? JSON.stringify(item.result) : item.status === "completed" ? "Completed" : (_a3 = item.status) != null ? _a3 : "Done";
    this.emit({
      type: "tool_result",
      id: item.id,
      content: resultText,
      isError: item.status === "failed" || item.status === "error"
    });
  }
  // -- mcpToolCall ------------------------------------------------------------
  emitToolUseFromMcp(item) {
    var _a3;
    this.emit({
      type: "tool_use",
      id: item.id,
      name: `mcp__${item.server}__${item.tool}`,
      input: (_a3 = item.arguments) != null ? _a3 : {}
    });
  }
  emitToolResultFromMcp(item) {
    var _a3;
    let content = "";
    if (item.error) {
      content = item.error;
    } else if ((_a3 = item.result) == null ? void 0 : _a3.content) {
      content = item.result.content.map((c) => {
        var _a4;
        return (_a4 = c.text) != null ? _a4 : "";
      }).filter(Boolean).join("\n");
    }
    if (!content) {
      content = item.status === "completed" ? "Completed" : "Failed";
    }
    this.emit({
      type: "tool_result",
      id: item.id,
      content,
      isError: item.status === "failed" || item.status === "error"
    });
  }
  emitContextCompactionBoundary(_item) {
    this.emit({ type: "context_compacted" });
  }
  emitUserMessageBoundary(item) {
    if (this.startedUserMessageIds.has(item.id)) {
      return;
    }
    this.startedUserMessageIds.add(item.id);
    this.emit({
      type: "user_message_start",
      itemId: item.id,
      content: this.extractUserMessageText(item.content)
    });
  }
  emitAgentMessageBoundary(item) {
    if (this.startedAgentMessageIds.has(item.id)) {
      return;
    }
    this.startedAgentMessageIds.add(item.id);
    this.emit({ type: "assistant_message_start", itemId: item.id });
  }
  completeAgentMessage(item) {
    if (!this.startedAgentMessageIds.has(item.id)) {
      this.emitAgentMessageBoundary(item);
    }
    if (this.agentMessageDeltaIds.has(item.id) || !item.text) {
      return;
    }
    this.emit({ type: "text", content: item.text });
  }
  extractUserMessageText(content) {
    return content.map((part) => part.type === "text" ? part.text : "").filter((text) => text.length > 0).join("\n\n");
  }
  // -- turn/plan/updated (update_plan) ----------------------------------------
  onPlanUpdated(params) {
    var _a3;
    this.planUpdateCounter += 1;
    const syntheticId = `plan-update-${(_a3 = params.turnId) != null ? _a3 : this.planUpdateCounter}`;
    const PLAN_STATUS_MAP = {
      inProgress: "in_progress",
      in_progress: "in_progress"
    };
    const todos = params.plan.map((item) => {
      var _a4;
      return {
        id: "",
        content: item.step,
        activeForm: item.step,
        status: (_a4 = PLAN_STATUS_MAP[item.status]) != null ? _a4 : item.status
      };
    });
    this.emit({ type: "tool_use", id: syntheticId, name: "TodoWrite", input: { todos } });
    this.emit({ type: "tool_result", id: syntheticId, content: "Plan updated", isError: false });
  }
  // -- outputDelta (commandExecution + fileChange) ----------------------------
  onOutputDelta(params) {
    this.emit({ type: "tool_output", id: params.itemId, content: params.delta });
  }
  // -- tokenUsage / turnCompleted / error -------------------------------------
  onTokenUsageUpdated(params) {
    const last = params.tokenUsage.last;
    const contextTokens = last.inputTokens;
    const contextWindow = params.tokenUsage.modelContextWindow;
    const usage = {
      inputTokens: last.inputTokens,
      cacheCreationInputTokens: 0,
      cacheReadInputTokens: last.cachedInputTokens,
      contextWindow,
      contextWindowIsAuthoritative: contextWindow > 0,
      contextTokens,
      percentage: contextWindow > 0 ? Math.min(100, Math.max(0, Math.round(contextTokens / contextWindow * 100))) : 0
    };
    this.emit({ type: "usage", usage, sessionId: params.threadId });
  }
  onTurnCompleted(params) {
    var _a3;
    const turn = params.turn;
    if (turn.status === "failed" && turn.error) {
      this.emit({ type: "error", content: turn.error.message });
    }
    if (turn.status === "completed") {
      (_a3 = this.onTurnMetadata) == null ? void 0 : _a3.call(this, {
        assistantMessageId: turn.id,
        ...this.isPlanTurn && this.sawPlanDelta ? { planCompleted: true } : {}
      });
    }
    this.emit({ type: "done" });
  }
  onError(params) {
    if (params.willRetry) return;
    this.emit({ type: "error", content: params.error.message });
  }
};

// src/providers/codex/runtime/CodexServerRequestRouter.ts
var CodexServerRequestRouter = class {
  constructor() {
    this.approvalCallback = null;
    this.askUserCallback = null;
    this.pendingApprovalRequests = /* @__PURE__ */ new Map();
    this.askUserAbortController = null;
    this.pendingAskUserRequestId = null;
    this.pendingAskUserThreadId = null;
  }
  setApprovalCallback(callback) {
    this.approvalCallback = callback;
  }
  setAskUserCallback(callback) {
    this.askUserCallback = callback;
  }
  async handleServerRequest(requestIdOrMethod, methodOrParams, maybeParams) {
    const hasExplicitRequestId = maybeParams !== void 0;
    const requestId = hasExplicitRequestId ? requestIdOrMethod : void 0;
    const method = hasExplicitRequestId ? methodOrParams : requestIdOrMethod;
    const params = hasExplicitRequestId ? maybeParams : methodOrParams;
    switch (method) {
      case "item/commandExecution/requestApproval":
        return this.handleCommandApproval(requestId, params);
      case "item/fileChange/requestApproval":
        return this.handleFileChangeApproval(requestId, params);
      case "item/permissions/requestApproval":
        return this.handlePermissionsApproval(requestId, params);
      case "item/tool/requestUserInput":
        return this.handleUserInputRequest(requestId, params);
      default:
        throw new Error(`Unsupported server request: ${method}`);
    }
  }
  hasPendingApprovalRequest(requestId, threadId) {
    return this.pendingApprovalRequests.get(requestId) === threadId;
  }
  async handleCommandApproval(requestId, params) {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2;
    if (!this.approvalCallback) return { decision: "decline" };
    const command = (_a3 = params.command) != null ? _a3 : "";
    const toolName = normalizeCodexToolName("command_execution");
    const input = {
      command,
      cwd: (_b2 = params.cwd) != null ? _b2 : null,
      reason: (_c = params.reason) != null ? _c : null,
      commandActions: (_d2 = params.commandActions) != null ? _d2 : null,
      approvalId: (_e = params.approvalId) != null ? _e : null,
      networkApprovalContext: (_f = params.networkApprovalContext) != null ? _f : null,
      additionalPermissions: (_g = params.additionalPermissions) != null ? _g : null,
      skillMetadata: (_h = params.skillMetadata) != null ? _h : null,
      proposedExecpolicyAmendment: (_i = params.proposedExecpolicyAmendment) != null ? _i : null,
      proposedNetworkPolicyAmendments: (_j2 = params.proposedNetworkPolicyAmendments) != null ? _j2 : null
    };
    const description = describeCommandApproval(params);
    if (requestId !== void 0) {
      this.pendingApprovalRequests.set(requestId, params.threadId);
    }
    try {
      const decision = await this.approvalCallback(toolName, input, description, {
        ...params.reason ? { decisionReason: params.reason } : {},
        ...params.networkApprovalContext ? { networkApprovalContext: params.networkApprovalContext } : {},
        ...params.additionalPermissions ? { additionalPermissions: params.additionalPermissions } : {},
        decisionOptions: buildCommandApprovalDecisionOptions(params)
      });
      return { decision: mapCommandApprovalDecision(decision) };
    } finally {
      if (requestId !== void 0) {
        this.pendingApprovalRequests.delete(requestId);
      }
    }
  }
  async handleFileChangeApproval(requestId, params) {
    var _a3;
    if (!this.approvalCallback) return { decision: "decline" };
    const reason = (_a3 = params.reason) != null ? _a3 : void 0;
    const toolName = normalizeCodexToolName("file_change");
    const input = { reason: reason != null ? reason : null };
    const description = reason ? `File change: ${reason}` : "File change";
    if (requestId !== void 0) {
      this.pendingApprovalRequests.set(requestId, params.threadId);
    }
    try {
      const decision = await this.approvalCallback(toolName, input, description, {});
      return { decision: mapFileChangeApprovalDecision(decision) };
    } finally {
      if (requestId !== void 0) {
        this.pendingApprovalRequests.delete(requestId);
      }
    }
  }
  async handlePermissionsApproval(requestId, params) {
    var _a3, _b2;
    if (!this.approvalCallback) return { permissions: {}, scope: "turn" };
    const requestedPermissions = (_a3 = params.permissions) != null ? _a3 : {};
    const reason = (_b2 = params.reason) != null ? _b2 : void 0;
    const toolName = "permissions";
    const description = reason ? `Permission request: ${reason}` : "Permission request";
    if (requestId !== void 0) {
      this.pendingApprovalRequests.set(requestId, params.threadId);
    }
    let decision;
    try {
      decision = await this.approvalCallback(toolName, requestedPermissions, description, {});
    } finally {
      if (requestId !== void 0) {
        this.pendingApprovalRequests.delete(requestId);
      }
    }
    if (decision === "allow") {
      return { permissions: requestedPermissions, scope: "turn" };
    }
    if (decision === "allow-always") {
      return { permissions: requestedPermissions, scope: "session" };
    }
    return { permissions: {}, scope: "turn" };
  }
  abortPendingAskUser(requestId, threadId) {
    if (!this.askUserAbortController) {
      return false;
    }
    if (requestId !== void 0 && requestId !== this.pendingAskUserRequestId) {
      return false;
    }
    if (threadId !== void 0 && threadId !== this.pendingAskUserThreadId) {
      return false;
    }
    this.askUserAbortController.abort();
    this.askUserAbortController = null;
    this.pendingAskUserRequestId = null;
    this.pendingAskUserThreadId = null;
    return true;
  }
  async handleUserInputRequest(requestId, params) {
    var _a3;
    if (!this.askUserCallback) return { answers: {} };
    const questions = (_a3 = params.questions) != null ? _a3 : [];
    const input = { questions };
    this.askUserAbortController = new AbortController();
    this.pendingAskUserRequestId = requestId != null ? requestId : null;
    this.pendingAskUserThreadId = params.threadId;
    let userAnswers;
    try {
      userAnswers = await this.askUserCallback(input, this.askUserAbortController.signal);
    } finally {
      this.askUserAbortController = null;
      this.pendingAskUserRequestId = null;
      this.pendingAskUserThreadId = null;
    }
    if (!userAnswers) return { answers: {} };
    const answers = {};
    for (const [key, value] of Object.entries(userAnswers)) {
      answers[key] = { answers: normalizeAnswers(value) };
    }
    return { answers };
  }
};
function describeCommandApproval(params) {
  var _a3;
  const networkContext = params.networkApprovalContext;
  if (networkContext) {
    return `Allow ${networkContext.protocol} access to ${networkContext.host}`;
  }
  const command = (_a3 = params.command) != null ? _a3 : "";
  return command ? `Execute: ${command}` : "Execute command";
}
function buildCommandApprovalDecisionOptions(params) {
  var _a3;
  const availableDecisions = (_a3 = params.availableDecisions) != null ? _a3 : ["accept", "acceptForSession", "decline"];
  return availableDecisions.map((decision) => mapDecisionOption(decision, params));
}
function mapDecisionOption(decision, params) {
  var _a3;
  if (decision === "accept") {
    return { label: "Allow once", value: "allow-once", decision: "allow" };
  }
  if (decision === "acceptForSession") {
    return { label: "Always allow", value: "allow-always", decision: "allow-always" };
  }
  if (decision === "decline") {
    return { label: "Deny", value: "deny", decision: "deny" };
  }
  if (decision === "cancel") {
    return { label: "Cancel", value: "cancel", decision: "cancel" };
  }
  if ("acceptWithExecpolicyAmendment" in decision) {
    return {
      label: "Allow similar commands",
      description: "Approve and store an exec policy amendment.",
      value: encodeCommandApprovalDecision(decision)
    };
  }
  const networkPolicyAmendment = decision.applyNetworkPolicyAmendment.network_policy_amendment;
  const host = networkPolicyAmendment.host || ((_a3 = params.networkApprovalContext) == null ? void 0 : _a3.host) || "host";
  const action = networkPolicyAmendment.action === "deny" ? "Deny" : "Allow";
  return {
    label: `${action} ${host} for this session`,
    description: `Apply a ${networkPolicyAmendment.action} rule for ${host}.`,
    value: encodeCommandApprovalDecision(decision)
  };
}
function normalizeAnswers(value) {
  if (Array.isArray(value)) {
    return value.map((item) => typeof item === "string" ? item : String(item)).filter((item) => item.trim().length > 0);
  }
  return [value];
}
function mapCommandApprovalDecision(decision) {
  switch (decision) {
    case "allow":
      return "accept";
    case "allow-always":
      return "acceptForSession";
    case "deny":
      return "decline";
    case "cancel":
      return "cancel";
    default:
      if (typeof decision === "object" && decision !== null && decision.type === "select-option") {
        const decoded = decodeCommandApprovalDecision(decision.value);
        if (decoded) {
          return decoded;
        }
      }
      return "decline";
  }
}
function mapFileChangeApprovalDecision(decision) {
  switch (decision) {
    case "allow":
      return "accept";
    case "allow-always":
      return "acceptForSession";
    case "deny":
      return "decline";
    case "cancel":
      return "cancel";
    default:
      return "decline";
  }
}
function encodeCommandApprovalDecision(decision) {
  return JSON.stringify(decision);
}
function decodeCommandApprovalDecision(value) {
  try {
    return JSON.parse(value);
  } catch (e2) {
    return null;
  }
}

// src/providers/codex/runtime/CodexSessionFileTail.ts
var fs15 = __toESM(require("fs"));
var DEFAULT_CONTEXT_WINDOW2 = 2e5;
function getNonEmptyString(value, fallback) {
  return typeof value === "string" && value.length > 0 ? value : fallback;
}
function isRecord4(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
function stringifyPayloadValue(raw) {
  try {
    const result = JSON.stringify(raw);
    return typeof result === "string" ? result : String(raw);
  } catch (e2) {
    return String(raw);
  }
}
function extractResponseItemMessageText(raw) {
  if (!Array.isArray(raw)) return "";
  return raw.map((part) => isRecord4(part) && typeof part.text === "string" ? part.text : "").join("");
}
function extractTextFromParts(parts) {
  return parts.map((part) => {
    if (typeof part === "string") return part;
    return isRecord4(part) && typeof part.text === "string" ? part.text : "";
  }).join("");
}
function extractResponseItemReasoningText(raw) {
  if (Array.isArray(raw.summary) && raw.summary.length > 0) {
    return extractTextFromParts(raw.summary);
  }
  if (Array.isArray(raw.content) && raw.content.length > 0) {
    return extractTextFromParts(raw.content);
  }
  return typeof raw.text === "string" ? raw.text : "";
}
function createSessionTailState(fallbackContextWindow = DEFAULT_CONTEXT_WINDOW2) {
  return {
    responseItemState: {
      emittedToolUseIds: /* @__PURE__ */ new Set(),
      emittedToolResultIds: /* @__PURE__ */ new Set(),
      knownCalls: /* @__PURE__ */ new Map()
    },
    currentTurnId: null,
    syntheticTurnCounter: 0,
    modelContextWindow: fallbackContextWindow,
    modelContextWindowIsAuthoritative: false,
    lastTextByTurn: /* @__PURE__ */ new Map(),
    lastThinkingByTurn: /* @__PURE__ */ new Map(),
    pendingUsageByTurn: /* @__PURE__ */ new Map(),
    emittedDoneByTurn: /* @__PURE__ */ new Set(),
    emittedUsageByTurn: /* @__PURE__ */ new Set(),
    callEnrichment: /* @__PURE__ */ new Map()
  };
}
function emitDelta(fullText, lastSeenMap, turnId, chunkType) {
  var _a3;
  if (!fullText) return [];
  const lastSeen = (_a3 = lastSeenMap.get(turnId)) != null ? _a3 : "";
  if (fullText.length <= lastSeen.length) return [];
  const delta = fullText.slice(lastSeen.length);
  lastSeenMap.set(turnId, fullText);
  return [{ type: chunkType, content: delta }];
}
function resolveTurnId(state, preferredTurnId) {
  if (preferredTurnId) return preferredTurnId;
  if (state.currentTurnId) return state.currentTurnId;
  const id = `synthetic-turn-${state.syntheticTurnCounter}`;
  state.syntheticTurnCounter += 1;
  return id;
}
var reportedUnhandledSessionEventTypes = /* @__PURE__ */ new Set();
function mapSessionFileEvent(event, sessionId, lineIndex, state) {
  var _a3;
  const eventType = event.type;
  if (eventType === "event_msg") {
    const payload = (_a3 = event.payload) != null ? _a3 : event;
    return mapEventMsgEvent(payload, sessionId, state);
  }
  if (eventType === "response_item") {
    return mapResponseItemEvent(event, sessionId, lineIndex, state);
  }
  if (eventType && !reportedUnhandledSessionEventTypes.has(eventType)) {
    reportedUnhandledSessionEventTypes.add(eventType);
  }
  return [];
}
function mapEventMsgEvent(payload, sessionId, state) {
  const payloadType = payload.type;
  const info = isRecord4(payload.info) ? payload.info : {};
  switch (payloadType) {
    case "task_started": {
      const turnId = getNonEmptyString(
        info.id,
        getNonEmptyString(payload.turn_id, `synthetic-turn-${state.syntheticTurnCounter++}`)
      );
      state.currentTurnId = turnId;
      state.modelContextWindowIsAuthoritative = false;
      if (typeof payload.model_context_window === "number" && payload.model_context_window > 0) {
        state.modelContextWindow = payload.model_context_window;
        state.modelContextWindowIsAuthoritative = true;
      }
      return [];
    }
    case "task_complete": {
      const turnId = resolveTurnId(state, void 0);
      const chunks = [];
      if (!state.emittedUsageByTurn.has(turnId)) {
        const pending = state.pendingUsageByTurn.get(turnId);
        if (pending) {
          const usage = buildUsageInfo2(
            pending.contextTokens,
            pending.contextWindow,
            pending.contextWindowIsAuthoritative
          );
          chunks.push({ type: "usage", usage, sessionId });
          state.emittedUsageByTurn.add(turnId);
        }
      }
      if (!state.emittedDoneByTurn.has(turnId)) {
        chunks.push({ type: "done" });
        state.emittedDoneByTurn.add(turnId);
      }
      return chunks;
    }
    case "turn_aborted": {
      const turnId = resolveTurnId(state, void 0);
      const chunks = [];
      if (!state.emittedDoneByTurn.has(turnId)) {
        chunks.push({ type: "done" });
        state.emittedDoneByTurn.add(turnId);
      }
      return chunks;
    }
    case "user_message":
      return [];
    case "agent_message": {
      const turnId = resolveTurnId(state, void 0);
      const fullText = typeof payload.text === "string" ? payload.text : typeof payload.message === "string" ? payload.message : "";
      return emitDelta(fullText, state.lastTextByTurn, turnId, "text");
    }
    case "agent_reasoning": {
      const turnId = resolveTurnId(state, void 0);
      const fullText = typeof payload.text === "string" ? payload.text : "";
      return emitDelta(fullText, state.lastThinkingByTurn, turnId, "thinking");
    }
    case "token_count": {
      const turnId = resolveTurnId(state, void 0);
      const lastTokenUsage = isRecord4(info.last_token_usage) ? info.last_token_usage : {};
      const inputTokens = typeof lastTokenUsage.input_tokens === "number" ? lastTokenUsage.input_tokens : typeof lastTokenUsage.input === "number" ? lastTokenUsage.input : 0;
      state.pendingUsageByTurn.set(turnId, {
        contextTokens: inputTokens,
        contextWindow: state.modelContextWindow,
        contextWindowIsAuthoritative: state.modelContextWindowIsAuthoritative
      });
      return [];
    }
    case "exec_command_end": {
      const callId = typeof payload.call_id === "string" ? payload.call_id : "";
      if (callId) {
        const exitCode = typeof payload.exit_code === "number" ? payload.exit_code : void 0;
        state.callEnrichment.set(callId, {
          ...state.callEnrichment.get(callId),
          exitCode
        });
      }
      return [];
    }
    case "patch_apply_end": {
      const callId = typeof payload.call_id === "string" ? payload.call_id : "";
      if (callId && typeof payload.success === "boolean" && !payload.success) {
        state.callEnrichment.set(callId, {
          ...state.callEnrichment.get(callId),
          exitCode: 1
        });
      }
      return [];
    }
    case "mcp_tool_call_end": {
      const callId = typeof payload.call_id === "string" ? payload.call_id : "";
      const invocation = isRecord4(payload.invocation) ? payload.invocation : {};
      if (callId && typeof invocation.server === "string" && typeof invocation.tool === "string") {
        state.callEnrichment.set(callId, {
          ...state.callEnrichment.get(callId),
          mcpServer: invocation.server,
          mcpTool: invocation.tool
        });
        const known = state.responseItemState.knownCalls.get(callId);
        if (known) {
          known.toolName = `mcp__${invocation.server}__${invocation.tool}`;
        }
      }
      return [];
    }
    case "web_search_end":
    case "view_image_tool_call":
    case "collab_agent_spawn_end":
    case "collab_waiting_end":
    case "collab_close_end":
      return [];
    default:
      return [];
  }
}
function mapResponseItemEvent(event, sessionId, lineIndex, state) {
  var _a3, _b2, _c;
  const payload = isRecord4(event.payload) ? event.payload : {};
  const payloadType = payload.type;
  const riState = state.responseItemState;
  switch (payloadType) {
    case "message": {
      if (payload.role !== "assistant") return [];
      const turnId = resolveTurnId(state, void 0);
      const fullText = extractResponseItemMessageText(payload.content);
      return emitDelta(fullText, state.lastTextByTurn, turnId, "text");
    }
    case "reasoning": {
      const turnId = resolveTurnId(state, void 0);
      const fullText = extractResponseItemReasoningText(payload);
      return emitDelta(fullText, state.lastThinkingByTurn, turnId, "thinking");
    }
    case "function_call":
    case "custom_tool_call": {
      const callId = getNonEmptyString(payload.call_id, `tail-call-${lineIndex}`);
      if (riState.emittedToolUseIds.has(callId)) return [];
      riState.emittedToolUseIds.add(callId);
      const rawName = typeof payload.name === "string" ? payload.name : void 0;
      const rawArgs = typeof payload.arguments === "string" ? payload.arguments : typeof payload.input === "string" ? payload.input : void 0;
      const parsedArgs = parseCodexArguments(rawArgs);
      const enrichment = state.callEnrichment.get(callId);
      const normalizedName = (enrichment == null ? void 0 : enrichment.mcpServer) && (enrichment == null ? void 0 : enrichment.mcpTool) ? `mcp__${enrichment.mcpServer}__${enrichment.mcpTool}` : normalizeCodexToolName(rawName);
      const normalizedInput = normalizeCodexToolInput(rawName, parsedArgs);
      riState.knownCalls.set(callId, { toolName: normalizedName, toolInput: normalizedInput });
      return [{
        type: "tool_use",
        id: callId,
        name: normalizedName,
        input: normalizedInput
      }];
    }
    case "web_search_call": {
      const callId = getNonEmptyString(payload.call_id, `tail-ws-${lineIndex}`);
      if (riState.emittedToolUseIds.has(callId)) return [];
      riState.emittedToolUseIds.add(callId);
      const input = normalizeCodexToolInput("web_search_call", {
        action: (_a3 = payload.action) != null ? _a3 : {}
      });
      riState.knownCalls.set(callId, { toolName: "WebSearch", toolInput: input });
      const chunks = [{
        type: "tool_use",
        id: callId,
        name: "WebSearch",
        input
      }];
      if (payload.status) {
        riState.emittedToolResultIds.add(callId);
        chunks.push({
          type: "tool_result",
          id: callId,
          content: "Search complete",
          isError: payload.status === "failed" || payload.status === "error"
        });
      }
      return chunks;
    }
    case "mcp_tool_call": {
      const callId = getNonEmptyString(payload.call_id, `tail-mcp-${lineIndex}`);
      const normalizedName = normalizeCodexMcpToolName(payload.server, payload.tool);
      const normalizedInput = normalizeCodexMcpToolInput(payload.arguments);
      const normalizedState = normalizeCodexMcpToolState(payload.status, payload.result, payload.error);
      const chunks = [];
      riState.knownCalls.set(callId, { toolName: normalizedName, toolInput: normalizedInput });
      if (!riState.emittedToolUseIds.has(callId)) {
        riState.emittedToolUseIds.add(callId);
        chunks.push({
          type: "tool_use",
          id: callId,
          name: normalizedName,
          input: normalizedInput
        });
      }
      if (normalizedState.isTerminal && !riState.emittedToolResultIds.has(callId)) {
        riState.emittedToolResultIds.add(callId);
        chunks.push({
          type: "tool_result",
          id: callId,
          content: (_b2 = normalizedState.result) != null ? _b2 : normalizedState.isError ? "Failed" : "Completed",
          isError: normalizedState.isError
        });
      }
      return chunks;
    }
    case "function_call_output":
    case "custom_tool_call_output": {
      const callId = getNonEmptyString(payload.call_id, `tail-out-${lineIndex}`);
      if (riState.emittedToolResultIds.has(callId)) return [];
      riState.emittedToolResultIds.add(callId);
      const known = riState.knownCalls.get(callId);
      const normalizedName = (_c = known == null ? void 0 : known.toolName) != null ? _c : "tool";
      const enrichment = state.callEnrichment.get(callId);
      if (Array.isArray(payload.output)) {
        const imagePath = (known == null ? void 0 : known.toolInput) && typeof known.toolInput.file_path === "string" ? known.toolInput.file_path : "Image loaded";
        return [{
          type: "tool_result",
          id: callId,
          content: imagePath,
          isError: false
        }];
      }
      const rawOutput = typeof payload.output === "string" ? payload.output : stringifyPayloadValue(payload.output);
      const content = normalizeCodexToolResult(normalizedName, rawOutput);
      const isError = (enrichment == null ? void 0 : enrichment.exitCode) !== void 0 ? enrichment.exitCode !== 0 : isCodexToolOutputError(rawOutput);
      return [{
        type: "tool_result",
        id: callId,
        content,
        isError
      }];
    }
    default:
      return [];
  }
}
function buildUsageInfo2(contextTokens, contextWindow, contextWindowIsAuthoritative) {
  return {
    inputTokens: contextTokens,
    cacheCreationInputTokens: 0,
    cacheReadInputTokens: 0,
    contextWindow,
    contextWindowIsAuthoritative,
    contextTokens,
    percentage: contextWindow > 0 ? Math.min(100, Math.max(0, Math.round(contextTokens / contextWindow * 100))) : 0
  };
}
function sleep(ms) {
  return new Promise((resolve8) => setTimeout(resolve8, ms));
}
var CodexFileTailEngine = class {
  constructor(sessionsDir, defaultContextWindow) {
    this.sessionsDir = sessionsDir;
    this.defaultContextWindow = defaultContextWindow;
    this.tailSessionFile = null;
    this.tailLineCursor = 0;
    this.pendingEvents = [];
    this.pollingActive = false;
    this.pollPromise = null;
    this.pollingError = null;
    this.lastEventAt = 0;
    this.lastPollAt = 0;
    this.consecutiveReadFailures = 0;
    this._turnCompleteEmitted = false;
    this._usageEmitted = false;
    this.tailState = createSessionTailState(defaultContextWindow);
  }
  get turnCompleteEmitted() {
    return this._turnCompleteEmitted;
  }
  get usageEmitted() {
    return this._usageEmitted;
  }
  async primeCursor(sessionId, sessionFilePath) {
    const filePath = this.findSessionFile(sessionId, sessionFilePath);
    if (!filePath) return false;
    const lines = this.readFileLines(filePath);
    this.tailLineCursor = lines.length;
    return true;
  }
  startPolling(sessionId, sessionFilePath) {
    const filePath = this.findSessionFile(sessionId, sessionFilePath);
    if (!filePath) {
      return false;
    }
    this.tailSessionFile = filePath;
    this.pollingActive = true;
    this.pollingError = null;
    this.pollPromise = this.pollLoop(sessionId);
    return true;
  }
  async stopPolling() {
    this.pollingActive = false;
    if (this.pollPromise) {
      await this.pollPromise;
      this.pollPromise = null;
    }
  }
  async waitForSettle() {
    const maxWait = 2500;
    const checkInterval = 80;
    const idleThreshold = 500;
    const pollRecencyThreshold = 250;
    const start = Date.now();
    while (Date.now() - start < maxWait) {
      const now = Date.now();
      const idle = this.lastEventAt > 0 ? now - this.lastEventAt : now - start;
      const pollRecent = this.lastPollAt > 0 && now - this.lastPollAt < pollRecencyThreshold;
      if (idle >= idleThreshold && pollRecent) {
        return;
      }
      await sleep(checkInterval);
    }
  }
  collectPendingEvents() {
    const events = this.pendingEvents;
    this.pendingEvents = [];
    return events;
  }
  consumePollingError() {
    const error48 = this.pollingError;
    this.pollingError = null;
    return error48;
  }
  resetForNewTurn() {
    this.tailState = createSessionTailState(this.defaultContextWindow);
    this.pendingEvents = [];
    this._turnCompleteEmitted = false;
    this._usageEmitted = false;
    this.pollingError = null;
    this.lastEventAt = 0;
    this.lastPollAt = 0;
    this.consecutiveReadFailures = 0;
  }
  // -----------------------------------------------------------------------
  // Private
  // -----------------------------------------------------------------------
  async pollLoop(sessionId) {
    try {
      while (this.pollingActive) {
        const events = this.drainSessionFileEvents(sessionId);
        if (events.length > 0) {
          this.pendingEvents.push(...events);
          this.lastEventAt = Date.now();
          this.trackTailFlags(events);
        }
        this.lastPollAt = Date.now();
        await sleep(100);
      }
      const finalEvents = this.drainSessionFileEvents(sessionId);
      if (finalEvents.length > 0) {
        this.pendingEvents.push(...finalEvents);
        this.trackTailFlags(finalEvents);
      }
    } catch (error48) {
      this.pollingError = error48 instanceof Error ? error48 : new Error(String(error48));
      this.pollingActive = false;
    } finally {
      this.lastPollAt = Date.now();
    }
  }
  drainSessionFileEvents(sessionId) {
    if (!sessionId) return [];
    const filePath = this.findSessionFile(sessionId);
    if (!filePath) return [];
    let lines;
    try {
      lines = this.readFileLines(filePath);
      this.consecutiveReadFailures = 0;
    } catch (e2) {
      this.consecutiveReadFailures += 1;
      if (this.consecutiveReadFailures >= 5) {
        throw new Error(`CodexFileTailEngine: 5 consecutive read failures for ${filePath}`);
      }
      return [];
    }
    if (this.tailLineCursor > lines.length) {
      this.tailLineCursor = 0;
    }
    if (this.tailLineCursor >= lines.length) return [];
    const newLines = lines.slice(this.tailLineCursor);
    const startIndex = this.tailLineCursor;
    this.tailLineCursor = lines.length;
    const chunks = [];
    for (let i2 = 0; i2 < newLines.length; i2++) {
      const line = newLines[i2];
      if (!line.trim()) continue;
      let parsed;
      try {
        parsed = JSON.parse(line);
      } catch (e2) {
        continue;
      }
      const mapped = mapSessionFileEvent(parsed, sessionId, startIndex + i2, this.tailState);
      chunks.push(...mapped);
    }
    return chunks;
  }
  findSessionFile(sessionId, sessionFilePath) {
    if (sessionFilePath && fs15.existsSync(sessionFilePath)) {
      this.tailSessionFile = sessionFilePath;
      return sessionFilePath;
    }
    if (this.tailSessionFile) {
      try {
        if (fs15.existsSync(this.tailSessionFile)) {
          return this.tailSessionFile;
        }
      } catch (e2) {
      }
      this.tailSessionFile = null;
    }
    const filePath = findCodexSessionFile(sessionId, this.sessionsDir);
    if (filePath) {
      this.tailSessionFile = filePath;
    }
    return filePath;
  }
  readFileLines(filePath) {
    const content = fs15.readFileSync(filePath, "utf-8");
    return content.split("\n").filter((line) => line.trim());
  }
  trackTailFlags(events) {
    for (const event of events) {
      if (event.type === "done") {
        this._turnCompleteEmitted = true;
      }
      if (event.type === "usage") {
        this._usageEmitted = true;
      }
    }
  }
};

// src/providers/codex/runtime/CodexSessionManager.ts
var CodexSessionManager = class {
  constructor() {
    this.threadId = null;
    this.sessionFilePath = null;
    this.sessionInvalidated = false;
  }
  getThreadId() {
    return this.threadId;
  }
  getSessionFilePath() {
    return this.sessionFilePath;
  }
  setThread(threadId, sessionFilePath) {
    const threadChanged = this.threadId !== threadId;
    this.threadId = threadId;
    if (sessionFilePath) {
      this.sessionFilePath = sessionFilePath;
    } else if (threadChanged) {
      this.sessionFilePath = null;
    }
  }
  reset() {
    this.threadId = null;
    this.sessionFilePath = null;
    this.sessionInvalidated = false;
  }
  invalidateSession() {
    this.sessionInvalidated = true;
  }
  consumeInvalidation() {
    const was = this.sessionInvalidated;
    this.sessionInvalidated = false;
    return was;
  }
};

// src/providers/codex/runtime/CodexChatRuntime.ts
function resolveCodexSandboxConfig(permissionMode, codexSafeMode = "workspace-write") {
  if (permissionMode === "yolo") {
    return { approvalPolicy: "never", sandbox: "danger-full-access" };
  }
  if (permissionMode === "plan") {
    return { approvalPolicy: "on-request", sandbox: "workspace-write" };
  }
  return { approvalPolicy: "on-request", sandbox: codexSafeMode };
}
function resolveCodexServiceTier(serviceTier, model) {
  if (model !== FAST_TIER_CODEX_MODEL) {
    return null;
  }
  return serviceTier === "fast" ? "fast" : null;
}
var EFFORT_MAP = {
  low: "low",
  medium: "medium",
  high: "high",
  xhigh: "xhigh"
};
var CodexChatRuntime = class {
  constructor(plugin) {
    this.providerId = "codex";
    this.session = new CodexSessionManager();
    this.process = null;
    this.transport = null;
    this.launchSpec = null;
    this.runtimeContext = null;
    this.notificationRouter = null;
    this.serverRequestRouter = new CodexServerRequestRouter();
    this.ready = false;
    this.readyListeners = /* @__PURE__ */ new Set();
    this.clientConfigKey = null;
    this.currentTurnId = null;
    this.currentQueryThreadId = null;
    this.loadedThreadId = null;
    this.currentThreadPath = null;
    this.pendingTurnNotifications = [];
    // Chunk buffer: notifications push here, query() drains
    this.chunkBuffer = [];
    this.chunkResolve = null;
    this.approvalCallback = null;
    this.approvalDismisser = null;
    this.askUserCallback = null;
    this.exitPlanModeCallback = null;
    this.permissionModeSyncCallback = null;
    this.subagentHookProvider = null;
    this.autoTurnCallback = null;
    this.activeInputBundles = /* @__PURE__ */ new Set();
    // Fork state
    this.pendingFork = null;
    // Cancellation
    this.canceled = false;
    this.turnMetadata = {};
    this.plugin = plugin;
  }
  getCapabilities() {
    return CODEX_PROVIDER_CAPABILITIES;
  }
  prepareTurn(request) {
    return encodeCodexTurn(request);
  }
  consumeTurnMetadata() {
    const metadata = { ...this.turnMetadata };
    this.turnMetadata = {};
    return metadata;
  }
  onReadyStateChange(listener) {
    this.readyListeners.add(listener);
    return () => {
      this.readyListeners.delete(listener);
    };
  }
  setResumeCheckpoint(checkpointId) {
    this.resumeCheckpoint = checkpointId;
  }
  syncConversationState(conversation, _externalContextPaths) {
    var _a3, _b2;
    if (!conversation) {
      this.session.reset();
      this.loadedThreadId = null;
      this.currentThreadPath = null;
      this.pendingFork = null;
      return;
    }
    const state = getCodexState(conversation.providerState);
    if (state.forkSource && !state.threadId && !conversation.sessionId) {
      this.pendingFork = state.forkSource;
      this.session.reset();
      this.loadedThreadId = null;
      this.currentThreadPath = null;
      return;
    }
    this.pendingFork = null;
    const threadId = (_b2 = (_a3 = state.threadId) != null ? _a3 : conversation.sessionId) != null ? _b2 : null;
    if (!threadId) {
      this.session.reset();
      this.loadedThreadId = null;
      this.currentThreadPath = null;
      return;
    }
    this.session.setThread(threadId, state.sessionFilePath);
  }
  async reloadMcpServers() {
  }
  async ensureReady(options) {
    const promptSettings = this.getSystemPromptSettings();
    const promptKey = computeSystemPromptKey(promptSettings);
    const launchSpec = resolveCodexAppServerLaunchSpec(this.plugin, this.providerId);
    const clientConfigKey = [promptKey, JSON.stringify({
      command: launchSpec.command,
      args: launchSpec.args,
      spawnCwd: launchSpec.spawnCwd,
      targetCwd: launchSpec.targetCwd,
      target: launchSpec.target
    })].join("::");
    const shouldRebuild = !this.process || !this.transport || !this.process.isAlive() || (options == null ? void 0 : options.force) === true || this.clientConfigKey !== clientConfigKey;
    if (shouldRebuild) {
      await this.shutdownProcess();
      await this.startAppServer(launchSpec, clientConfigKey);
    }
    this.setReady(true);
    return shouldRebuild;
  }
  async *query(originalTurn, _conversationHistory, queryOptions) {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l, _m, _n, _o, _p2, _q, _r, _s;
    this.resetTurnMetadata();
    let turn = originalTurn;
    await this.ensureReady();
    this.canceled = false;
    this.cleanupActiveInputBundles();
    this.chunkBuffer = [];
    this.chunkResolve = null;
    this.currentQueryThreadId = null;
    this.pendingTurnNotifications = [];
    let tailEngine = null;
    let tailDrainInterval = null;
    let toolSourceMode = "fallback";
    let tailDonePromise = null;
    let transcriptSessionFilePath;
    const model = this.resolveModel(queryOptions);
    const promptSettings = this.getSystemPromptSettings();
    const promptText = buildSystemPrompt(promptSettings);
    const enqueueChunk = (chunk) => {
      this.chunkBuffer.push(chunk);
      if (this.chunkResolve) {
        this.chunkResolve();
        this.chunkResolve = null;
      }
    };
    const switchToLiveToolFallback = () => {
      if (toolSourceMode === "fallback") {
        return;
      }
      toolSourceMode = "fallback";
      if (tailDrainInterval) {
        clearInterval(tailDrainInterval);
        tailDrainInterval = null;
      }
      if (tailEngine) {
        void tailEngine.stopPolling().catch(() => {
        });
      }
    };
    const syncTailPollingState = () => {
      if (!tailEngine) return null;
      const tailError = tailEngine.consumePollingError();
      if (tailError) {
        switchToLiveToolFallback();
        return tailError;
      }
      return null;
    };
    const drainTailToolChunks = () => {
      if (!tailEngine) return;
      if (toolSourceMode !== "transcript") return;
      if (syncTailPollingState()) return;
      const toolChunks = tailEngine.collectPendingEvents().filter(
        (chunk) => chunk.type === "tool_use" || chunk.type === "tool_result"
      );
      for (const chunk of toolChunks) {
        enqueueChunk(chunk);
      }
    };
    const stopTailToolPolling = async () => {
      if (tailDrainInterval) {
        clearInterval(tailDrainInterval);
        tailDrainInterval = null;
      }
      if (tailEngine) {
        await tailEngine.stopPolling();
      }
    };
    const flushTailToolsBeforeDone = () => {
      if (toolSourceMode !== "transcript" || !tailEngine) {
        enqueueChunk({ type: "done" });
        return;
      }
      if (tailDonePromise) {
        return;
      }
      tailDonePromise = (async () => {
        try {
          await tailEngine.waitForSettle();
          if (syncTailPollingState()) {
            return;
          }
          drainTailToolChunks();
        } finally {
          await stopTailToolPolling();
          enqueueChunk({ type: "done" });
        }
      })();
    };
    this.notificationRouter = new CodexNotificationRouter(
      (chunk) => {
        syncTailPollingState();
        if (toolSourceMode === "transcript") {
          if (chunk.type === "tool_use" || chunk.type === "tool_result") {
            return;
          }
          if (chunk.type === "done") {
            flushTailToolsBeforeDone();
            return;
          }
        }
        enqueueChunk(chunk);
      },
      (update) => this.recordTurnMetadata(update)
    );
    this.wireTransportHandlers();
    const compactValidationError = this.validateCompactTurn(originalTurn);
    if (compactValidationError) {
      yield { type: "error", content: compactValidationError };
      yield { type: "done" };
      return;
    }
    try {
      const existingThreadId = this.session.getThreadId();
      let threadId;
      let threadPath = null;
      let threadTargetPath = null;
      let completedPendingFork = false;
      if (this.pendingFork) {
        const fork = this.pendingFork;
        const forkResult = await this.transport.request("thread/fork", {
          threadId: fork.sessionId
        });
        threadId = forkResult.thread.id;
        threadTargetPath = (_a3 = forkResult.thread.path) != null ? _a3 : null;
        threadPath = this.toHostSessionPath(threadTargetPath);
        const forkTurns = (_b2 = forkResult.thread.turns) != null ? _b2 : [];
        const checkpointIndex = forkTurns.findIndex((t2) => t2.id === fork.resumeAt);
        if (checkpointIndex < 0) {
          throw new Error(`Fork checkpoint not found: ${fork.resumeAt}`);
        }
        const numTurnsToRollback = forkTurns.length - checkpointIndex - 1;
        const permissionMode = this.resolveSandboxConfig();
        await this.transport.request("thread/resume", {
          threadId,
          model: model != null ? model : DEFAULT_CODEX_PRIMARY_MODEL,
          approvalPolicy: permissionMode.approvalPolicy,
          sandbox: permissionMode.sandbox,
          serviceTier: resolveCodexServiceTier(this.getProviderSettings().serviceTier, model != null ? model : DEFAULT_CODEX_PRIMARY_MODEL),
          baseInstructions: promptText,
          persistExtendedHistory: true
        });
        if (numTurnsToRollback > 0) {
          await this.transport.request("thread/rollback", {
            threadId,
            numTurns: numTurnsToRollback
          });
        }
        this.loadedThreadId = threadId;
        completedPendingFork = true;
        if (_conversationHistory && _conversationHistory.length > 0) {
          const checkpointIdx = _conversationHistory.findIndex(
            (m2) => m2.assistantMessageId === fork.resumeAt
          );
          if (checkpointIdx >= 0 && checkpointIdx < _conversationHistory.length - 1) {
            const suffix = _conversationHistory.slice(checkpointIdx + 1);
            const replayContext = buildContextFromHistory(suffix);
            if (replayContext.trim()) {
              turn = {
                ...turn,
                prompt: `${replayContext}

User: ${turn.prompt}`
              };
            }
          }
        }
      } else if (existingThreadId && existingThreadId !== this.loadedThreadId) {
        const permissionMode = this.resolveSandboxConfig();
        const resumeResult = await this.transport.request("thread/resume", {
          threadId: existingThreadId,
          model: model != null ? model : DEFAULT_CODEX_PRIMARY_MODEL,
          approvalPolicy: permissionMode.approvalPolicy,
          sandbox: permissionMode.sandbox,
          serviceTier: resolveCodexServiceTier(this.getProviderSettings().serviceTier, model != null ? model : DEFAULT_CODEX_PRIMARY_MODEL),
          baseInstructions: promptText,
          persistExtendedHistory: true
        });
        threadId = resumeResult.thread.id;
        threadTargetPath = (_c = resumeResult.thread.path) != null ? _c : null;
        threadPath = this.toHostSessionPath(threadTargetPath);
        this.loadedThreadId = threadId;
      } else if (existingThreadId && existingThreadId === this.loadedThreadId) {
        threadId = existingThreadId;
      } else {
        const permissionMode = this.resolveSandboxConfig();
        const startResult = await this.transport.request("thread/start", {
          model: model != null ? model : DEFAULT_CODEX_PRIMARY_MODEL,
          cwd: (_f = (_e = (_d2 = this.launchSpec) == null ? void 0 : _d2.targetCwd) != null ? _e : getVaultPath(this.plugin.app)) != null ? _f : void 0,
          approvalPolicy: permissionMode.approvalPolicy,
          sandbox: permissionMode.sandbox,
          serviceTier: resolveCodexServiceTier(this.getProviderSettings().serviceTier, model != null ? model : DEFAULT_CODEX_PRIMARY_MODEL),
          baseInstructions: promptText,
          experimentalRawEvents: false,
          persistExtendedHistory: true
        });
        threadId = startResult.thread.id;
        threadTargetPath = (_g = startResult.thread.path) != null ? _g : null;
        threadPath = this.toHostSessionPath(threadTargetPath);
        this.loadedThreadId = threadId;
      }
      this.session.setThread(threadId, (_h = threadPath != null ? threadPath : this.currentThreadPath) != null ? _h : void 0);
      if (threadPath) this.currentThreadPath = threadPath;
      this.currentQueryThreadId = threadId;
      if (completedPendingFork) {
        this.pendingFork = null;
      }
      if (turn.isCompact) {
        (_i = this.notificationRouter) == null ? void 0 : _i.beginTurn({ isPlanTurn: false });
        await this.transport.request(
          "thread/compact/start",
          { threadId }
        );
        this.recordTurnMetadata({ wasSent: true });
      } else {
        tailEngine = new CodexFileTailEngine(
          (_j2 = this.resolveTranscriptRootHost(threadPath)) != null ? _j2 : path15.join(os10.homedir(), ".codex", "sessions"),
          2e5
        );
        tailEngine.resetForNewTurn();
        transcriptSessionFilePath = (_k = threadPath != null ? threadPath : this.session.getSessionFilePath()) != null ? _k : null;
        const transcriptReady = await tailEngine.primeCursor(
          threadId,
          transcriptSessionFilePath != null ? transcriptSessionFilePath : void 0
        );
        if (transcriptReady) {
          toolSourceMode = "transcript";
        }
        const skillInputs = await this.resolveSkillInputs(turn.request.text);
        const turnInputBundle = this.buildInput(turn.prompt, turn.request.images, skillInputs);
        this.registerActiveInputBundle(turnInputBundle);
        const providerSettings = this.getProviderSettings();
        const effort = (_l = EFFORT_MAP[providerSettings.effortLevel]) != null ? _l : "medium";
        const resolvedModel = model != null ? model : DEFAULT_CODEX_PRIMARY_MODEL;
        const isPlanMode = providerSettings.permissionMode === "plan";
        const externalContextPaths = this.resolveExternalContextPaths(turn, queryOptions);
        const permissionMode = this.resolveSandboxConfig();
        const transcriptRootTarget = (_o = (_n = (_m = this.runtimeContext) == null ? void 0 : _m.sessionsDirTarget) != null ? _n : deriveCodexSessionsRootFromSessionPath(threadTargetPath)) != null ? _o : this.resolveTranscriptRootTarget(threadPath != null ? threadPath : transcriptSessionFilePath);
        const sandboxPolicy = this.buildTurnSandboxPolicy(
          externalContextPaths,
          permissionMode.sandbox,
          transcriptRootTarget,
          threadPath != null ? threadPath : transcriptSessionFilePath
        );
        const collaborationMode = isPlanMode ? {
          mode: "plan",
          settings: {
            model: resolvedModel,
            reasoning_effort: effort,
            developer_instructions: null
          }
        } : void 0;
        const summary = getEffectiveCodexReasoningSummary(providerSettings, resolvedModel);
        const serviceTier = resolveCodexServiceTier(providerSettings.serviceTier, resolvedModel);
        (_p2 = this.notificationRouter) == null ? void 0 : _p2.beginTurn({ isPlanTurn: isPlanMode });
        const turnResult = await this.transport.request("turn/start", {
          threadId,
          input: turnInputBundle.input,
          approvalPolicy: permissionMode.approvalPolicy,
          model: resolvedModel,
          serviceTier,
          effort,
          summary,
          sandboxPolicy,
          ...collaborationMode ? { collaborationMode } : {}
        });
        this.currentTurnId = turnResult.turn.id;
        this.recordTurnMetadata({
          userMessageId: turnResult.turn.id,
          wasSent: true
        });
        this.flushPendingTurnNotifications();
        if (toolSourceMode === "transcript" && tailEngine) {
          const transcriptPollingStarted = tailEngine.startPolling(
            threadId,
            transcriptSessionFilePath != null ? transcriptSessionFilePath : void 0
          );
          if (transcriptPollingStarted) {
            tailDrainInterval = setInterval(() => {
              drainTailToolChunks();
            }, 50);
          } else {
            switchToLiveToolFallback();
          }
        }
      }
      while (true) {
        if (this.canceled) {
          while (this.chunkBuffer.length > 0) {
            const chunk = this.chunkBuffer.shift();
            yield chunk;
            if (chunk.type === "done") return;
          }
          yield { type: "done" };
          return;
        }
        if (this.chunkBuffer.length === 0) {
          await new Promise((resolve8) => {
            this.chunkResolve = resolve8;
            if (this.chunkBuffer.length > 0 || this.canceled) {
              resolve8();
              this.chunkResolve = null;
            }
          });
        }
        while (this.chunkBuffer.length > 0) {
          const chunk = this.chunkBuffer.shift();
          yield chunk;
          if (chunk.type === "done") {
            return;
          }
        }
      }
    } catch (err) {
      if (this.canceled) {
        yield { type: "done" };
        return;
      }
      const message = err instanceof Error ? err.message : "Unknown Codex error";
      yield { type: "error", content: message };
      yield { type: "done" };
      return;
    } finally {
      (_q = this.notificationRouter) == null ? void 0 : _q.endTurn();
      if (!tailDonePromise) {
        await stopTailToolPolling().catch(() => {
        });
      }
      this.cleanupActiveInputBundles();
      this.currentTurnId = null;
      this.currentQueryThreadId = null;
      this.pendingTurnNotifications = [];
      if (!this.session.getSessionFilePath()) {
        const threadId = this.session.getThreadId();
        if (threadId) {
          const sessionFilePath = findCodexSessionFile(
            threadId,
            (_s = this.resolveTranscriptRootHost((_r = this.session.getSessionFilePath()) != null ? _r : this.currentThreadPath)) != null ? _s : void 0
          );
          if (sessionFilePath) {
            this.session.setThread(threadId, sessionFilePath);
          }
        }
      }
    }
  }
  async steer(turn) {
    if (turn.isCompact || this.canceled) {
      return false;
    }
    const transport = this.transport;
    const threadId = this.currentQueryThreadId;
    const turnId = this.currentTurnId;
    if (!transport || !threadId || !turnId) {
      return false;
    }
    const skillInputs = await this.resolveSkillInputs(turn.request.text);
    const inputBundle = this.buildInput(turn.prompt, turn.request.images, skillInputs);
    this.registerActiveInputBundle(inputBundle);
    try {
      const result = await transport.request("turn/steer", {
        threadId,
        input: inputBundle.input,
        expectedTurnId: turnId
      });
      if (result.turnId !== turnId) {
        return false;
      }
      return this.currentQueryThreadId === threadId && this.currentTurnId === turnId && !this.canceled;
    } catch (error48) {
      this.disposeInputBundle(inputBundle);
      throw error48;
    }
  }
  cancel() {
    this.canceled = true;
    this.dismissAllPendingPrompts();
    const threadId = this.session.getThreadId();
    const turnId = this.currentTurnId;
    if (this.transport && threadId && turnId) {
      this.transport.request("turn/interrupt", { threadId, turnId }).catch(() => {
      });
    }
    if (this.chunkResolve) {
      this.chunkResolve();
      this.chunkResolve = null;
    }
  }
  resetSession() {
    this.teardownState();
  }
  getSessionId() {
    return this.session.getThreadId();
  }
  consumeSessionInvalidation() {
    return this.session.consumeInvalidation();
  }
  isReady() {
    return this.ready;
  }
  resetTurnMetadata() {
    this.turnMetadata = {};
  }
  recordTurnMetadata(update) {
    this.turnMetadata = {
      ...this.turnMetadata,
      ...update
    };
  }
  async getSupportedCommands() {
    return [];
  }
  cleanup() {
    this.cancel();
    this.teardownState();
    this.readyListeners.clear();
  }
  async rewind(_userMessageId, _assistantMessageId) {
    return { canRewind: false, error: "Codex does not support rewind" };
  }
  setApprovalCallback(callback) {
    this.approvalCallback = callback;
    this.serverRequestRouter.setApprovalCallback(callback);
  }
  setApprovalDismisser(dismisser) {
    this.approvalDismisser = dismisser;
  }
  setAskUserQuestionCallback(callback) {
    this.askUserCallback = callback;
    this.serverRequestRouter.setAskUserCallback(callback);
  }
  setExitPlanModeCallback(callback) {
    this.exitPlanModeCallback = callback;
  }
  setPermissionModeSyncCallback(callback) {
    this.permissionModeSyncCallback = callback;
  }
  setSubagentHookProvider(getState) {
    this.subagentHookProvider = getState;
  }
  setAutoTurnCallback(callback) {
    this.autoTurnCallback = callback;
  }
  buildSessionUpdates(params) {
    var _a3;
    const threadId = this.session.getThreadId();
    const sessionFilePath = (_a3 = this.session.getSessionFilePath()) != null ? _a3 : this.currentThreadPath;
    const transcriptRootPath = this.resolveTranscriptRootHost(sessionFilePath);
    const existingState = params.conversation ? getCodexState(params.conversation.providerState) : null;
    const providerState = {
      ...threadId ? { threadId } : {},
      ...sessionFilePath ? { sessionFilePath } : {},
      ...transcriptRootPath || (existingState == null ? void 0 : existingState.transcriptRootPath) ? { transcriptRootPath: transcriptRootPath != null ? transcriptRootPath : existingState == null ? void 0 : existingState.transcriptRootPath } : {},
      ...(existingState == null ? void 0 : existingState.forkSource) ? { forkSource: existingState.forkSource } : {},
      ...(existingState == null ? void 0 : existingState.forkSourceSessionFilePath) ? { forkSourceSessionFilePath: existingState.forkSourceSessionFilePath } : {},
      ...(existingState == null ? void 0 : existingState.forkSourceTranscriptRootPath) ? { forkSourceTranscriptRootPath: existingState.forkSourceTranscriptRootPath } : {}
    };
    const updates = {
      sessionId: threadId,
      providerState
    };
    if (params.sessionInvalidated && params.conversation) {
      updates.sessionId = null;
      updates.providerState = void 0;
    }
    return { updates };
  }
  resolveSessionIdForFork(conversation) {
    var _a3, _b2, _c, _d2;
    const threadId = this.session.getThreadId();
    if (threadId) return threadId;
    if (!conversation) return null;
    const state = getCodexState(conversation.providerState);
    return (_d2 = (_c = (_a3 = state.threadId) != null ? _a3 : conversation.sessionId) != null ? _c : (_b2 = state.forkSource) == null ? void 0 : _b2.sessionId) != null ? _d2 : null;
  }
  // -----------------------------------------------------------------------
  // Private helpers
  // -----------------------------------------------------------------------
  teardownState() {
    this.cleanupActiveInputBundles();
    this.session.reset();
    this.launchSpec = null;
    this.runtimeContext = null;
    this.loadedThreadId = null;
    this.currentThreadPath = null;
    this.currentTurnId = null;
    this.currentQueryThreadId = null;
    this.pendingTurnNotifications = [];
    this.pendingFork = null;
    this.clientConfigKey = null;
    this.shutdownProcess().catch(() => {
    });
    this.setReady(false);
  }
  dismissApprovalUI() {
    if (this.approvalDismisser) {
      this.approvalDismisser();
    }
  }
  dismissAllPendingPrompts() {
    this.dismissApprovalUI();
    this.serverRequestRouter.abortPendingAskUser();
  }
  registerActiveInputBundle(bundle) {
    this.activeInputBundles.add(bundle);
  }
  disposeInputBundle(bundle) {
    if (this.activeInputBundles.delete(bundle)) {
      bundle.cleanup();
      return;
    }
    bundle.cleanup();
  }
  cleanupActiveInputBundles() {
    for (const bundle of this.activeInputBundles) {
      bundle.cleanup();
    }
    this.activeInputBundles.clear();
  }
  setReady(ready) {
    this.ready = ready;
    for (const listener of this.readyListeners) {
      listener(ready);
    }
  }
  getSystemPromptSettings() {
    var _a3;
    const settings11 = this.plugin.settings;
    return {
      mediaFolder: settings11.mediaFolder,
      customPrompt: settings11.systemPrompt,
      vaultPath: (_a3 = getVaultPath(this.plugin.app)) != null ? _a3 : void 0,
      userName: settings11.userName
    };
  }
  getProviderSettings() {
    return ProviderSettingsCoordinator.getProviderSettingsSnapshot(
      this.plugin.settings,
      this.providerId
    );
  }
  getAuxiliaryModel() {
    var _a3;
    return (_a3 = this.resolveModel()) != null ? _a3 : null;
  }
  resolveModel(queryOptions) {
    var _a3;
    const providerSettings = this.getProviderSettings();
    return (_a3 = queryOptions == null ? void 0 : queryOptions.model) != null ? _a3 : providerSettings.model;
  }
  resolveSandboxConfig() {
    const providerSettings = this.getProviderSettings();
    return resolveCodexSandboxConfig(
      providerSettings.permissionMode,
      getCodexProviderSettings(providerSettings).safeMode
    );
  }
  async startAppServer(launchSpec, clientConfigKey) {
    this.launchSpec = launchSpec;
    this.process = new CodexAppServerProcess(launchSpec);
    this.process.start();
    this.transport = new CodexRpcTransport(this.process);
    this.transport.start();
    const initializeResult = await initializeCodexAppServerTransport(this.transport);
    this.runtimeContext = createCodexRuntimeContext(launchSpec, initializeResult);
    this.clientConfigKey = clientConfigKey;
  }
  wireTransportHandlers() {
    if (!this.transport || !this.notificationRouter) return;
    const router = this.notificationRouter;
    const methods = [
      "item/agentMessage/delta",
      "item/started",
      "item/completed",
      "item/plan/delta",
      "item/reasoning/textDelta",
      "item/reasoning/summaryTextDelta",
      "item/reasoning/summaryPartAdded",
      "thread/tokenUsage/updated",
      "turn/plan/updated",
      "turn/completed",
      "error",
      "thread/started",
      "thread/status/changed",
      "turn/started",
      "serverRequest/resolved",
      "item/commandExecution/outputDelta",
      "item/fileChange/outputDelta"
    ];
    for (const method of methods) {
      this.transport.onNotification(method, (params) => {
        if (method === "serverRequest/resolved") {
          this.handleServerRequestResolved(params);
          return;
        }
        if (!this.routeNotification(method, params)) {
          return;
        }
        router.handleNotification(method, params);
      });
    }
    const requestMethods = [
      "item/commandExecution/requestApproval",
      "item/fileChange/requestApproval",
      "item/permissions/requestApproval",
      "item/tool/requestUserInput"
    ];
    for (const method of requestMethods) {
      this.transport.onServerRequest(method, (requestId, params) => {
        return this.serverRequestRouter.handleServerRequest(requestId, method, params);
      });
    }
  }
  async shutdownProcess() {
    if (this.transport) {
      this.transport.dispose();
      this.transport = null;
    }
    if (this.process) {
      await this.process.shutdown();
      this.process = null;
    }
    this.launchSpec = null;
    this.runtimeContext = null;
    this.notificationRouter = null;
    this.currentTurnId = null;
    this.currentQueryThreadId = null;
    this.pendingTurnNotifications = [];
    this.loadedThreadId = null;
  }
  resolveExternalContextPaths(turn, queryOptions) {
    var _a3, _b2;
    const externalContextPaths = (_b2 = (_a3 = turn.request.externalContextPaths) != null ? _a3 : queryOptions == null ? void 0 : queryOptions.externalContextPaths) != null ? _b2 : [];
    return [...new Set(externalContextPaths.filter((value) => typeof value === "string" && value.trim().length > 0))];
  }
  buildTurnSandboxPolicy(externalContextPaths, sandboxMode, transcriptRootTargetHint, sessionFilePathHint) {
    var _a3, _b2, _c, _d2, _e, _f;
    if (sandboxMode === "danger-full-access") {
      return { type: "dangerFullAccess" };
    }
    if (sandboxMode === "read-only") {
      return {
        type: "readOnly",
        access: { type: "fullAccess" },
        networkAccess: false
      };
    }
    if (sandboxMode !== "workspace-write") {
      return void 0;
    }
    const mappedExternalContextPaths = this.mapRequiredHostPathsToTarget(
      externalContextPaths,
      "external context path"
    );
    const memoriesDirTarget = (_c = (_a3 = deriveCodexMemoriesDirFromSessionsRoot(transcriptRootTargetHint)) != null ? _a3 : this.resolveMemoriesDirTarget(sessionFilePathHint)) != null ? _c : ((_b2 = this.launchSpec) == null ? void 0 : _b2.target.method) === "wsl" ? null : path15.join(os10.homedir(), ".codex", "memories");
    const writableRoots = [
      (_e = (_d2 = this.launchSpec) == null ? void 0 : _d2.targetCwd) != null ? _e : getVaultPath(this.plugin.app),
      ...mappedExternalContextPaths,
      memoriesDirTarget,
      this.mapHostPathToTarget(os10.tmpdir()),
      ((_f = this.launchSpec) == null ? void 0 : _f.target.platformFamily) === "unix" ? "/tmp" : null,
      this.mapHostPathToTarget(process.env.TMPDIR)
    ].filter((value) => typeof value === "string" && value.trim().length > 0);
    return {
      type: "workspaceWrite",
      writableRoots: [...new Set(writableRoots)],
      readOnlyAccess: { type: "fullAccess" },
      networkAccess: false,
      excludeTmpdirEnvVar: false,
      excludeSlashTmp: false
    };
  }
  handleServerRequestResolved(params) {
    if (this.serverRequestRouter.hasPendingApprovalRequest(params.requestId, params.threadId)) {
      this.dismissApprovalUI();
      return;
    }
    this.serverRequestRouter.abortPendingAskUser(params.requestId, params.threadId);
  }
  routeNotification(method, params) {
    if (method === "turn/started") {
      this.handleTurnStartedNotification(params);
      return false;
    }
    const scope = this.extractNotificationScope(method, params);
    if (!scope) {
      return true;
    }
    if (!this.currentQueryThreadId || scope.threadId !== this.currentQueryThreadId) {
      return false;
    }
    if (!this.currentTurnId) {
      this.pendingTurnNotifications.push({ method, params });
      return false;
    }
    if (scope.turnId !== this.currentTurnId) {
      return false;
    }
    return true;
  }
  handleTurnStartedNotification(params) {
    var _a3;
    if (!params || typeof params !== "object") return;
    const notification = params;
    const threadId = notification.threadId;
    const turnId = (_a3 = notification.turn) == null ? void 0 : _a3.id;
    if (!threadId || !turnId) return;
    if (threadId !== this.currentQueryThreadId) return;
    if (!this.currentTurnId) {
      this.currentTurnId = turnId;
      this.flushPendingTurnNotifications();
    }
  }
  validateCompactTurn(turn) {
    if (!turn.isCompact) {
      return null;
    }
    if (turn.request.text.trim() !== "/compact") {
      return "/compact does not accept arguments";
    }
    return null;
  }
  flushPendingTurnNotifications() {
    if (!this.notificationRouter || !this.currentTurnId) {
      this.pendingTurnNotifications = [];
      return;
    }
    const pending = this.pendingTurnNotifications;
    this.pendingTurnNotifications = [];
    for (const notification of pending) {
      const scope = this.extractNotificationScope(notification.method, notification.params);
      if (!scope) {
        this.notificationRouter.handleNotification(notification.method, notification.params);
        continue;
      }
      if (scope.threadId === this.currentQueryThreadId && scope.turnId === this.currentTurnId) {
        this.notificationRouter.handleNotification(notification.method, notification.params);
      }
    }
  }
  extractNotificationScope(method, params) {
    if (!params || typeof params !== "object") {
      return null;
    }
    const notification = params;
    const threadId = typeof notification.threadId === "string" ? notification.threadId : null;
    if (method === "turn/completed") {
      const turn = notification.turn;
      const turnId2 = turn && typeof turn === "object" && typeof turn.id === "string" ? turn.id : null;
      return threadId && turnId2 ? { threadId, turnId: turnId2 } : null;
    }
    const turnId = typeof notification.turnId === "string" ? notification.turnId : null;
    return threadId && turnId ? { threadId, turnId } : null;
  }
  async resolveSkillInputs(text) {
    var _a3, _b2, _c, _d2, _e, _f, _g;
    const skillNames = extractExplicitCodexSkillNames(text);
    if (skillNames.length === 0 || !this.transport) {
      return [];
    }
    try {
      const cwd = (_c = (_b2 = (_a3 = this.launchSpec) == null ? void 0 : _a3.targetCwd) != null ? _b2 : getVaultPath(this.plugin.app)) != null ? _c : process.cwd();
      const result = await this.transport.request("skills/list", {
        cwds: [cwd]
      });
      const skills = (_g = (_f = (_d2 = result.data.find((entry) => entry.cwd === cwd)) == null ? void 0 : _d2.skills) != null ? _f : (_e = result.data[0]) == null ? void 0 : _e.skills) != null ? _g : [];
      const resolvedInputs = [];
      for (const skillName of skillNames) {
        const resolvedSkill = findPreferredCodexSkillByName(skills, skillName);
        if (!resolvedSkill) {
          continue;
        }
        resolvedInputs.push({
          type: "skill",
          name: resolvedSkill.name,
          path: resolvedSkill.path
        });
      }
      return resolvedInputs;
    } catch (e2) {
      return [];
    }
  }
  buildInput(text, images, skills) {
    const input = [];
    let tempDir = null;
    const cleanup = () => {
      if (!tempDir) {
        return;
      }
      try {
        fs16.rmSync(tempDir, { recursive: true, force: true });
      } catch (e2) {
      }
    };
    try {
      if (images && images.length > 0) {
        tempDir = fs16.mkdtempSync(path15.join(os10.tmpdir(), "claudian-codex-images-"));
        for (let i2 = 0; i2 < images.length; i2++) {
          const img = images[i2];
          if (!img.mediaType.startsWith("image/")) continue;
          const filename = toAttachmentFilename(img, i2);
          const filePath = path15.join(tempDir, `${i2 + 1}-${filename}`);
          fs16.writeFileSync(filePath, Buffer.from(img.data, "base64"));
          const targetFilePath = this.mapHostPathToTarget(filePath);
          if (!targetFilePath) {
            throw new Error(`Codex cannot access image attachment path from the selected target: ${filePath}`);
          }
          input.push({ type: "localImage", path: targetFilePath });
        }
      }
      if (text) {
        input.push({ type: "text", text, text_elements: [] });
      }
      if (skills && skills.length > 0) {
        input.push(...skills);
      }
      return { input, cleanup };
    } catch (error48) {
      cleanup();
      throw error48;
    }
  }
  toHostSessionPath(targetPath) {
    var _a3, _b2;
    if (!targetPath) {
      return null;
    }
    return (_b2 = (_a3 = this.launchSpec) == null ? void 0 : _a3.pathMapper.toHostPath(targetPath)) != null ? _b2 : targetPath;
  }
  toTargetSessionPath(sessionPath) {
    var _a3;
    if (!sessionPath) {
      return null;
    }
    if (!this.launchSpec) {
      return sessionPath;
    }
    if (this.launchSpec.target.platformFamily === "unix" && sessionPath.startsWith("/")) {
      return sessionPath;
    }
    if (this.launchSpec.target.platformFamily === "windows" && (/^[A-Za-z]:[\\/]/.test(sessionPath) || sessionPath.startsWith("\\\\"))) {
      return sessionPath;
    }
    return (_a3 = this.launchSpec.pathMapper.toTargetPath(sessionPath)) != null ? _a3 : sessionPath;
  }
  mapHostPathToTarget(hostPath) {
    var _a3, _b2;
    if (!hostPath) {
      return null;
    }
    return (_b2 = (_a3 = this.launchSpec) == null ? void 0 : _a3.pathMapper.toTargetPath(hostPath)) != null ? _b2 : hostPath;
  }
  mapRequiredHostPathsToTarget(hostPaths, label) {
    if (!this.launchSpec) {
      return hostPaths;
    }
    return hostPaths.map((hostPath) => {
      const targetPath = this.launchSpec.pathMapper.toTargetPath(hostPath);
      if (!targetPath) {
        throw new Error(`Codex cannot access ${label} from the selected target: ${hostPath}`);
      }
      return targetPath;
    });
  }
  resolveTranscriptRootHost(sessionFilePath) {
    var _a3, _b2, _c;
    return (_c = (_a3 = this.runtimeContext) == null ? void 0 : _a3.sessionsDirHost) != null ? _c : deriveCodexSessionsRootFromSessionPath(
      (_b2 = sessionFilePath != null ? sessionFilePath : this.session.getSessionFilePath()) != null ? _b2 : this.currentThreadPath
    );
  }
  resolveTranscriptRootTarget(sessionFilePath) {
    var _a3, _b2;
    if ((_a3 = this.runtimeContext) == null ? void 0 : _a3.sessionsDirTarget) {
      return this.runtimeContext.sessionsDirTarget;
    }
    const targetSessionPath = this.toTargetSessionPath(
      (_b2 = sessionFilePath != null ? sessionFilePath : this.session.getSessionFilePath()) != null ? _b2 : this.currentThreadPath
    );
    return deriveCodexSessionsRootFromSessionPath(targetSessionPath);
  }
  resolveMemoriesDirTarget(sessionFilePath) {
    var _a3;
    if ((_a3 = this.runtimeContext) == null ? void 0 : _a3.memoriesDirTarget) {
      return this.runtimeContext.memoriesDirTarget;
    }
    return deriveCodexMemoriesDirFromSessionsRoot(
      this.resolveTranscriptRootTarget(sessionFilePath)
    );
  }
};
function toAttachmentFilename(attachment, index) {
  var _a3, _b2;
  const base = ((_a3 = attachment.filename) != null ? _a3 : "").trim().replace(/[^A-Za-z0-9._-]/g, "_") || `image-${index + 1}`;
  if (base.includes(".")) return base;
  const subtype = (_b2 = attachment.mediaType.split("/")[1]) != null ? _b2 : "img";
  const extension = subtype === "jpeg" ? "jpg" : subtype;
  return `${base}.${extension}`;
}

// src/providers/codex/registration.ts
var codexProviderRegistration = {
  displayName: "Codex",
  blankTabOrder: 15,
  isEnabled: (settings11) => getCodexProviderSettings(settings11).enabled,
  capabilities: CODEX_PROVIDER_CAPABILITIES,
  environmentKeyPatterns: [/^OPENAI_/i, /^CODEX_/i],
  chatUIConfig: codexChatUIConfig,
  settingsReconciler: codexSettingsReconciler,
  createRuntime: ({ plugin }) => new CodexChatRuntime(plugin),
  createTitleGenerationService: (plugin) => new CodexTitleGenerationService(plugin),
  createInstructionRefineService: (plugin) => new CodexInstructionRefineService(plugin),
  createInlineEditService: (plugin) => new CodexInlineEditService(plugin),
  historyService: new CodexConversationHistoryService(),
  taskResultInterpreter: new CodexTaskResultInterpreter(),
  subagentLifecycleAdapter: codexSubagentLifecycleAdapter
};

// src/providers/opencode/agents/OpencodeAgentMentionProvider.ts
var OpencodeAgentMentionProvider = class {
  constructor(storage) {
    this.storage = storage;
    this.agents = [];
  }
  async loadAgents() {
    this.agents = await this.storage.loadAll();
  }
  searchAgents(query) {
    const q10 = query.toLowerCase();
    return this.agents.filter((agent) => isMentionableSubagent(agent)).filter((agent) => agent.name.toLowerCase().includes(q10) || agent.description.toLowerCase().includes(q10)).map((agent) => ({
      id: agent.name,
      name: agent.name,
      description: agent.description,
      source: "vault"
    }));
  }
};
function isMentionableSubagent(agent) {
  if (agent.hidden || agent.disable) {
    return false;
  }
  return agent.mode === "subagent";
}

// src/providers/opencode/commands/OpencodeCommandCatalog.ts
function slashCommandToEntry2(command) {
  var _a3;
  return {
    id: command.id,
    providerId: "opencode",
    kind: "command",
    name: command.name,
    description: command.description,
    content: command.content,
    argumentHint: command.argumentHint,
    allowedTools: command.allowedTools,
    model: command.model,
    disableModelInvocation: command.disableModelInvocation,
    userInvocable: command.userInvocable,
    context: command.context,
    agent: command.agent,
    hooks: command.hooks,
    scope: "runtime",
    source: (_a3 = command.source) != null ? _a3 : "sdk",
    isEditable: false,
    isDeletable: false,
    displayPrefix: "/",
    insertPrefix: "/"
  };
}
function dedupeRuntimeCommands(commands) {
  const deduped = [];
  const seen = /* @__PURE__ */ new Set();
  for (const command of commands) {
    const normalizedName = command.name.trim().replace(/^\/+/, "");
    if (!normalizedName) {
      continue;
    }
    const key = normalizedName.toLowerCase();
    if (seen.has(key)) {
      continue;
    }
    seen.add(key);
    deduped.push({
      ...command,
      name: normalizedName
    });
  }
  return deduped;
}
var OpencodeCommandCatalog = class {
  constructor() {
    this.runtimeCommands = [];
  }
  setRuntimeCommands(commands) {
    this.runtimeCommands = dedupeRuntimeCommands(commands);
  }
  async listDropdownEntries(_context) {
    return this.runtimeCommands.map(slashCommandToEntry2);
  }
  async listVaultEntries() {
    return [];
  }
  async saveVaultEntry(_entry) {
    throw new Error("OpenCode runtime commands are not editable from Claudian.");
  }
  async deleteVaultEntry(_entry) {
    throw new Error("OpenCode runtime commands are not deletable from Claudian.");
  }
  getDropdownConfig() {
    return {
      providerId: "opencode",
      triggerChars: ["/"],
      builtInPrefix: "/",
      skillPrefix: "/",
      commandPrefix: "/"
    };
  }
  async refresh() {
  }
};

// src/providers/opencode/runtime/OpencodeCliResolver.ts
var fs17 = __toESM(require("node:fs"));
init_env();
init_path();
var OpencodeCliResolver = class {
  constructor() {
    this.cachedHostname = getHostnameKey();
    this.lastCliPath = "";
    this.lastHostnamePath = "";
    this.lastEnvText = "";
    this.resolvedPath = null;
  }
  resolveFromSettings(settings11) {
    var _a3;
    const opencodeSettings = getOpencodeProviderSettings(settings11);
    const cliPath = opencodeSettings.cliPath.trim();
    const hostnamePath = ((_a3 = opencodeSettings.cliPathsByHost[this.cachedHostname]) != null ? _a3 : "").trim();
    const envText = getRuntimeEnvironmentText(settings11, "opencode");
    if (this.resolvedPath !== null && cliPath === this.lastCliPath && hostnamePath === this.lastHostnamePath && envText === this.lastEnvText) {
      return this.resolvedPath;
    }
    this.lastCliPath = cliPath;
    this.lastHostnamePath = hostnamePath;
    this.lastEnvText = envText;
    this.resolvedPath = this.resolve(
      opencodeSettings.cliPathsByHost,
      cliPath,
      envText
    );
    return this.resolvedPath;
  }
  resolve(hostnamePaths, legacyPath, _envText) {
    var _a3, _b2;
    const hostnamePath = ((_a3 = hostnamePaths == null ? void 0 : hostnamePaths[this.cachedHostname]) != null ? _a3 : "").trim();
    return (_b2 = resolveConfiguredCliPath(hostnamePath)) != null ? _b2 : resolveConfiguredCliPath(legacyPath.trim());
  }
  reset() {
    this.lastCliPath = "";
    this.lastHostnamePath = "";
    this.lastEnvText = "";
    this.resolvedPath = null;
  }
};
function resolveConfiguredCliPath(cliPath) {
  if (!cliPath) {
    return null;
  }
  try {
    const expanded = expandHomePath(cliPath);
    if (fs17.existsSync(expanded) && fs17.statSync(expanded).isFile()) {
      return expanded;
    }
  } catch (e2) {
    return null;
  }
  return null;
}

// src/providers/opencode/storage/OpencodeAgentStorage.ts
var path16 = __toESM(require("node:path"));

// src/providers/opencode/types/agent.ts
var OPENCODE_AGENT_KNOWN_KEYS = /* @__PURE__ */ new Set([
  "name",
  "description",
  "mode",
  "model",
  "variant",
  "temperature",
  "top_p",
  "steps",
  "maxSteps",
  "hidden",
  "color",
  "disable",
  "tools",
  "options",
  "permission"
]);

// src/providers/opencode/storage/OpencodeAgentStorage.ts
var OPENCODE_AGENT_PATH = ".opencode/agent";
var OPENCODE_AGENTS_PATH = ".opencode/agents";
var OPENCODE_AGENT_SCAN_PATHS = [
  OPENCODE_AGENTS_PATH,
  OPENCODE_AGENT_PATH
];
var OPENCODE_DEFAULT_AGENT_SAVE_PATH = OPENCODE_AGENT_PATH;
var OPENCODE_AGENT_PERSISTENCE_PREFIX = "opencode-agent";
function createOpencodeAgentPersistenceKey(location) {
  return `${OPENCODE_AGENT_PERSISTENCE_PREFIX}:${encodeURIComponent(normalizeVaultPath(location.filePath))}`;
}
function parseOpencodeAgentPersistenceKey(persistenceKey) {
  if (!persistenceKey) {
    return null;
  }
  const normalizedKey = normalizeVaultPath(persistenceKey);
  if (isSupportedAgentFilePath(normalizedKey)) {
    return { filePath: normalizedKey };
  }
  const [prefix, encodedRelativePath] = persistenceKey.split(":");
  if (prefix !== OPENCODE_AGENT_PERSISTENCE_PREFIX || !encodedRelativePath) {
    return null;
  }
  const decoded = normalizeVaultPath(decodeURIComponent(encodedRelativePath));
  if (isSupportedAgentFilePath(decoded)) {
    return { filePath: decoded };
  }
  return decoded.endsWith(".md") ? { filePath: `${OPENCODE_AGENTS_PATH}/${decoded}` } : null;
}
var OpencodeAgentStorage = class {
  constructor(vaultAdapter) {
    this.vaultAdapter = vaultAdapter;
  }
  async loadAll() {
    return this.scanAdapter(this.vaultAdapter);
  }
  async load(agent) {
    const filePath = this.resolveCurrentPath(agent);
    try {
      if (!await this.vaultAdapter.exists(filePath)) return null;
      const content = await this.vaultAdapter.read(filePath);
      return parseOpencodeAgentMarkdown(content, filePath);
    } catch (e2) {
      return null;
    }
  }
  async save(agent, previous) {
    const filePath = this.resolveTargetPath(agent, previous);
    const previousPath = previous ? this.resolveCurrentPath(previous) : null;
    await this.vaultAdapter.ensureFolder(path16.posix.dirname(filePath));
    const content = serializeOpencodeAgentMarkdown(agent);
    await this.vaultAdapter.write(filePath, content);
    if (previousPath && previousPath !== filePath) {
      await this.vaultAdapter.delete(previousPath);
    }
  }
  async delete(agent) {
    const filePath = this.resolveCurrentPath(agent);
    await this.vaultAdapter.delete(filePath);
  }
  resolveCurrentPath(agent) {
    const persistedLocation = parseOpencodeAgentPersistenceKey(agent.persistenceKey);
    if (persistedLocation) {
      return persistedLocation.filePath;
    }
    return `${OPENCODE_DEFAULT_AGENT_SAVE_PATH}/${agent.name}.md`;
  }
  resolveTargetPath(agent, previous) {
    if (previous && previous.name === agent.name) {
      return this.resolveCurrentPath(previous);
    }
    return `${OPENCODE_DEFAULT_AGENT_SAVE_PATH}/${agent.name}.md`;
  }
  async scanAdapter(adapter) {
    const agentsByName = /* @__PURE__ */ new Map();
    for (const rootPath of OPENCODE_AGENT_SCAN_PATHS) {
      try {
        const files = await adapter.listFilesRecursive(rootPath);
        for (const filePath of files) {
          if (!filePath.endsWith(".md")) continue;
          try {
            const content = await adapter.read(filePath);
            const agent = parseOpencodeAgentMarkdown(content, filePath);
            if (!agent) continue;
            const dedupeKey = agent.name.toLowerCase();
            agentsByName.delete(dedupeKey);
            agentsByName.set(dedupeKey, agent);
          } catch (e2) {
          }
        }
      } catch (e2) {
      }
    }
    return Array.from(agentsByName.values());
  }
};
function parseOpencodeAgentMarkdown(content, filePath) {
  var _a3;
  const parsed = parseFrontmatter(content);
  if (!parsed) {
    return null;
  }
  const fileName = normalizeAgentNameFromPath(filePath);
  const frontmatter = parsed.frontmatter;
  const rawName = typeof frontmatter.name === "string" ? frontmatter.name.trim() : "";
  const name = rawName || fileName;
  const description = typeof frontmatter.description === "string" ? frontmatter.description.trim() : "";
  if (!name || !description) {
    return null;
  }
  const result = {
    name,
    description,
    prompt: parsed.body.trim(),
    persistenceKey: createOpencodeAgentPersistenceKey({
      filePath: normalizeVaultPath(filePath)
    })
  };
  const mode = normalizeMode(frontmatter.mode);
  if (mode) result.mode = mode;
  if (typeof frontmatter.model === "string" && frontmatter.model.trim()) {
    result.model = frontmatter.model.trim();
  }
  if (typeof frontmatter.variant === "string" && frontmatter.variant.trim()) {
    result.variant = frontmatter.variant.trim();
  }
  if (typeof frontmatter.temperature === "number" && Number.isFinite(frontmatter.temperature)) {
    result.temperature = frontmatter.temperature;
  }
  const topP = normalizeFiniteNumber(frontmatter.top_p);
  if (topP !== void 0) {
    result.topP = topP;
  }
  if (typeof frontmatter.color === "string" && frontmatter.color.trim()) {
    result.color = frontmatter.color.trim();
  }
  const steps = (_a3 = normalizePositiveInteger(frontmatter.steps)) != null ? _a3 : normalizePositiveInteger(frontmatter.maxSteps);
  if (steps !== void 0) {
    result.steps = steps;
  }
  if (extractBoolean(frontmatter, "hidden") !== void 0) {
    result.hidden = extractBoolean(frontmatter, "hidden");
  }
  if (extractBoolean(frontmatter, "disable") !== void 0) {
    result.disable = extractBoolean(frontmatter, "disable");
  }
  if (isBooleanRecord(frontmatter.tools)) {
    result.tools = { ...frontmatter.tools };
  }
  if (isRecord(frontmatter.options)) {
    result.options = { ...frontmatter.options };
  }
  if (frontmatter.permission !== void 0) {
    result.permission = frontmatter.permission;
  }
  const extraFrontmatter = {};
  for (const [key, value] of Object.entries(frontmatter)) {
    if (!OPENCODE_AGENT_KNOWN_KEYS.has(key)) {
      extraFrontmatter[key] = value;
    }
  }
  if (Object.keys(extraFrontmatter).length > 0) {
    result.extraFrontmatter = extraFrontmatter;
  }
  return result;
}
function serializeOpencodeAgentMarkdown(agent) {
  const lines = ["---"];
  lines.push(`name: ${yamlString(agent.name)}`);
  lines.push(`description: ${yamlString(agent.description)}`);
  if (agent.mode) {
    lines.push(`mode: ${agent.mode}`);
  }
  if (agent.model) {
    lines.push(`model: ${serializeYamlValue(agent.model)}`);
  }
  if (agent.variant) {
    lines.push(`variant: ${serializeYamlValue(agent.variant)}`);
  }
  if (agent.temperature !== void 0) {
    lines.push(`temperature: ${serializeYamlValue(agent.temperature)}`);
  }
  if (agent.topP !== void 0) {
    lines.push(`top_p: ${serializeYamlValue(agent.topP)}`);
  }
  if (agent.color) {
    lines.push(`color: ${serializeYamlValue(agent.color)}`);
  }
  if (agent.steps !== void 0) {
    lines.push(`steps: ${serializeYamlValue(agent.steps)}`);
  }
  if (agent.hidden) {
    lines.push("hidden: true");
  }
  if (agent.disable) {
    lines.push("disable: true");
  }
  if (agent.tools && Object.keys(agent.tools).length > 0) {
    lines.push(`tools: ${serializeYamlValue(agent.tools)}`);
  }
  if (agent.options && Object.keys(agent.options).length > 0) {
    lines.push(`options: ${serializeYamlValue(agent.options)}`);
  }
  if (agent.permission !== void 0) {
    lines.push(`permission: ${serializeYamlValue(agent.permission)}`);
  }
  if (agent.extraFrontmatter) {
    for (const [key, value] of Object.entries(agent.extraFrontmatter)) {
      lines.push(`${key}: ${serializeYamlValue(value)}`);
    }
  }
  lines.push("---");
  lines.push(agent.prompt);
  return lines.join("\n");
}
function normalizeAgentNameFromPath(filePath) {
  const relativePath = toRelativeAgentPath(filePath);
  return relativePath.replace(/\.md$/i, "");
}
function toRelativeAgentPath(filePath) {
  var _a3;
  const normalized = normalizeVaultPath(filePath);
  for (const rootPath of OPENCODE_AGENT_SCAN_PATHS) {
    const prefix = `${rootPath}/`;
    const index = normalized.lastIndexOf(prefix);
    if (index >= 0) {
      return normalized.slice(index + prefix.length);
    }
  }
  return (_a3 = normalized.split("/").pop()) != null ? _a3 : normalized;
}
function normalizeMode(value) {
  return value === "subagent" || value === "primary" || value === "all" ? value : void 0;
}
function normalizeFiniteNumber(value) {
  return typeof value === "number" && Number.isFinite(value) ? value : void 0;
}
function normalizePositiveInteger(value) {
  return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : void 0;
}
function isBooleanRecord(value) {
  if (!isRecord(value)) {
    return false;
  }
  return Object.values(value).every((entry) => typeof entry === "boolean");
}
function serializeYamlValue(value) {
  if (typeof value === "string") {
    return yamlString(value);
  }
  if (typeof value === "number" || typeof value === "boolean") {
    return String(value);
  }
  if (value === null) {
    return "null";
  }
  return JSON.stringify(value);
}
function normalizeVaultPath(filePath) {
  return filePath.replace(/\\/g, "/");
}
function isSupportedAgentFilePath(filePath) {
  return OPENCODE_AGENT_SCAN_PATHS.some((rootPath) => filePath.startsWith(`${rootPath}/`)) && filePath.endsWith(".md");
}

// src/providers/opencode/ui/OpencodeSettingsTab.ts
var fs18 = __toESM(require("fs"));
var import_obsidian19 = require("obsidian");
init_env();
init_path();

// src/providers/opencode/ui/OpencodeAgentSettings.ts
var import_obsidian18 = require("obsidian");
var OPENCODE_AGENT_INVALID_SEGMENT_PATTERN = /[<>:"\\|?*]/;
function validateOpencodeAgentName(name) {
  if (!name) return "Agent name is required";
  const segments = name.split("/");
  if (segments.length === 0 || segments.some((segment) => segment.length === 0)) {
    return "Agent name must use slash-separated path segments without leading or trailing slashes";
  }
  for (const segment of segments) {
    if (!segment.trim()) {
      return "Agent name path segments cannot be empty or whitespace-only";
    }
    if (segment !== segment.trim()) {
      return "Agent name path segments cannot start or end with whitespace";
    }
    if (segment === "." || segment === "..") {
      return 'Agent name cannot include "." or ".." path segments';
    }
    if (segment.includes("\0") || OPENCODE_AGENT_INVALID_SEGMENT_PATTERN.test(segment)) {
      return "Agent name path segments cannot contain Windows-reserved filename characters";
    }
  }
  return null;
}
function findOpencodeAgentNameConflict(agents, name, currentPersistenceKey) {
  var _a3;
  const normalizedName = name.toLowerCase();
  return (_a3 = agents.find(
    (agent) => agent.name.toLowerCase() === normalizedName && agent.persistenceKey !== currentPersistenceKey
  )) != null ? _a3 : null;
}
var OpencodeAgentModal = class extends import_obsidian18.Modal {
  constructor(app, existing, allAgents, onSave) {
    super(app);
    this.existing = existing;
    this.allAgents = allAgents;
    this.onSave = onSave;
  }
  onOpen() {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l, _m, _n, _o, _p2, _q;
    this.setTitle(this.existing ? "Edit OpenCode Subagent" : "Add OpenCode Subagent");
    this.modalEl.addClass("claudian-sp-modal");
    const { contentEl } = this;
    let nameInput;
    let descriptionInput;
    let modelInput;
    let variantInput;
    let temperatureInput;
    let topPInput;
    let colorInput;
    let stepsInput;
    let hiddenValue = (_b2 = (_a3 = this.existing) == null ? void 0 : _a3.hidden) != null ? _b2 : false;
    let disableValue = (_d2 = (_c = this.existing) == null ? void 0 : _c.disable) != null ? _d2 : false;
    let toolsInput;
    let permissionInput;
    let optionsInput;
    new import_obsidian18.Setting(contentEl).setName("Name").setDesc("OpenCode agent name. Use slash-separated segments for nested agents.").addText((text) => {
      var _a4, _b3;
      nameInput = text.inputEl;
      text.setValue((_b3 = (_a4 = this.existing) == null ? void 0 : _a4.name) != null ? _b3 : "").setPlaceholder("review");
    });
    new import_obsidian18.Setting(contentEl).setName("Description").setDesc("When OpenCode should use this subagent").addText((text) => {
      var _a4, _b3;
      descriptionInput = text.inputEl;
      text.setValue((_b3 = (_a4 = this.existing) == null ? void 0 : _a4.description) != null ? _b3 : "").setPlaceholder("Reviews code for correctness and maintainability");
    });
    const details = contentEl.createEl("details", { cls: "claudian-sp-advanced-section" });
    details.createEl("summary", {
      text: "Advanced options",
      cls: "claudian-sp-advanced-summary"
    });
    if (((_e = this.existing) == null ? void 0 : _e.model) || ((_f = this.existing) == null ? void 0 : _f.variant) || ((_g = this.existing) == null ? void 0 : _g.temperature) !== void 0 || ((_h = this.existing) == null ? void 0 : _h.topP) !== void 0 || ((_i = this.existing) == null ? void 0 : _i.color) || ((_j2 = this.existing) == null ? void 0 : _j2.steps) !== void 0 || ((_k = this.existing) == null ? void 0 : _k.hidden) || ((_l = this.existing) == null ? void 0 : _l.disable) || ((_m = this.existing) == null ? void 0 : _m.tools) || ((_n = this.existing) == null ? void 0 : _n.permission) !== void 0 || ((_o = this.existing) == null ? void 0 : _o.options)) {
      details.open = true;
    }
    new import_obsidian18.Setting(details).setName("Model").setDesc("Model override in provider/model format").addText((text) => {
      var _a4, _b3;
      modelInput = text.inputEl;
      text.setValue((_b3 = (_a4 = this.existing) == null ? void 0 : _a4.model) != null ? _b3 : "").setPlaceholder("anthropic/claude-sonnet-4-20250514");
    });
    new import_obsidian18.Setting(details).setName("Variant").setDesc("Model variant override").addText((text) => {
      var _a4, _b3;
      variantInput = text.inputEl;
      text.setValue((_b3 = (_a4 = this.existing) == null ? void 0 : _a4.variant) != null ? _b3 : "").setPlaceholder("high");
    });
    new import_obsidian18.Setting(details).setName("Temperature").setDesc("Optional sampling temperature").addText((text) => {
      var _a4;
      temperatureInput = text.inputEl;
      text.setValue(((_a4 = this.existing) == null ? void 0 : _a4.temperature) !== void 0 ? String(this.existing.temperature) : "").setPlaceholder("0.1");
    });
    new import_obsidian18.Setting(details).setName("Top P").setDesc("Optional nucleus sampling value").addText((text) => {
      var _a4;
      topPInput = text.inputEl;
      text.setValue(((_a4 = this.existing) == null ? void 0 : _a4.topP) !== void 0 ? String(this.existing.topP) : "").setPlaceholder("0.9");
    });
    new import_obsidian18.Setting(details).setName("Color").setDesc("Hex color or theme token").addText((text) => {
      var _a4, _b3;
      colorInput = text.inputEl;
      text.setValue((_b3 = (_a4 = this.existing) == null ? void 0 : _a4.color) != null ? _b3 : "").setPlaceholder("#FF5733");
    });
    new import_obsidian18.Setting(details).setName("Steps").setDesc("Maximum agentic iterations before forcing text-only output").addText((text) => {
      var _a4;
      stepsInput = text.inputEl;
      text.setValue(((_a4 = this.existing) == null ? void 0 : _a4.steps) !== void 0 ? String(this.existing.steps) : "").setPlaceholder("10");
    });
    new import_obsidian18.Setting(details).setName("Hide From @mention").setDesc("Hide this subagent from the @ autocomplete menu").addToggle((toggle) => {
      toggle.setValue(hiddenValue).onChange((value) => {
        hiddenValue = value;
      });
    });
    new import_obsidian18.Setting(details).setName("Disable Agent").setDesc("Disable the agent without deleting the file").addToggle((toggle) => {
      toggle.setValue(disableValue).onChange((value) => {
        disableValue = value;
      });
    });
    new import_obsidian18.Setting(details).setName("Enabled Tools (JSON)").setDesc('Optional deprecated tools map, e.g. {"write":false,"edit":false}').addTextArea((text) => {
      var _a4;
      toolsInput = text.inputEl;
      text.setValue(((_a4 = this.existing) == null ? void 0 : _a4.tools) ? JSON.stringify(this.existing.tools, null, 2) : "").setPlaceholder('{\n  "write": false,\n  "edit": false\n}');
    });
    new import_obsidian18.Setting(details).setName("Permission (JSON)").setDesc('Optional permission config, e.g. {"edit":"deny","bash":"allow"}').addTextArea((text) => {
      var _a4;
      permissionInput = text.inputEl;
      text.setValue(((_a4 = this.existing) == null ? void 0 : _a4.permission) !== void 0 ? JSON.stringify(this.existing.permission, null, 2) : "").setPlaceholder('{\n  "edit": "deny"\n}');
    });
    new import_obsidian18.Setting(details).setName("Options (JSON)").setDesc("Optional custom agent options").addTextArea((text) => {
      var _a4;
      optionsInput = text.inputEl;
      text.setValue(((_a4 = this.existing) == null ? void 0 : _a4.options) ? JSON.stringify(this.existing.options, null, 2) : "").setPlaceholder('{\n  "focus": "security"\n}');
    });
    new import_obsidian18.Setting(contentEl).setName("Prompt").setDesc("Markdown body used as the agent prompt");
    const promptArea = contentEl.createEl("textarea", {
      cls: "claudian-sp-content-area",
      attr: {
        rows: "10",
        placeholder: "Review code changes carefully and call out correctness, regressions, and missing coverage."
      }
    });
    promptArea.value = (_q = (_p2 = this.existing) == null ? void 0 : _p2.prompt) != null ? _q : "";
    const buttonContainer = contentEl.createDiv({ cls: "claudian-sp-modal-buttons" });
    const cancelBtn = buttonContainer.createEl("button", {
      text: "Cancel",
      cls: "claudian-cancel-btn"
    });
    cancelBtn.addEventListener("click", () => this.close());
    const saveBtn = buttonContainer.createEl("button", {
      text: "Save",
      cls: "claudian-save-btn"
    });
    saveBtn.addEventListener("click", async () => {
      var _a4, _b3, _c2;
      const name = nameInput.value.trim();
      const nameError = validateOpencodeAgentName(name);
      if (nameError) {
        new import_obsidian18.Notice(nameError);
        return;
      }
      const description = descriptionInput.value.trim();
      if (!description) {
        new import_obsidian18.Notice("Description is required");
        return;
      }
      const prompt = promptArea.value;
      if (!prompt.trim()) {
        new import_obsidian18.Notice("Prompt is required");
        return;
      }
      const duplicate = findOpencodeAgentNameConflict(
        this.allAgents,
        name,
        (_a4 = this.existing) == null ? void 0 : _a4.persistenceKey
      );
      if (duplicate) {
        new import_obsidian18.Notice(`A subagent named "${name}" already exists`);
        return;
      }
      const temperature = parseOptionalNumber(temperatureInput.value, "Temperature");
      if (temperature.error) {
        new import_obsidian18.Notice(temperature.error);
        return;
      }
      const topP = parseOptionalNumber(topPInput.value, "Top P");
      if (topP.error) {
        new import_obsidian18.Notice(topP.error);
        return;
      }
      const steps = parseOptionalPositiveInteger(stepsInput.value, "Steps");
      if (steps.error) {
        new import_obsidian18.Notice(steps.error);
        return;
      }
      const tools = parseOptionalJsonObjectOfBooleans(toolsInput.value, "Enabled Tools");
      if (tools.error) {
        new import_obsidian18.Notice(tools.error);
        return;
      }
      const permission = parseOptionalJson(permissionInput.value, "Permission");
      if (permission.error) {
        new import_obsidian18.Notice(permission.error);
        return;
      }
      const options = parseOptionalJsonObject(optionsInput.value, "Options");
      if (options.error) {
        new import_obsidian18.Notice(options.error);
        return;
      }
      const agent = {
        name,
        description,
        prompt,
        mode: "subagent",
        hidden: hiddenValue || void 0,
        disable: disableValue || void 0,
        model: modelInput.value.trim() || void 0,
        variant: variantInput.value.trim() || void 0,
        temperature: temperature.value,
        topP: topP.value,
        color: colorInput.value.trim() || void 0,
        steps: steps.value,
        tools: tools.value,
        permission: permission.value,
        options: options.value,
        persistenceKey: (_b3 = this.existing) == null ? void 0 : _b3.persistenceKey,
        extraFrontmatter: (_c2 = this.existing) == null ? void 0 : _c2.extraFrontmatter
      };
      try {
        await this.onSave(agent);
      } catch (error48) {
        const message = error48 instanceof Error ? error48.message : "Unknown error";
        new import_obsidian18.Notice(`Failed to save subagent: ${message}`);
        return;
      }
      this.close();
    });
  }
  onClose() {
    this.contentEl.empty();
  }
};
var OpencodeAgentSettings = class {
  constructor(containerEl, storage, app, onChanged) {
    this.agents = [];
    this.containerEl = containerEl;
    this.storage = storage;
    this.app = app;
    this.onChanged = onChanged;
    void this.render();
  }
  async render() {
    this.containerEl.empty();
    try {
      this.agents = await this.storage.loadAll();
    } catch (e2) {
      this.agents = [];
    }
    const visibleAgents = this.agents.filter((agent) => agent.mode === "subagent");
    const headerEl = this.containerEl.createDiv({ cls: "claudian-sp-header" });
    headerEl.createSpan({ text: "OpenCode Subagents", cls: "claudian-sp-label" });
    const actionsEl = headerEl.createDiv({ cls: "claudian-sp-header-actions" });
    const refreshBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Refresh" }
    });
    (0, import_obsidian18.setIcon)(refreshBtn, "refresh-cw");
    refreshBtn.addEventListener("click", () => {
      void this.render();
    });
    const addBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Add" }
    });
    (0, import_obsidian18.setIcon)(addBtn, "plus");
    addBtn.addEventListener("click", () => this.openModal(null));
    if (visibleAgents.length === 0) {
      const emptyEl = this.containerEl.createDiv({ cls: "claudian-sp-empty-state" });
      emptyEl.setText("No OpenCode subagents in vault. Click + to create one.");
      return;
    }
    const listEl = this.containerEl.createDiv({ cls: "claudian-sp-list" });
    for (const agent of visibleAgents) {
      this.renderItem(listEl, agent);
    }
  }
  renderItem(listEl, agent) {
    const itemEl = listEl.createDiv({ cls: "claudian-sp-item" });
    const infoEl = itemEl.createDiv({ cls: "claudian-sp-info" });
    const headerRow = infoEl.createDiv({ cls: "claudian-sp-item-header" });
    const nameEl = headerRow.createSpan({ cls: "claudian-sp-item-name" });
    nameEl.setText(agent.name);
    headerRow.createSpan({
      text: "subagent",
      cls: "claudian-slash-item-badge"
    });
    if (agent.model) {
      headerRow.createSpan({ text: agent.model, cls: "claudian-slash-item-badge" });
    }
    if (agent.description) {
      const descEl = infoEl.createDiv({ cls: "claudian-sp-item-desc" });
      descEl.setText(agent.description);
    }
    const actionsEl = itemEl.createDiv({ cls: "claudian-sp-item-actions" });
    const editBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn",
      attr: { "aria-label": "Edit" }
    });
    (0, import_obsidian18.setIcon)(editBtn, "pencil");
    editBtn.addEventListener("click", () => this.openModal(agent));
    const deleteBtn = actionsEl.createEl("button", {
      cls: "claudian-settings-action-btn claudian-settings-delete-btn",
      attr: { "aria-label": "Delete" }
    });
    (0, import_obsidian18.setIcon)(deleteBtn, "trash-2");
    deleteBtn.addEventListener("click", async () => {
      var _a3;
      if (!this.app) return;
      const confirmed = await confirmDelete(
        this.app,
        `Delete subagent "${agent.name}"?`
      );
      if (!confirmed) return;
      try {
        await this.storage.delete(agent);
        await this.render();
        await ((_a3 = this.onChanged) == null ? void 0 : _a3.call(this));
        new import_obsidian18.Notice(`Subagent "${agent.name}" deleted`);
      } catch (e2) {
        new import_obsidian18.Notice("Failed to delete subagent");
      }
    });
  }
  openModal(existing) {
    if (!this.app) return;
    const modal = new OpencodeAgentModal(
      this.app,
      existing,
      this.agents,
      async (agent) => {
        var _a3;
        await this.storage.save(agent, existing);
        await this.render();
        await ((_a3 = this.onChanged) == null ? void 0 : _a3.call(this));
        new import_obsidian18.Notice(
          existing ? `Subagent "${agent.name}" updated` : `Subagent "${agent.name}" created`
        );
      }
    );
    modal.open();
  }
};
function parseOptionalNumber(value, label) {
  const trimmed = value.trim();
  if (!trimmed) {
    return {};
  }
  const parsed = Number(trimmed);
  if (!Number.isFinite(parsed)) {
    return { error: `${label} must be a valid number` };
  }
  return { value: parsed };
}
function parseOptionalPositiveInteger(value, label) {
  const trimmed = value.trim();
  if (!trimmed) {
    return {};
  }
  const parsed = Number(trimmed);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    return { error: `${label} must be a positive integer` };
  }
  return { value: parsed };
}
function parseOptionalJson(value, label) {
  const trimmed = value.trim();
  if (!trimmed) {
    return {};
  }
  try {
    return { value: JSON.parse(trimmed) };
  } catch (e2) {
    return { error: `${label} must be valid JSON` };
  }
}
function parseOptionalJsonObject(value, label) {
  const parsed = parseOptionalJson(value, label);
  if (parsed.error || parsed.value === void 0) {
    return parsed.error ? { error: parsed.error } : {};
  }
  if (!isJsonObject(parsed.value)) {
    return { error: `${label} must be a JSON object` };
  }
  return { value: parsed.value };
}
function parseOptionalJsonObjectOfBooleans(value, label) {
  const parsed = parseOptionalJsonObject(value, label);
  if (parsed.error || parsed.value === void 0) {
    return parsed.error ? { error: parsed.error } : {};
  }
  if (!Object.values(parsed.value).every((entry) => typeof entry === "boolean")) {
    return { error: `${label} must map tool names to boolean values` };
  }
  return { value: parsed.value };
}
function isJsonObject(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}

// src/providers/opencode/ui/OpencodeSettingsTab.ts
var ALL_PROVIDERS_KEY = "all";
var opencodeSettingsTabRenderer = {
  render(container, context) {
    const opencodeWorkspace = maybeGetOpencodeWorkspaceServices();
    const settingsBag = context.plugin.settings;
    const opencodeSettings = getOpencodeProviderSettings(settingsBag);
    const hostnameKey = getHostnameKey();
    new import_obsidian19.Setting(container).setName("Setup").setHeading();
    new import_obsidian19.Setting(container).setName("Enable OpenCode").setDesc("Launch `opencode acp` as a provider.").addToggle(
      (toggle) => toggle.setValue(opencodeSettings.enabled).onChange(async (value) => {
        updateOpencodeProviderSettings(settingsBag, { enabled: value });
        await context.plugin.saveSettings();
        context.refreshModelSelectors();
      })
    );
    const cliPathSetting = new import_obsidian19.Setting(container).setName(`CLI Path (${hostnameKey})`).setDesc("Optional absolute path to the OpenCode CLI for this computer. Leave empty to use `opencode` from PATH.");
    const validationEl = container.createDiv({ cls: "claudian-cli-path-validation" });
    validationEl.style.color = "var(--text-error)";
    validationEl.style.fontSize = "0.85em";
    validationEl.style.marginTop = "-0.5em";
    validationEl.style.marginBottom = "0.5em";
    validationEl.style.display = "none";
    const validatePath = (value) => {
      const trimmed = value.trim();
      if (!trimmed) {
        return null;
      }
      const expandedPath = expandHomePath(trimmed);
      if (!fs18.existsSync(expandedPath)) {
        return "Path does not exist";
      }
      const stat = fs18.statSync(expandedPath);
      if (!stat.isFile()) {
        return "Path must point to a file";
      }
      return null;
    };
    const updateCliPathValidation = (value, inputEl) => {
      const error48 = validatePath(value);
      if (error48) {
        validationEl.setText(error48);
        validationEl.style.display = "block";
        if (inputEl) {
          inputEl.style.borderColor = "var(--text-error)";
        }
        return false;
      }
      validationEl.style.display = "none";
      if (inputEl) {
        inputEl.style.borderColor = "";
      }
      return true;
    };
    const cliPathsByHost = { ...opencodeSettings.cliPathsByHost };
    const currentValue = opencodeSettings.cliPathsByHost[hostnameKey] || "";
    let cliPathInputEl = null;
    const persistCliPath = async (value) => {
      var _a3;
      const isValid2 = updateCliPathValidation(value, cliPathInputEl != null ? cliPathInputEl : void 0);
      if (!isValid2) {
        return false;
      }
      const trimmed = value.trim();
      if (trimmed) {
        cliPathsByHost[hostnameKey] = trimmed;
      } else {
        delete cliPathsByHost[hostnameKey];
      }
      updateOpencodeProviderSettings(settingsBag, { cliPathsByHost: { ...cliPathsByHost } });
      clearOpencodeDiscoveryState(settingsBag);
      await context.plugin.saveSettings();
      (_a3 = opencodeWorkspace == null ? void 0 : opencodeWorkspace.cliResolver) == null ? void 0 : _a3.reset();
      await recycleOpencodeRuntime();
      return true;
    };
    const recycleOpencodeRuntime = async () => {
      var _a3, _b2;
      for (const view of context.plugin.getAllViews()) {
        const tabManager = view.getTabManager();
        if (tabManager == null ? void 0 : tabManager.broadcastToProviderTabs) {
          await tabManager.broadcastToProviderTabs("opencode", (service) => Promise.resolve(service.cleanup()));
        } else {
          await (tabManager == null ? void 0 : tabManager.broadcastToAllTabs(
            (service) => Promise.resolve(service.cleanup())
          ));
        }
        (_a3 = view.invalidateProviderCommandCaches) == null ? void 0 : _a3.call(view, ["opencode"]);
        (_b2 = view.refreshModelSelector) == null ? void 0 : _b2.call(view);
      }
    };
    cliPathSetting.addText((text) => {
      text.setPlaceholder(process.platform === "win32" ? "C:\\Users\\you\\AppData\\Roaming\\npm\\opencode.cmd" : "/usr/local/bin/opencode").setValue(currentValue).onChange(async (value) => {
        await persistCliPath(value);
      });
      text.inputEl.addClass("claudian-settings-cli-path-input");
      text.inputEl.style.width = "100%";
      cliPathInputEl = text.inputEl;
      updateCliPathValidation(currentValue, text.inputEl);
    });
    new import_obsidian19.Setting(container).setName("Models").setHeading();
    new import_obsidian19.Setting(container).setName("Visible Models").setDesc("Choose which OpenCode models appear in the chat selector. Filter by provider or type to search. The current session model stays pinned even if it is not selected here.");
    const pickerEl = container.createDiv({ cls: "claudian-opencode-model-picker" });
    let searchQuery = "";
    let providerFilter = ALL_PROVIDERS_KEY;
    const summaryEl = pickerEl.createDiv({ cls: "claudian-opencode-model-picker-summary" });
    const selectedEl = pickerEl.createDiv({ cls: "claudian-opencode-model-picker-selected" });
    const catalogEl = pickerEl.createEl("details", { cls: "claudian-opencode-model-picker-catalog" });
    catalogEl.open = getOpencodeProviderSettings(settingsBag).visibleModels.length === 0;
    const catalogSummaryEl = catalogEl.createEl("summary", {
      cls: "claudian-opencode-model-picker-catalog-summary"
    });
    catalogSummaryEl.createSpan({
      cls: "claudian-opencode-model-picker-catalog-caret",
      text: "\u25B8"
    });
    catalogSummaryEl.createSpan({
      cls: "claudian-opencode-model-picker-catalog-title",
      text: "Browse models"
    });
    const catalogSummaryCountEl = catalogSummaryEl.createSpan({
      cls: "claudian-opencode-model-picker-catalog-count"
    });
    const controlsEl = catalogEl.createDiv({ cls: "claudian-opencode-model-picker-controls" });
    const searchInput = controlsEl.createEl("input", {
      cls: "claudian-opencode-model-picker-search",
      type: "search"
    });
    searchInput.placeholder = "Filter by model, provider, or id\u2026";
    searchInput.addEventListener("input", () => {
      searchQuery = searchInput.value.trim().toLowerCase();
      renderList();
    });
    const providerSelectEl = controlsEl.createEl("select", {
      cls: "claudian-opencode-model-picker-provider"
    });
    providerSelectEl.addEventListener("change", () => {
      providerFilter = providerSelectEl.value;
      renderList();
    });
    const listEl = catalogEl.createDiv({ cls: "claudian-opencode-model-picker-list" });
    const getEnrichedModels = () => {
      const current = getOpencodeProviderSettings(settingsBag);
      return buildEnrichedModels(current.discoveredModels, current.visibleModels);
    };
    const filterModels = (models) => {
      return models.filter((model) => {
        if (providerFilter !== ALL_PROVIDERS_KEY && model.providerKey !== providerFilter) {
          return false;
        }
        if (!searchQuery) {
          return true;
        }
        return model.rawId.toLowerCase().includes(searchQuery) || model.modelLabel.toLowerCase().includes(searchQuery) || model.providerLabel.toLowerCase().includes(searchQuery) || model.description.toLowerCase().includes(searchQuery);
      });
    };
    const persistVisibleModels = async (visibleModels) => {
      const currentVisibleModels = getOpencodeProviderSettings(settingsBag).visibleModels;
      const normalized = normalizeOpencodeVisibleModels(
        visibleModels,
        getOpencodeProviderSettings(settingsBag).discoveredModels
      );
      if (sameStringList(currentVisibleModels, normalized)) {
        return;
      }
      updateOpencodeProviderSettings(settingsBag, { visibleModels: normalized });
      await context.plugin.saveSettings();
      renderAll();
      context.refreshModelSelectors();
    };
    const persistModelAliases = async (modelAliases) => {
      updateOpencodeProviderSettings(settingsBag, { modelAliases });
      await context.plugin.saveSettings();
      renderSelected();
      context.refreshModelSelectors();
    };
    const renderSummary = () => {
      summaryEl.empty();
      const current = getOpencodeProviderSettings(settingsBag);
      const enriched = getEnrichedModels();
      const providerCount = new Set(enriched.map((model) => model.providerKey)).size;
      const providerWord = providerCount === 1 ? "provider" : "providers";
      summaryEl.createSpan({ text: "Visible: " });
      summaryEl.createSpan({
        cls: "claudian-opencode-model-picker-summary-value",
        text: String(current.visibleModels.length)
      });
      summaryEl.createSpan({
        text: ` of ${current.discoveredModels.length} discovered \u2022 ${providerCount} ${providerWord}`
      });
      catalogSummaryCountEl.setText(
        current.discoveredModels.length > 0 ? `${current.discoveredModels.length} available` : "No models discovered yet"
      );
    };
    const renderSelected = () => {
      var _a3;
      selectedEl.empty();
      const current = getOpencodeProviderSettings(settingsBag);
      if (current.visibleModels.length === 0) {
        selectedEl.style.display = "none";
        return;
      }
      selectedEl.style.display = "";
      const enrichedByRawId = new Map(
        getEnrichedModels().map((model) => [model.rawId, model])
      );
      const headerEl = selectedEl.createDiv({ cls: "claudian-opencode-model-picker-selected-header" });
      headerEl.createEl("span", {
        cls: "claudian-opencode-model-picker-selected-label",
        text: `Selected (${current.visibleModels.length})`
      });
      const clearAllBtn = headerEl.createEl("button", {
        cls: "claudian-opencode-model-picker-selected-clear",
        text: "Clear all"
      });
      clearAllBtn.setAttribute("aria-label", "Clear all selected models");
      clearAllBtn.addEventListener("click", () => {
        void persistVisibleModels([]);
      });
      const rowsEl = selectedEl.createDiv({ cls: "claudian-opencode-model-picker-selected-rows" });
      for (const rawId of current.visibleModels) {
        const enriched = enrichedByRawId.get(rawId);
        const defaultLabel = enriched ? `${enriched.providerLabel}/${enriched.modelLabel}` : rawId;
        const rowEl = rowsEl.createDiv({ cls: "claudian-opencode-model-picker-selected-row" });
        if (enriched && !enriched.isAvailable) {
          rowEl.classList.add("claudian-opencode-model-picker-selected-row--unavailable");
        }
        const infoEl = rowEl.createDiv({ cls: "claudian-opencode-model-picker-selected-info" });
        const titleEl = infoEl.createDiv({ cls: "claudian-opencode-model-picker-selected-title" });
        if (enriched) {
          titleEl.createEl("span", {
            cls: "claudian-opencode-model-picker-selected-badge",
            text: enriched.providerLabel
          });
          titleEl.createEl("span", {
            cls: "claudian-opencode-model-picker-selected-name",
            text: enriched.modelLabel
          });
        } else {
          titleEl.createEl("span", {
            cls: "claudian-opencode-model-picker-selected-name",
            text: rawId
          });
        }
        if (enriched && !enriched.isAvailable) {
          infoEl.createEl("div", {
            cls: "claudian-opencode-model-picker-selected-unavailable",
            text: "Not currently reported by OpenCode"
          });
        }
        infoEl.createEl("div", {
          cls: "claudian-opencode-model-picker-selected-id",
          text: rawId
        });
        const controlsEl2 = rowEl.createDiv({ cls: "claudian-opencode-model-picker-selected-controls" });
        const aliasInput = controlsEl2.createEl("input", {
          cls: "claudian-opencode-model-picker-selected-alias",
          type: "text"
        });
        aliasInput.placeholder = defaultLabel;
        aliasInput.value = (_a3 = current.modelAliases[rawId]) != null ? _a3 : "";
        aliasInput.setAttribute("aria-label", `Alias for ${defaultLabel}`);
        aliasInput.title = "Custom label shown in the model selector. Leave empty to use the default.";
        const commitAlias = () => {
          var _a4;
          const latest = getOpencodeProviderSettings(settingsBag);
          const existing = (_a4 = latest.modelAliases[rawId]) != null ? _a4 : "";
          const next = aliasInput.value.trim();
          if (next === existing) {
            aliasInput.value = existing;
            return;
          }
          const nextAliases = { ...latest.modelAliases };
          if (next) {
            nextAliases[rawId] = next;
          } else {
            delete nextAliases[rawId];
          }
          void persistModelAliases(nextAliases);
        };
        aliasInput.addEventListener("blur", commitAlias);
        aliasInput.addEventListener("keydown", (event) => {
          var _a4;
          if (event.key === "Enter") {
            event.preventDefault();
            aliasInput.blur();
          } else if (event.key === "Escape") {
            event.preventDefault();
            aliasInput.value = (_a4 = getOpencodeProviderSettings(settingsBag).modelAliases[rawId]) != null ? _a4 : "";
            aliasInput.blur();
          }
        });
        const removeBtn = controlsEl2.createEl("button", {
          cls: "claudian-opencode-model-picker-selected-remove",
          text: "\xD7"
        });
        removeBtn.setAttribute("aria-label", `Remove ${defaultLabel}`);
        removeBtn.addEventListener("click", () => {
          void persistVisibleModels(current.visibleModels.filter((entry) => entry !== rawId));
        });
      }
    };
    const renderProviderSelect = () => {
      const enriched = getEnrichedModels();
      const providers = /* @__PURE__ */ new Map();
      for (const model of enriched) {
        const existing = providers.get(model.providerKey);
        if (existing) {
          existing.count += 1;
        } else {
          providers.set(model.providerKey, { count: 1, label: model.providerLabel });
        }
      }
      providerSelectEl.empty();
      providerSelectEl.createEl("option", {
        text: `All providers (${enriched.length})`,
        value: ALL_PROVIDERS_KEY
      });
      const sortedProviders = Array.from(providers.entries()).sort(([, left], [, right]) => left.label.localeCompare(right.label));
      for (const [key, { count, label }] of sortedProviders) {
        providerSelectEl.createEl("option", {
          text: `${label} (${count})`,
          value: key
        });
      }
      if (providerFilter !== ALL_PROVIDERS_KEY && !providers.has(providerFilter)) {
        providerFilter = ALL_PROVIDERS_KEY;
      }
      providerSelectEl.value = providerFilter;
    };
    const renderList = () => {
      listEl.empty();
      const current = getOpencodeProviderSettings(settingsBag);
      const selectedIds = new Set(current.visibleModels);
      const enriched = getEnrichedModels();
      const filtered = filterModels(enriched);
      if (filtered.length === 0) {
        const emptyEl = listEl.createDiv({ cls: "claudian-opencode-model-picker-empty" });
        emptyEl.setText(enriched.length === 0 ? "Start OpenCode once to load its model catalog. Claudian will then let you pick visible models." : "No models match your filter.");
        return;
      }
      for (const model of filtered) {
        const rowEl = listEl.createEl("label", { cls: "claudian-opencode-model-picker-row" });
        const isSelected = selectedIds.has(model.rawId);
        if (isSelected) {
          rowEl.classList.add("claudian-opencode-model-picker-row--selected");
        }
        rowEl.title = model.rawId;
        const checkboxEl = rowEl.createEl("input", { type: "checkbox" });
        checkboxEl.checked = isSelected;
        checkboxEl.addEventListener("change", () => {
          const currentVisibleModels = getOpencodeProviderSettings(settingsBag).visibleModels;
          const next = checkboxEl.checked ? [...currentVisibleModels, model.rawId] : currentVisibleModels.filter((id) => id !== model.rawId);
          void persistVisibleModels(next);
        });
        const textEl = rowEl.createDiv({ cls: "claudian-opencode-model-picker-row-text" });
        const headerEl = textEl.createDiv({ cls: "claudian-opencode-model-picker-row-header" });
        headerEl.createEl("span", {
          cls: "claudian-opencode-model-picker-row-name",
          text: model.modelLabel
        });
        const badgeEl = headerEl.createEl("span", {
          cls: "claudian-opencode-model-picker-row-badge",
          text: model.providerLabel
        });
        if (!model.isAvailable) {
          badgeEl.classList.add("claudian-opencode-model-picker-row-badge--unavailable");
          badgeEl.setText("Unavailable");
          badgeEl.title = "Configured model not currently reported by OpenCode";
        }
        textEl.createDiv({
          cls: "claudian-opencode-model-picker-row-meta",
          text: model.rawId
        });
        if (model.description) {
          textEl.createDiv({
            cls: "claudian-opencode-model-picker-row-desc",
            text: model.description
          });
        }
      }
    };
    const renderAll = () => {
      renderSummary();
      renderSelected();
      renderProviderSelect();
      renderList();
    };
    renderAll();
    new import_obsidian19.Setting(container).setName("Commands and Skills").setHeading();
    const commandsDesc = container.createDiv({ cls: "claudian-sp-settings-desc" });
    commandsDesc.createEl("p", {
      cls: "setting-item-description",
      text: "OpenCode can auto-detect vault-level Claude slash commands from .claude/commands/ and skills from .claude/skills/, .codex/skills/, and .agents/skills/. Manage those entries in the Claude or Codex settings tab. This setting only hides entries from the OpenCode dropdown."
    });
    context.renderHiddenProviderCommandSetting(container, "opencode", {
      name: "Hidden Commands and Skills",
      desc: "Hide specific OpenCode commands and skills from the dropdown. Enter names without the leading slash, one per line.",
      placeholder: "compact\nreview\nfix"
    });
    if (opencodeWorkspace == null ? void 0 : opencodeWorkspace.agentStorage) {
      new import_obsidian19.Setting(container).setName("Subagents").setHeading();
      const subagentsDesc = container.createDiv({ cls: "claudian-sp-settings-desc" });
      subagentsDesc.createEl("p", {
        cls: "setting-item-description",
        text: "Manage vault-level OpenCode subagents from .opencode/agent/ and legacy .opencode/agents/. New entries are saved as subagent-only files and appear in the @mention menu."
      });
      const subagentsContainer = container.createDiv({ cls: "claudian-slash-commands-container" });
      new OpencodeAgentSettings(
        subagentsContainer,
        opencodeWorkspace.agentStorage,
        context.plugin.app,
        async () => {
          var _a3;
          await ((_a3 = opencodeWorkspace.refreshAgentMentions) == null ? void 0 : _a3.call(opencodeWorkspace));
          await recycleOpencodeRuntime();
        }
      );
    }
    renderEnvironmentSettingsSection({
      container,
      plugin: context.plugin,
      scope: "provider:opencode",
      heading: "Environment",
      name: "Environment Variables",
      desc: "Extra environment variables passed to OpenCode. `OPENCODE_ENABLE_EXA=1` is enabled by default.",
      placeholder: `${OPENCODE_DEFAULT_ENVIRONMENT_VARIABLES}
OPENCODE_DB=/path/to/opencode.db`,
      renderCustomContextLimits: (target) => context.renderCustomContextLimits(target, "opencode")
    });
  }
};
function buildEnrichedModels(discoveredModels, visibleModels) {
  var _a3;
  const enriched = [];
  const discoveredIds = /* @__PURE__ */ new Set();
  const baseModels = buildOpencodeBaseModels(discoveredModels);
  for (const model of baseModels) {
    const { modelLabel, providerLabel } = splitOpencodeModelLabel(model.label || model.rawId);
    discoveredIds.add(model.rawId);
    enriched.push({
      description: (_a3 = model.description) != null ? _a3 : "",
      isAvailable: true,
      modelLabel,
      providerKey: providerLabel.toLowerCase(),
      providerLabel,
      rawId: model.rawId
    });
  }
  for (const rawId of visibleModels) {
    if (discoveredIds.has(rawId)) {
      continue;
    }
    const { modelLabel, providerLabel } = splitOpencodeModelLabel(rawId);
    enriched.push({
      description: "",
      isAvailable: false,
      modelLabel,
      providerKey: providerLabel.toLowerCase(),
      providerLabel,
      rawId
    });
  }
  return enriched.sort((left, right) => {
    const providerCmp = left.providerLabel.localeCompare(right.providerLabel);
    if (providerCmp !== 0) {
      return providerCmp;
    }
    return left.modelLabel.localeCompare(right.modelLabel);
  });
}

// src/providers/opencode/runtime/OpencodeChatRuntime.ts
var fs21 = __toESM(require("node:fs/promises"));
var path19 = __toESM(require("node:path"));
init_env();
init_path();

// src/providers/acp/AcpJsonRpcTransport.ts
var import_node_readline = require("node:readline");
var DEFAULT_TIMEOUT_MS2 = 3e4;
var JsonRpcTransportClosedError = class extends Error {
  constructor(message = "JSON-RPC transport closed") {
    super(message);
    this.name = "JsonRpcTransportClosedError";
  }
};
var JsonRpcErrorResponse = class extends Error {
  constructor(method, code, message, data) {
    super(message);
    this.method = method;
    this.code = code;
    this.data = data;
    this.name = "JsonRpcErrorResponse";
  }
};
var AcpJsonRpcTransport = class {
  constructor(streams, defaultTimeoutMs = DEFAULT_TIMEOUT_MS2) {
    this.streams = streams;
    this.defaultTimeoutMs = defaultTimeoutMs;
    this.abortController = new AbortController();
    this.closeListeners = /* @__PURE__ */ new Set();
    this.disposed = false;
    this.nextId = 1;
    this.notificationHandlers = /* @__PURE__ */ new Map();
    this.pending = /* @__PURE__ */ new Map();
    this.readline = null;
    this.requestHandlers = /* @__PURE__ */ new Map();
  }
  get signal() {
    return this.abortController.signal;
  }
  get isClosed() {
    return this.disposed;
  }
  start() {
    var _a3, _b2;
    if (this.readline || this.disposed) {
      return;
    }
    this.readline = (0, import_node_readline.createInterface)({
      crlfDelay: Infinity,
      input: this.streams.input
    });
    this.readline.on("line", (line) => this.handleLine(line));
    this.readline.on("close", () => {
      if (!this.disposed) {
        this.dispose(new JsonRpcTransportClosedError("JSON-RPC input closed"));
      }
    });
    this.unregisterClose = (_b2 = (_a3 = this.streams).onClose) == null ? void 0 : _b2.call(_a3, (error48) => {
      if (!this.disposed) {
        this.dispose(error48 != null ? error48 : new JsonRpcTransportClosedError());
      }
    });
  }
  onClose(listener) {
    this.closeListeners.add(listener);
    return () => {
      this.closeListeners.delete(listener);
    };
  }
  onNotification(method, handler) {
    let handlers = this.notificationHandlers.get(method);
    if (!handlers) {
      handlers = /* @__PURE__ */ new Set();
      this.notificationHandlers.set(method, handlers);
    }
    handlers.add(handler);
    return () => {
      const current = this.notificationHandlers.get(method);
      if (!current) return;
      current.delete(handler);
      if (current.size === 0) {
        this.notificationHandlers.delete(method);
      }
    };
  }
  onRequest(method, handler) {
    this.requestHandlers.set(method, handler);
    return () => {
      if (this.requestHandlers.get(method) === handler) {
        this.requestHandlers.delete(method);
      }
    };
  }
  async request(method, params, options = {}) {
    var _a3;
    this.start();
    if (this.disposed) {
      throw new JsonRpcTransportClosedError();
    }
    const id = this.nextId++;
    const timeoutMs = (_a3 = options.timeoutMs) != null ? _a3 : this.defaultTimeoutMs;
    return new Promise((resolve8, reject) => {
      let timer;
      let onAbort;
      const cleanup = () => {
        if (timer) clearTimeout(timer);
        if (onAbort && options.signal) {
          options.signal.removeEventListener("abort", onAbort);
        }
      };
      const pending = {
        cleanup,
        method,
        reject,
        resolve: resolve8
      };
      if (timeoutMs > 0) {
        timer = setTimeout(() => {
          this.pending.delete(id);
          cleanup();
          reject(new Error(`Request timeout: ${method} (${timeoutMs}ms)`));
        }, timeoutMs);
      }
      if (options.signal) {
        if (options.signal.aborted) {
          cleanup();
          reject(new Error(`Request aborted: ${method}`));
          return;
        }
        onAbort = () => {
          this.pending.delete(id);
          cleanup();
          reject(new Error(`Request aborted: ${method}`));
        };
        options.signal.addEventListener("abort", onAbort, { once: true });
      }
      this.pending.set(id, pending);
      try {
        this.sendRaw({ id, jsonrpc: "2.0", method, params });
      } catch (error48) {
        this.pending.delete(id);
        cleanup();
        reject(error48 instanceof Error ? error48 : new Error(String(error48)));
      }
    });
  }
  notify(method, params) {
    this.start();
    if (this.disposed) {
      return;
    }
    this.sendRaw({ jsonrpc: "2.0", method, params });
  }
  dispose(error48 = new JsonRpcTransportClosedError("JSON-RPC transport disposed")) {
    var _a3;
    if (this.disposed) {
      return;
    }
    this.disposed = true;
    this.abortController.abort();
    (_a3 = this.unregisterClose) == null ? void 0 : _a3.call(this);
    this.unregisterClose = void 0;
    if (this.readline) {
      this.readline.removeAllListeners();
      this.readline.close();
      this.readline = null;
    }
    for (const [id, pending] of this.pending) {
      pending.cleanup();
      pending.reject(error48);
      this.pending.delete(id);
    }
    for (const listener of this.closeListeners) {
      try {
        listener(error48);
      } catch (e2) {
      }
    }
  }
  handleLine(line) {
    if (line.trim().length === 0) {
      return;
    }
    let message;
    try {
      message = JSON.parse(line);
    } catch (e2) {
      return;
    }
    if ("id" in message && !("method" in message)) {
      this.handleResponse(message);
      return;
    }
    if ("method" in message && "id" in message) {
      this.handleRequest(message);
      return;
    }
    if ("method" in message) {
      this.handleNotification(message);
    }
  }
  handleResponse(message) {
    if (typeof message.id !== "number") {
      return;
    }
    const pending = this.pending.get(message.id);
    if (!pending) {
      return;
    }
    this.pending.delete(message.id);
    pending.cleanup();
    if (message.error) {
      pending.reject(new JsonRpcErrorResponse(
        pending.method,
        message.error.code,
        message.error.message,
        message.error.data
      ));
      return;
    }
    pending.resolve(message.result);
  }
  handleNotification(message) {
    const handlers = this.notificationHandlers.get(message.method);
    if (!handlers || handlers.size === 0) {
      return;
    }
    for (const handler of handlers) {
      void Promise.resolve(handler(message.params)).catch(() => {
      });
    }
  }
  handleRequest(message) {
    const handler = this.requestHandlers.get(message.method);
    if (!handler) {
      this.sendRaw({
        error: {
          code: -32601,
          message: `Unhandled server request: ${message.method}`
        },
        id: message.id,
        jsonrpc: "2.0"
      });
      return;
    }
    void Promise.resolve(handler(message.params)).then(
      (result) => {
        this.sendRaw({ id: message.id, jsonrpc: "2.0", result });
      },
      (error48) => {
        this.sendRaw({
          error: {
            code: -32603,
            message: error48 instanceof Error ? error48.message : "Internal error"
          },
          id: message.id,
          jsonrpc: "2.0"
        });
      }
    );
  }
  sendRaw(message) {
    if (this.disposed) {
      throw new JsonRpcTransportClosedError();
    }
    this.streams.output.write(`${JSON.stringify(message)}
`);
  }
};

// src/providers/acp/methodNames.ts
var ACP_METHOD_CANDIDATES = {
  authenticate: ["authenticate"],
  cancel: ["session/cancel", "cancel"],
  initialize: ["initialize"],
  listSessions: ["session/list", "listSessions"],
  loadSession: ["session/load", "loadSession"],
  newSession: ["session/new", "newSession"],
  prompt: ["session/prompt", "prompt"],
  setConfigOption: ["session/set_config_option", "setSessionConfigOption"],
  setMode: ["session/set_mode", "setSessionMode"]
};
var ACP_SERVER_NOTIFICATION_ALIASES = {
  sessionUpdate: ["session/update", "sessionUpdate"]
};
var ACP_SERVER_REQUEST_ALIASES = {
  createTerminal: ["terminal/create", "terminalCreate"],
  killTerminal: ["terminal/kill", "terminalKill"],
  readTextFile: ["fs/read_text_file", "fs/readTextFile"],
  releaseTerminal: ["terminal/release", "terminalRelease"],
  requestPermission: ["session/request_permission", "requestPermission"],
  terminalOutput: ["terminal/output", "terminalOutput"],
  waitForTerminalExit: ["terminal/wait_for_exit", "terminalWaitForExit"],
  writeTextFile: ["fs/write_text_file", "fs/writeTextFile"]
};
function getAcpMethodCandidates(logicalMethod, overrides) {
  const override = overrides == null ? void 0 : overrides[logicalMethod];
  if (override) {
    return Array.isArray(override) ? [...override] : [override];
  }
  return [...ACP_METHOD_CANDIDATES[logicalMethod]];
}

// src/providers/acp/AcpClientConnection.ts
var ACP_PROMPT_TURN_TIMEOUT_MS = 0;
var AcpClientConnection = class {
  constructor(options) {
    this.options = options;
    this.agentInfo = null;
    this.agentCapabilities = null;
    this.authMethods = null;
    this.methodCache = /* @__PURE__ */ new Map();
    this.sessionNotificationListeners = /* @__PURE__ */ new Set();
    this.unsubscribeHandlers = [];
    this.registerServerHandlers();
  }
  get signal() {
    return this.options.transport.signal;
  }
  get negotiatedAgentInfo() {
    return this.agentInfo;
  }
  get negotiatedAgentCapabilities() {
    return this.agentCapabilities;
  }
  get negotiatedAuthMethods() {
    return this.authMethods;
  }
  onSessionNotification(listener) {
    this.sessionNotificationListeners.add(listener);
    return () => {
      this.sessionNotificationListeners.delete(listener);
    };
  }
  dispose() {
    var _a3;
    while (this.unsubscribeHandlers.length > 0) {
      (_a3 = this.unsubscribeHandlers.pop()) == null ? void 0 : _a3();
    }
    this.sessionNotificationListeners.clear();
  }
  async initialize(partialRequest = {}) {
    var _a3, _b2, _c, _d2, _e, _f;
    const request = {
      clientCapabilities: mergeCapabilities2(
        this.buildClientCapabilities(),
        partialRequest.clientCapabilities
      ),
      clientInfo: (_b2 = (_a3 = partialRequest.clientInfo) != null ? _a3 : this.options.clientInfo) != null ? _b2 : null,
      protocolVersion: (_c = partialRequest.protocolVersion) != null ? _c : 1
    };
    const response = await this.requestWithFallback("initialize", request);
    this.agentInfo = (_d2 = response.agentInfo) != null ? _d2 : null;
    this.agentCapabilities = (_e = response.agentCapabilities) != null ? _e : null;
    this.authMethods = (_f = response.authMethods) != null ? _f : null;
    return response;
  }
  authenticate(request) {
    return this.requestWithFallback("authenticate", request);
  }
  newSession(request) {
    return this.requestWithFallback("newSession", request);
  }
  loadSession(request) {
    return this.requestWithFallback("loadSession", request);
  }
  listSessions(request = {}) {
    return this.requestWithFallback("listSessions", request);
  }
  prompt(request) {
    return this.requestWithFallback("prompt", request, {
      timeoutMs: ACP_PROMPT_TURN_TIMEOUT_MS
    });
  }
  cancel(notification) {
    this.notifyLogicalMethod("cancel", notification, { sendAllCandidatesIfUncached: true });
  }
  setMode(request) {
    return this.requestWithFallback("setMode", request);
  }
  setConfigOption(request) {
    return this.requestWithFallback("setConfigOption", request);
  }
  buildClientCapabilities() {
    var _a3, _b2;
    const capabilities = { ...this.options.clientCapabilities };
    const fileSystem = (_a3 = this.options.delegate) == null ? void 0 : _a3.fileSystem;
    const terminal = (_b2 = this.options.delegate) == null ? void 0 : _b2.terminal;
    if ((fileSystem == null ? void 0 : fileSystem.readTextFile) || (fileSystem == null ? void 0 : fileSystem.writeTextFile)) {
      capabilities.fs = {
        ...capabilities.fs,
        ...fileSystem.readTextFile ? { readTextFile: true } : {},
        ...fileSystem.writeTextFile ? { writeTextFile: true } : {}
      };
    }
    if (terminal) {
      capabilities.terminal = true;
    }
    return Object.keys(capabilities).length === 0 ? void 0 : capabilities;
  }
  registerServerHandlers() {
    const transport = this.options.transport;
    const delegate = this.options.delegate;
    const subscribeNotification = (aliases, handler) => {
      for (const alias of aliases) {
        this.unsubscribeHandlers.push(transport.onNotification(alias, handler));
      }
    };
    const subscribeRequest = (aliases, handler) => {
      for (const alias of aliases) {
        this.unsubscribeHandlers.push(transport.onRequest(alias, handler));
      }
    };
    subscribeNotification(
      ACP_SERVER_NOTIFICATION_ALIASES.sessionUpdate,
      async (params) => this.dispatchSessionNotification(params)
    );
    if (delegate == null ? void 0 : delegate.requestPermission) {
      const requestPermission = delegate.requestPermission;
      subscribeRequest(
        ACP_SERVER_REQUEST_ALIASES.requestPermission,
        (params) => requestPermission(params)
      );
    }
    const fileSystem = delegate == null ? void 0 : delegate.fileSystem;
    if (fileSystem == null ? void 0 : fileSystem.readTextFile) {
      const readTextFile = fileSystem.readTextFile;
      subscribeRequest(
        ACP_SERVER_REQUEST_ALIASES.readTextFile,
        (params) => readTextFile(params)
      );
    }
    if (fileSystem == null ? void 0 : fileSystem.writeTextFile) {
      const writeTextFile = fileSystem.writeTextFile;
      subscribeRequest(
        ACP_SERVER_REQUEST_ALIASES.writeTextFile,
        (params) => writeTextFile(params)
      );
    }
    const terminal = delegate == null ? void 0 : delegate.terminal;
    if (terminal) {
      subscribeRequest(
        ACP_SERVER_REQUEST_ALIASES.createTerminal,
        (params) => terminal.createTerminal(params)
      );
      subscribeRequest(
        ACP_SERVER_REQUEST_ALIASES.terminalOutput,
        (params) => terminal.terminalOutput(params)
      );
      subscribeRequest(
        ACP_SERVER_REQUEST_ALIASES.waitForTerminalExit,
        (params) => terminal.waitForTerminalExit(params)
      );
      subscribeRequest(
        ACP_SERVER_REQUEST_ALIASES.killTerminal,
        (params) => terminal.killTerminal(params)
      );
      subscribeRequest(
        ACP_SERVER_REQUEST_ALIASES.releaseTerminal,
        (params) => terminal.releaseTerminal(params)
      );
    }
  }
  async dispatchSessionNotification(notification) {
    var _a3;
    if ((_a3 = this.options.delegate) == null ? void 0 : _a3.onSessionNotification) {
      await this.options.delegate.onSessionNotification(notification);
    }
    for (const listener of this.sessionNotificationListeners) {
      await listener(notification);
    }
  }
  // -32601 (Method not found) is the only error we absorb; agents that advertise legacy
  // method names only reject unknown candidates with it, so every other code is real.
  async requestWithFallback(logicalMethod, params, requestOptions) {
    const cachedMethod = this.methodCache.get(logicalMethod);
    if (cachedMethod) {
      return this.options.transport.request(cachedMethod, params, requestOptions);
    }
    const candidates = getAcpMethodCandidates(logicalMethod, this.options.methodOverrides);
    let lastError = null;
    for (const methodName of candidates) {
      try {
        const result = await this.options.transport.request(methodName, params, requestOptions);
        this.methodCache.set(logicalMethod, methodName);
        return result;
      } catch (error48) {
        if (!(error48 instanceof JsonRpcErrorResponse) || error48.code !== -32601) {
          throw error48;
        }
        lastError = error48;
      }
    }
    if (lastError) {
      throw lastError;
    }
    throw new Error(`No ACP method candidates configured for ${logicalMethod}`);
  }
  notifyLogicalMethod(logicalMethod, params, options = {}) {
    const cachedMethod = this.methodCache.get(logicalMethod);
    if (cachedMethod) {
      this.options.transport.notify(cachedMethod, params);
      return;
    }
    const candidates = getAcpMethodCandidates(logicalMethod, this.options.methodOverrides);
    const methodNames = options.sendAllCandidatesIfUncached ? Array.from(new Set(candidates)) : candidates.slice(0, 1);
    for (const methodName of methodNames) {
      this.options.transport.notify(methodName, params);
    }
  }
};
function mergeCapabilities2(base, override) {
  if (!base && !override) {
    return void 0;
  }
  const merged = { ...base, ...override };
  if ((base == null ? void 0 : base.auth) || (override == null ? void 0 : override.auth)) {
    merged.auth = { ...base == null ? void 0 : base.auth, ...override == null ? void 0 : override.auth };
  }
  if ((base == null ? void 0 : base.fs) || (override == null ? void 0 : override.fs)) {
    merged.fs = { ...base == null ? void 0 : base.fs, ...override == null ? void 0 : override.fs };
  }
  return Object.keys(merged).length === 0 ? void 0 : merged;
}

// src/providers/acp/AcpSessionConfig.ts
function flattenAcpSessionConfigSelectOptions(options) {
  if (options.length === 0) {
    return [];
  }
  if (isSelectGroup(options[0])) {
    return options.flatMap((group) => group.options);
  }
  return options;
}
function extractAcpSessionModelState(params) {
  var _a3, _b2, _c, _d2;
  const { items, current } = resolveSelectItems(params.configOptions, "model");
  if (items) {
    return { availableModels: items, currentModelId: current };
  }
  return {
    availableModels: (_b2 = (_a3 = params.models) == null ? void 0 : _a3.availableModels) != null ? _b2 : [],
    currentModelId: (_d2 = (_c = params.models) == null ? void 0 : _c.currentModelId) != null ? _d2 : current
  };
}
function extractAcpSessionModeState(params) {
  var _a3, _b2, _c, _d2;
  const { items, current } = resolveSelectItems(params.configOptions, "mode");
  if (items) {
    return { availableModes: items, currentModeId: current };
  }
  return {
    availableModes: (_b2 = (_a3 = params.modes) == null ? void 0 : _a3.availableModes) != null ? _b2 : [],
    currentModeId: (_d2 = (_c = params.modes) == null ? void 0 : _c.currentModeId) != null ? _d2 : current
  };
}
function resolveSelectItems(configOptions, category) {
  const selectOption = findSessionConfigSelectOption(configOptions, category);
  if (!selectOption) {
    return { current: null, items: null };
  }
  const items = flattenAcpSessionConfigSelectOptions(selectOption.options).map((option) => ({
    ...option.description ? { description: option.description } : {},
    id: option.value,
    name: option.name
  }));
  return {
    current: selectOption.currentValue,
    items: items.length > 0 ? items : null
  };
}
function findSessionConfigSelectOption(configOptions, category) {
  if (!configOptions) {
    return null;
  }
  const byCategory = configOptions.find((option) => option.type === "select" && normalizeComparableKey(option.category) === category);
  if ((byCategory == null ? void 0 : byCategory.type) === "select") {
    return byCategory;
  }
  const byLegacyId = configOptions.find((option) => option.type === "select" && normalizeComparableKey(option.id) === category);
  return (byLegacyId == null ? void 0 : byLegacyId.type) === "select" ? byLegacyId : null;
}
function isSelectGroup(option) {
  return "options" in option;
}
function normalizeComparableKey(value) {
  return typeof value === "string" ? value.trim().toLowerCase() : "";
}

// src/providers/acp/AcpSessionUpdateNormalizer.ts
var ANONYMOUS_MESSAGE_KEY = "\0anonymous";
var AcpSessionUpdateNormalizer = class {
  constructor() {
    this.seenMessages = /* @__PURE__ */ new Map();
    this.toolCalls = /* @__PURE__ */ new Map();
  }
  reset() {
    this.seenMessages.clear();
    this.toolCalls.clear();
  }
  normalize(update) {
    switch (update.sessionUpdate) {
      case "user_message_chunk":
        return this.normalizeMessageChunk("user", update);
      case "agent_message_chunk":
        return this.normalizeMessageChunk("assistant", update);
      case "agent_thought_chunk":
        return this.normalizeMessageChunk("thinking", update);
      case "tool_call":
        return this.normalizeToolCall(update);
      case "tool_call_update":
        return this.normalizeToolCallUpdate(update);
      case "plan":
        return { plan: update, type: "plan" };
      case "available_commands_update":
        return {
          commands: update.availableCommands.map(mapAcpCommandToSlashCommand),
          type: "commands"
        };
      case "current_mode_update":
        return { currentModeId: update.currentModeId, type: "current_mode" };
      case "config_option_update":
        return { configOptions: update.configOptions, type: "config_options" };
      case "session_info_update":
        return {
          sessionInfo: { ...update, updatedAtMs: parseIsoDate(update.updatedAt) },
          type: "session_info"
        };
      case "usage_update":
        return { type: "usage", usage: update };
    }
  }
  normalizeMessageChunk(role, update) {
    var _a3, _b2, _c;
    const streamChunks = [];
    if (role === "user" && this.claimMessageStart("user", update.messageId)) {
      streamChunks.push({
        content: extractPrimaryText(update.content),
        itemId: (_a3 = update.messageId) != null ? _a3 : void 0,
        type: "user_message_start"
      });
    } else if (role === "assistant" && this.claimMessageStart("assistant", update.messageId)) {
      streamChunks.push({
        itemId: (_b2 = update.messageId) != null ? _b2 : void 0,
        type: "assistant_message_start"
      });
    }
    const text = renderAcpContentBlock(update.content);
    if (text && role === "thinking") {
      streamChunks.push({ content: text, type: "thinking" });
    } else if (text && role === "assistant") {
      streamChunks.push({ content: text, type: "text" });
    }
    return {
      content: update.content,
      messageId: (_c = update.messageId) != null ? _c : null,
      role,
      streamChunks,
      type: "message_chunk"
    };
  }
  normalizeToolCall(toolCall) {
    const toolState = {
      input: normalizeToolInput2(toolCall.rawInput),
      name: normalizeToolName(toolCall.title, toolCall.kind),
      output: renderToolPayload(toolCall.content, toolCall.rawOutput),
      status: toolCall.status
    };
    this.toolCalls.set(toolCall.toolCallId, toolState);
    const streamChunks = [{
      id: toolCall.toolCallId,
      input: toolState.input,
      name: toolState.name,
      type: "tool_use"
    }];
    if (toolState.status === "completed" || toolState.status === "failed") {
      streamChunks.push({
        content: toolState.output || defaultToolResultText(toolState.status),
        id: toolCall.toolCallId,
        isError: toolState.status === "failed",
        type: "tool_result"
      });
    }
    return { streamChunks, toolCall, toolState, type: "tool_call" };
  }
  normalizeToolCallUpdate(toolCallUpdate) {
    var _a3, _b2, _c;
    const current = (_a3 = this.toolCalls.get(toolCallUpdate.toolCallId)) != null ? _a3 : {
      input: {},
      name: "tool",
      output: "",
      status: null
    };
    if (toolCallUpdate.title) {
      current.name = normalizeToolName(toolCallUpdate.title, (_b2 = toolCallUpdate.kind) != null ? _b2 : null);
    } else if (toolCallUpdate.kind && current.name === "tool") {
      current.name = normalizeToolName(void 0, toolCallUpdate.kind);
    }
    if (toolCallUpdate.rawInput !== void 0) {
      current.input = normalizeToolInput2(toolCallUpdate.rawInput);
    }
    const nextOutput = renderToolPayload((_c = toolCallUpdate.content) != null ? _c : void 0, toolCallUpdate.rawOutput) || current.output;
    const streamChunks = [];
    if (nextOutput.length > current.output.length && nextOutput.startsWith(current.output)) {
      streamChunks.push({
        content: nextOutput.slice(current.output.length),
        id: toolCallUpdate.toolCallId,
        type: "tool_output"
      });
    }
    current.output = nextOutput;
    if (toolCallUpdate.status !== void 0) {
      current.status = toolCallUpdate.status;
    }
    if (current.status === "completed" || current.status === "failed") {
      streamChunks.push({
        content: current.output || defaultToolResultText(current.status),
        id: toolCallUpdate.toolCallId,
        isError: current.status === "failed",
        type: "tool_result"
      });
    }
    this.toolCalls.set(toolCallUpdate.toolCallId, current);
    return {
      streamChunks,
      toolCallUpdate,
      toolState: { ...current },
      type: "tool_call_update"
    };
  }
  // A message-start chunk must fire exactly once per (role, messageId). Anonymous streams
  // share a single slot per role so repeated chunks without an id do not restart the message.
  claimMessageStart(role, messageId) {
    const key = messageId != null ? messageId : ANONYMOUS_MESSAGE_KEY;
    let seen = this.seenMessages.get(role);
    if (!seen) {
      seen = /* @__PURE__ */ new Set();
      this.seenMessages.set(role, seen);
    }
    if (seen.has(key)) {
      return false;
    }
    seen.add(key);
    return true;
  }
};
function mapAcpCommandToSlashCommand(command) {
  var _a3, _b2, _c;
  const name = command.name.replace(/^\//, "");
  return {
    argumentHint: (_b2 = (_a3 = command.input) == null ? void 0 : _a3.hint) != null ? _b2 : void 0,
    content: "",
    description: (_c = command.description) != null ? _c : void 0,
    id: `acp:${name}`,
    name,
    source: "sdk"
  };
}
function normalizeToolName(title, kind) {
  return (title == null ? void 0 : title.trim()) || (kind == null ? void 0 : kind.trim()) || "tool";
}
function normalizeToolInput2(rawInput) {
  if (isPlainObject3(rawInput)) {
    return rawInput;
  }
  if (rawInput === void 0) {
    return {};
  }
  return { value: rawInput };
}
function renderToolPayload(content, rawOutput) {
  if (Array.isArray(content) && content.length > 0) {
    return content.map(renderToolCallContent).filter((text) => text.length > 0).join("\n\n");
  }
  return rawOutput === void 0 ? "" : formatUnknownValue(rawOutput);
}
function renderToolCallContent(content) {
  switch (content.type) {
    case "content":
      return renderAcpContentBlock(content.content);
    case "diff":
      return `Diff: ${content.path}`;
    case "terminal":
      return `Terminal: ${content.terminalId}`;
  }
}
function defaultToolResultText(status) {
  return status === "failed" ? "Tool failed" : "Tool completed";
}
function extractPrimaryText(content) {
  if (content.type === "text") {
    return content.text;
  }
  if (content.type === "resource" && "text" in content.resource) {
    return content.resource.text;
  }
  return "";
}
function renderAcpContentBlock(content) {
  switch (content.type) {
    case "text":
      return content.text;
    case "image":
      return content.uri ? `[image: ${content.uri}]` : `[image: ${content.mimeType}]`;
    case "audio":
      return `[audio: ${content.mimeType}]`;
    case "resource_link":
      return content.title || content.name || content.uri;
    case "resource":
      return "text" in content.resource ? content.resource.text : `[resource: ${content.resource.uri}]`;
  }
}
function formatUnknownValue(value) {
  if (typeof value === "string") {
    return value;
  }
  if (value === null) {
    return "null";
  }
  if (value === void 0) {
    return "";
  }
  if (typeof value === "number" || typeof value === "boolean") {
    return String(value);
  }
  try {
    return JSON.stringify(value, null, 2);
  } catch (e2) {
    return String(value);
  }
}
function isPlainObject3(value) {
  return Boolean(value) && typeof value === "object" && !Array.isArray(value);
}
function parseIsoDate(value) {
  if (value === void 0) {
    return void 0;
  }
  if (value === null) {
    return null;
  }
  const timestamp = Date.parse(value);
  return Number.isNaN(timestamp) ? null : timestamp;
}

// src/providers/acp/AcpSubprocess.ts
var import_node_child_process = require("node:child_process");
var SIGKILL_TIMEOUT_MS2 = 3e3;
var STDERR_BUFFER_LIMIT = 8e3;
var AcpSubprocess = class {
  constructor(launchSpec) {
    this.launchSpec = launchSpec;
    this.closeError = null;
    this.closeListeners = /* @__PURE__ */ new Set();
    this.notifiedClose = false;
    this.proc = null;
    this.stderrBuffer = "";
  }
  get stdin() {
    return this.requireProc().stdin;
  }
  get stdout() {
    return this.requireProc().stdout;
  }
  get stderr() {
    return this.requireProc().stderr;
  }
  requireProc() {
    if (!this.proc) {
      throw new Error("ACP subprocess is not started");
    }
    return this.proc;
  }
  start() {
    if (this.proc) {
      return;
    }
    const proc = (0, import_node_child_process.spawn)(this.launchSpec.command, this.launchSpec.args, {
      cwd: this.launchSpec.cwd,
      env: this.launchSpec.env,
      stdio: "pipe",
      windowsHide: true
    });
    proc.stderr.on("data", (chunk) => {
      const text = typeof chunk === "string" ? chunk : chunk.toString("utf-8");
      this.stderrBuffer = `${this.stderrBuffer}${text}`.slice(-STDERR_BUFFER_LIMIT);
    });
    proc.on("error", (error48) => {
      this.closeError = error48;
      this.notifyClose(error48);
    });
    proc.on("exit", (code, signal) => {
      var _a3;
      const exitError = (_a3 = this.closeError) != null ? _a3 : code === 0 && signal === null ? void 0 : new Error(`ACP subprocess exited (${formatExit(code, signal)})`);
      this.notifyClose(exitError);
    });
    this.proc = proc;
  }
  isAlive() {
    return this.proc !== null && this.proc.exitCode === null && !this.proc.killed;
  }
  getStderrSnapshot() {
    return this.stderrBuffer.trim();
  }
  onClose(listener) {
    this.closeListeners.add(listener);
    return () => {
      this.closeListeners.delete(listener);
    };
  }
  async shutdown() {
    if (!this.proc || this.proc.exitCode !== null) {
      return;
    }
    await new Promise((resolve8) => {
      const proc = this.proc;
      const onClose = () => {
        cleanup();
        resolve8();
      };
      const killTimer = setTimeout(() => {
        proc.kill("SIGKILL");
      }, SIGKILL_TIMEOUT_MS2);
      const cleanup = () => {
        clearTimeout(killTimer);
        proc.off("exit", onClose);
      };
      proc.once("exit", onClose);
      proc.kill("SIGTERM");
    });
  }
  notifyClose(error48) {
    if (this.notifiedClose) {
      return;
    }
    this.notifiedClose = true;
    for (const listener of this.closeListeners) {
      try {
        listener(error48);
      } catch (e2) {
      }
    }
  }
};
function formatExit(code, signal) {
  if (signal) {
    return `signal ${signal}`;
  }
  if (code === null) {
    return "unknown";
  }
  return `code ${code}`;
}

// src/providers/acp/AcpToolStreamAdapter.ts
var AcpToolStreamAdapter = class {
  constructor(adapter) {
    this.adapter = adapter;
    this.toolStates = /* @__PURE__ */ new Map();
  }
  reset() {
    this.toolStates.clear();
  }
  normalizeToolCall(toolCall, chunks) {
    const state = this.updateToolState(void 0, {
      kind: toolCall.kind,
      rawInput: toolCall.rawInput,
      title: toolCall.title
    });
    this.toolStates.set(toolCall.toolCallId, state);
    return chunks.map((chunk) => this.normalizeChunk(chunk, state, toolCall.rawOutput));
  }
  normalizeToolCallUpdate(toolCallUpdate, chunks) {
    const state = this.updateToolState(this.toolStates.get(toolCallUpdate.toolCallId), {
      kind: toolCallUpdate.kind,
      rawInput: toolCallUpdate.rawInput,
      title: toolCallUpdate.title
    });
    this.toolStates.set(toolCallUpdate.toolCallId, state);
    const result = [];
    if (toolCallUpdate.rawInput !== void 0) {
      result.push({
        id: toolCallUpdate.toolCallId,
        input: state.input,
        name: this.adapter.normalizeToolName(state.rawName),
        type: "tool_use"
      });
    }
    for (const chunk of chunks) {
      result.push(this.normalizeChunk(chunk, state, toolCallUpdate.rawOutput));
    }
    return result;
  }
  updateToolState(current, update) {
    var _a3;
    const nextRawName = this.adapter.resolveRawToolName(current == null ? void 0 : current.rawName, update);
    const nextInput = (_a3 = current == null ? void 0 : current.input) != null ? _a3 : {};
    if (update.rawInput !== void 0) {
      const rawInput = normalizeRawToolInput(update.rawInput);
      return this.buildToolState(nextRawName, { ...nextInput, ...rawInput });
    }
    if (nextRawName !== (current == null ? void 0 : current.rawName)) {
      return this.buildToolState(nextRawName, nextInput);
    }
    return current != null ? current : this.buildToolState(nextRawName, {});
  }
  buildToolState(rawName, input) {
    return {
      input: this.adapter.normalizeToolInput(rawName, input),
      rawName
    };
  }
  normalizeChunk(chunk, state, rawOutput) {
    switch (chunk.type) {
      case "tool_use":
        return {
          ...chunk,
          input: state.input,
          name: this.adapter.normalizeToolName(state.rawName)
        };
      case "tool_result": {
        const toolUseResult = this.adapter.normalizeToolUseResult(state.rawName, state.input, rawOutput);
        return toolUseResult ? { ...chunk, toolUseResult } : chunk;
      }
      default:
        return chunk;
    }
  }
};
function normalizeRawToolInput(rawInput) {
  return rawInput && typeof rawInput === "object" && !Array.isArray(rawInput) ? rawInput : {};
}

// src/providers/acp/buildAcpUsageInfo.ts
function buildAcpUsageInfo(params) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h;
  const promptUsage = (_a3 = params.promptUsage) != null ? _a3 : null;
  const contextWindow = (_b2 = params.contextWindow) != null ? _b2 : null;
  if (!promptUsage && !contextWindow) {
    return null;
  }
  const contextTokens = (_d2 = (_c = contextWindow == null ? void 0 : contextWindow.used) != null ? _c : promptUsage == null ? void 0 : promptUsage.totalTokens) != null ? _d2 : 0;
  const contextWindowSize = (_e = contextWindow == null ? void 0 : contextWindow.size) != null ? _e : 0;
  return {
    cacheCreationInputTokens: (_f = promptUsage == null ? void 0 : promptUsage.cachedWriteTokens) != null ? _f : 0,
    cacheReadInputTokens: (_g = promptUsage == null ? void 0 : promptUsage.cachedReadTokens) != null ? _g : 0,
    contextTokens,
    contextWindow: contextWindowSize,
    // Only the contextWindow update speaks authoritatively about window size; falling back
    // to promptUsage alone is a best-effort approximation.
    contextWindowIsAuthoritative: Boolean(contextWindow),
    inputTokens: (_h = promptUsage == null ? void 0 : promptUsage.inputTokens) != null ? _h : 0,
    model: params.model,
    percentage: computePercentage(contextTokens, contextWindowSize)
  };
}
function computePercentage(used, total) {
  if (total <= 0) {
    return 0;
  }
  const ratio = Math.round(used / total * 100);
  return Math.min(100, Math.max(0, ratio));
}

// src/providers/opencode/capabilities.ts
var OPENCODE_PROVIDER_CAPABILITIES = Object.freeze({
  providerId: "opencode",
  supportsPersistentRuntime: true,
  supportsNativeHistory: true,
  supportsPlanMode: true,
  supportsRewind: false,
  supportsFork: false,
  supportsProviderCommands: true,
  supportsImageAttachments: true,
  supportsInstructionMode: true,
  supportsMcpTools: false,
  supportsTurnSteer: false,
  reasoningControl: "effort"
});

// src/providers/opencode/normalization/opencodeToolNormalization.ts
var TOOL_NAME_MAP2 = {
  bash: TOOL_BASH,
  edit: TOOL_EDIT,
  glob: TOOL_GLOB,
  grep: TOOL_GREP,
  question: TOOL_ASK_USER_QUESTION,
  read: TOOL_READ,
  skill: TOOL_SKILL,
  task: TOOL_TASK,
  todowrite: TOOL_TODO_WRITE,
  webfetch: TOOL_WEB_FETCH,
  websearch: TOOL_WEB_SEARCH,
  write: TOOL_WRITE
};
function isPlainObject4(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
function isKnownToolName(value) {
  if (typeof value !== "string") {
    return false;
  }
  return value.trim().toLowerCase() in TOOL_NAME_MAP2;
}
function toKnownToolName(value) {
  if (!value) {
    return null;
  }
  const normalized = value.trim().toLowerCase();
  return isKnownToolName(normalized) ? normalized : null;
}
function firstString(...values) {
  for (const value of values) {
    if (typeof value === "string") {
      return value;
    }
  }
  return void 0;
}
function firstTrimmedString(...values) {
  for (const value of values) {
    if (typeof value !== "string") {
      continue;
    }
    const trimmed = value.trim();
    if (trimmed.length > 0) {
      return trimmed;
    }
  }
  return void 0;
}
function firstNonEmptyString2(...values) {
  var _a3;
  return (_a3 = firstTrimmedString(...values)) != null ? _a3 : "";
}
function normalizeStringArray3(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  const uniqueValues = /* @__PURE__ */ new Set();
  for (const entry of value) {
    if (typeof entry !== "string") {
      continue;
    }
    const trimmed = entry.trim();
    if (!trimmed) {
      continue;
    }
    uniqueValues.add(trimmed);
  }
  return [...uniqueValues];
}
function normalizeQuestionOptions(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  return value.flatMap((option) => {
    if (typeof option === "string") {
      const label2 = option.trim();
      return label2 ? [{ description: "", label: label2 }] : [];
    }
    if (!isPlainObject4(option)) {
      return [];
    }
    const label = typeof option.label === "string" ? option.label.trim() : "";
    if (!label) {
      return [];
    }
    return [{
      description: typeof option.description === "string" ? option.description : "",
      label
    }];
  });
}
function normalizeQuestionItems(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  return value.map((item, index) => {
    var _a3, _b2;
    const record2 = isPlainObject4(item) ? item : {};
    const question = (_a3 = firstTrimmedString(record2.question)) != null ? _a3 : `Question ${index + 1}`;
    const header = (_b2 = firstTrimmedString(record2.header)) != null ? _b2 : `Q${index + 1}`;
    return {
      ...typeof record2.id === "string" && record2.id.trim() ? { id: record2.id } : {},
      header,
      multiSelect: record2.multiSelect === true || record2.multi_select === true || record2.multiple === true,
      options: normalizeQuestionOptions(record2.options),
      question
    };
  });
}
function normalizeTodoStatus(value) {
  switch (value) {
    case "completed":
    case "cancelled":
      return "completed";
    case "in_progress":
      return "in_progress";
    default:
      return "pending";
  }
}
function normalizeTodos(value) {
  if (!Array.isArray(value)) {
    return [];
  }
  return value.flatMap((item) => {
    var _a3;
    if (!isPlainObject4(item)) {
      return [];
    }
    const content = firstTrimmedString(item.content, item.title, item.description);
    if (!content) {
      return [];
    }
    return [{
      activeForm: (_a3 = firstTrimmedString(item.activeForm, item.active_form)) != null ? _a3 : content,
      content,
      ...typeof item.id === "string" ? { id: item.id } : {},
      status: normalizeTodoStatus(item.status)
    }];
  });
}
function normalizeQuestionAnswers(rawAnswers, questions) {
  if (!Array.isArray(rawAnswers) || questions.length === 0) {
    return void 0;
  }
  const answers = {};
  for (let index = 0; index < Math.min(rawAnswers.length, questions.length); index += 1) {
    const question = questions[index];
    const rawEntry = rawAnswers[index];
    if (!question) {
      continue;
    }
    const values = Array.isArray(rawEntry) ? rawEntry.filter((value) => typeof value === "string" && value.trim().length > 0) : typeof rawEntry === "string" && rawEntry.trim().length > 0 ? [rawEntry] : [];
    if (values.length === 0) {
      continue;
    }
    const normalizedValue = values.length === 1 ? values[0] : values;
    answers[question.question] = normalizedValue;
    if (question.id) {
      answers[question.id] = normalizedValue;
    }
  }
  return Object.keys(answers).length > 0 ? answers : void 0;
}
function extractToolMetadata(rawOutput) {
  if (!isPlainObject4(rawOutput)) {
    return null;
  }
  return isPlainObject4(rawOutput.metadata) ? rawOutput.metadata : null;
}
function resolveOpencodeRawToolName(currentRawName, update) {
  const titleName = firstTrimmedString(update.title);
  const knownTitleName = titleName && isKnownToolName(titleName) ? titleName.trim().toLowerCase() : void 0;
  if (knownTitleName) {
    return knownTitleName;
  }
  if (currentRawName) {
    return currentRawName;
  }
  switch (update.kind) {
    case "execute":
      return "bash";
    case "fetch":
      return "webfetch";
    case "read":
      return "read";
    default:
      return titleName != null ? titleName : "tool";
  }
}
function normalizeWebSearchInput2(input) {
  var _a3;
  const action = isPlainObject4(input.action) ? input.action : {};
  const queries = normalizeStringArray3((_a3 = action.queries) != null ? _a3 : input.queries);
  const query = firstNonEmptyString2(action.query, input.query, queries[0]);
  const url2 = firstNonEmptyString2(action.url, input.url);
  const pattern = firstNonEmptyString2(action.pattern, input.pattern);
  const explicitType = firstNonEmptyString2(action.type, input.actionType, input.action_type);
  const actionType = explicitType || (url2 && pattern ? "find_in_page" : url2 ? "open_page" : query || queries.length > 0 ? "search" : "");
  const normalized = {};
  if (actionType) {
    normalized.actionType = actionType;
  }
  if (query) {
    normalized.query = query;
  }
  if (queries.length > 0) {
    normalized.queries = queries;
  }
  if (url2) {
    normalized.url = url2;
  }
  if (pattern) {
    normalized.pattern = pattern;
  }
  return normalized;
}
function normalizeOpencodeToolName(rawName) {
  const knownName = toKnownToolName(rawName);
  if (!knownName) {
    return (rawName == null ? void 0 : rawName.trim()) || "tool";
  }
  return TOOL_NAME_MAP2[knownName];
}
function normalizeOpencodeToolInput(rawName, input) {
  const knownName = toKnownToolName(rawName);
  switch (knownName) {
    case "question":
      return { questions: normalizeQuestionItems(input.questions) };
    case "read":
      return {
        ...firstString(input.file_path, input.filePath) ? { file_path: firstString(input.file_path, input.filePath) } : {},
        ...typeof input.limit === "number" ? { limit: input.limit } : {},
        ...typeof input.offset === "number" ? { offset: input.offset } : {}
      };
    case "write":
      return {
        ...typeof input.content === "string" ? { content: input.content } : {},
        ...firstString(input.file_path, input.filePath) ? { file_path: firstString(input.file_path, input.filePath) } : {}
      };
    case "edit":
      return {
        ...firstString(input.file_path, input.filePath) ? { file_path: firstString(input.file_path, input.filePath) } : {},
        ...firstString(input.old_string, input.oldString) ? { old_string: firstString(input.old_string, input.oldString) } : {},
        ...firstString(input.new_string, input.newString) ? { new_string: firstString(input.new_string, input.newString) } : {},
        ...typeof input.replace_all === "boolean" ? { replace_all: input.replace_all } : typeof input.replaceAll === "boolean" ? { replace_all: input.replaceAll } : {}
      };
    case "task":
      return {
        ...firstTrimmedString(input.command) ? { command: firstTrimmedString(input.command) } : {},
        ...firstTrimmedString(input.description) ? { description: firstTrimmedString(input.description) } : {},
        ...firstTrimmedString(input.prompt) ? { prompt: firstTrimmedString(input.prompt) } : {},
        ...input.run_in_background === true || input.run_in_background === false ? { run_in_background: input.run_in_background } : {},
        ...firstTrimmedString(input.subagent_type) ? { subagent_type: firstTrimmedString(input.subagent_type) } : {},
        ...firstTrimmedString(input.task_id) ? { task_id: firstTrimmedString(input.task_id) } : {}
      };
    case "todowrite":
      return { todos: normalizeTodos(input.todos) };
    case "skill":
      return firstTrimmedString(input.skill, input.name) ? { skill: firstTrimmedString(input.skill, input.name) } : {};
    case "websearch":
      return normalizeWebSearchInput2(input);
    default:
      return input;
  }
}
function normalizeOpencodeToolUseResult(rawName, input, rawOutput) {
  const knownName = toKnownToolName(rawName);
  const metadata = extractToolMetadata(rawOutput);
  const normalized = {};
  if ((knownName === "write" || knownName === "edit") && firstString(input.file_path, input.filePath, metadata == null ? void 0 : metadata.filepath, metadata == null ? void 0 : metadata.filePath)) {
    normalized.filePath = firstString(input.file_path, input.filePath, metadata == null ? void 0 : metadata.filepath, metadata == null ? void 0 : metadata.filePath);
  }
  if (knownName === "question") {
    const questions = Array.isArray(input.questions) ? input.questions : [];
    const answers = normalizeQuestionAnswers(metadata == null ? void 0 : metadata.answers, questions);
    if (answers) {
      normalized.answers = answers;
    }
  }
  return Object.keys(normalized).length > 0 ? normalized : void 0;
}
function createOpencodeToolStreamAdapter() {
  return new AcpToolStreamAdapter({
    normalizeToolInput: normalizeOpencodeToolInput,
    normalizeToolName: normalizeOpencodeToolName,
    normalizeToolUseResult: normalizeOpencodeToolUseResult,
    resolveRawToolName: resolveOpencodeRawToolName
  });
}

// src/providers/opencode/types/index.ts
function getOpencodeState(providerState) {
  return providerState != null ? providerState : {};
}

// src/providers/opencode/runtime/buildOpencodePrompt.ts
function buildOpencodePromptText(request, conversationHistory = []) {
  let prompt = request.text;
  if (request.currentNotePath) {
    prompt = appendCurrentNote(prompt, request.currentNotePath);
  }
  if (request.editorSelection && request.editorSelection.mode !== "none") {
    prompt = appendEditorContext(prompt, request.editorSelection);
  }
  if (request.browserSelection) {
    prompt = appendBrowserContext(prompt, request.browserSelection);
  }
  if (request.canvasSelection) {
    prompt = appendCanvasContext(prompt, request.canvasSelection);
  }
  if (conversationHistory.length > 0) {
    const historyContext = buildContextFromHistory(conversationHistory);
    prompt = buildPromptWithHistoryContext(
      historyContext,
      prompt,
      prompt,
      conversationHistory
    );
  }
  return prompt;
}
function buildOpencodePromptBlocks(request, conversationHistory = []) {
  var _a3;
  const blocks = [
    { type: "text", text: buildOpencodePromptText(request, conversationHistory) }
  ];
  for (const image of (_a3 = request.images) != null ? _a3 : []) {
    if (!image.data) {
      continue;
    }
    blocks.push({
      data: image.data,
      mimeType: image.mediaType,
      type: "image"
    });
  }
  return blocks;
}

// src/providers/opencode/runtime/OpencodeLaunchArtifacts.ts
var fs20 = __toESM(require("node:fs/promises"));
var path18 = __toESM(require("node:path"));
init_path();

// src/providers/opencode/runtime/OpencodePaths.ts
var fs19 = __toESM(require("node:fs"));
var os11 = __toESM(require("node:os"));
var path17 = __toESM(require("node:path"));
var OPENCODE_APP_NAME = "opencode";
var DEFAULT_DATABASE_NAME = "opencode.db";
var DATABASE_NAME_PATTERN = /^opencode(?:-[a-z0-9._-]+)?\.db$/i;
function resolveOpencodeDataDir(env = process.env) {
  var _a3;
  const xdgDataHome = (_a3 = env.XDG_DATA_HOME) == null ? void 0 : _a3.trim();
  if (xdgDataHome) {
    return path17.join(xdgDataHome, OPENCODE_APP_NAME);
  }
  const home = env.HOME || os11.homedir();
  if (process.platform === "win32") {
    const appData = env.APPDATA || env.LOCALAPPDATA || path17.join(home, "AppData", "Roaming");
    return path17.join(appData, OPENCODE_APP_NAME);
  }
  return path17.join(home, ".local", "share", OPENCODE_APP_NAME);
}
function resolveOpencodeDatabasePath(env = process.env) {
  var _a3, _b2;
  const override = (_a3 = env.OPENCODE_DB) == null ? void 0 : _a3.trim();
  if (override) {
    if (override === ":memory:" || path17.isAbsolute(override)) {
      return override;
    }
    return path17.join(resolveOpencodeDataDir(env), override);
  }
  const candidates = getOpencodeDatabasePathCandidates(env);
  for (const candidate of candidates) {
    if (fs19.existsSync(candidate)) {
      return candidate;
    }
  }
  return (_b2 = candidates[0]) != null ? _b2 : null;
}
function resolveExistingOpencodeDatabasePath(preferredPath, env = process.env) {
  const preferred = preferredPath == null ? void 0 : preferredPath.trim();
  if (preferred) {
    if (preferred === ":memory:") {
      return preferred;
    }
    if (fs19.existsSync(preferred)) {
      return preferred;
    }
  }
  const resolved = resolveOpencodeDatabasePath(env);
  if (resolved && (resolved === ":memory:" || fs19.existsSync(resolved))) {
    return resolved;
  }
  return preferred != null ? preferred : resolved;
}
function getOpencodeDatabasePathCandidates(env) {
  const candidates = [];
  const seen = /* @__PURE__ */ new Set();
  const home = env.HOME || os11.homedir();
  const dataDirs = [
    resolveOpencodeDataDir(env),
    path17.join(home, "Library", "Application Support", OPENCODE_APP_NAME)
  ];
  for (const dataDir of dataDirs) {
    pushCandidate(candidates, seen, path17.join(dataDir, DEFAULT_DATABASE_NAME));
    try {
      const matches = fs19.readdirSync(dataDir).filter((entry) => DATABASE_NAME_PATTERN.test(entry)).sort((left, right) => {
        if (left === DEFAULT_DATABASE_NAME) return -1;
        if (right === DEFAULT_DATABASE_NAME) return 1;
        return left.localeCompare(right);
      });
      for (const entry of matches) {
        pushCandidate(candidates, seen, path17.join(dataDir, entry));
      }
    } catch (e2) {
    }
  }
  return candidates;
}
function pushCandidate(candidates, seen, candidate) {
  if (seen.has(candidate)) {
    return;
  }
  seen.add(candidate);
  candidates.push(candidate);
}

// src/providers/opencode/runtime/OpencodeLaunchArtifacts.ts
var DEFAULT_OPENCODE_MANAGED_AGENT_CONFIGS = [
  { id: OPENCODE_BUILD_MODE_ID },
  {
    definition: {
      mode: "primary",
      permission: {
        plan_enter: "allow",
        question: "allow"
      }
    },
    id: OPENCODE_YOLO_MODE_ID
  },
  {
    definition: {
      mode: "primary",
      permission: {
        plan_enter: "allow",
        question: "allow",
        bash: "ask",
        edit: "ask"
      }
    },
    id: OPENCODE_SAFE_MODE_ID
  },
  { id: OPENCODE_PLAN_MODE_ID }
];
async function prepareOpencodeLaunchArtifacts(params) {
  var _a3, _b2, _c, _d2, _e, _f, _g;
  const artifactsDir = path18.join(
    params.workspaceRoot,
    CLAUDIAN_STORAGE_PATH,
    (_a3 = params.artifactsSubdir) != null ? _a3 : "opencode"
  );
  const systemPromptPath = path18.join(artifactsDir, "system.md");
  const configPath = path18.join(artifactsDir, "config.json");
  const systemPrompt = normalizeSystemPrompt(
    (_b2 = params.systemPromptText) != null ? _b2 : buildSystemPrompt(requireSettings(params))
  );
  const promptKey = (_c = params.systemPromptKey) != null ? _c : params.systemPromptText !== void 0 ? params.systemPromptText : computeSystemPromptKey(requireSettings(params));
  const baseConfig = await loadOpencodeBaseConfig(
    params.runtimeEnv.OPENCODE_CONFIG,
    params.workspaceRoot
  );
  const configContent = `${JSON.stringify(
    buildOpencodeManagedConfig(
      baseConfig,
      systemPromptPath,
      (_e = params.userName) != null ? _e : (_d2 = params.settings) == null ? void 0 : _d2.userName,
      params.managedAgents,
      params.defaultAgentId
    ),
    null,
    2
  )}
`;
  const databasePath = resolveOpencodeDatabasePath(params.runtimeEnv);
  await fs20.mkdir(artifactsDir, { recursive: true });
  await writeIfChanged(systemPromptPath, systemPrompt);
  await writeIfChanged(configPath, configContent);
  return {
    configPath,
    configContent,
    databasePath,
    launchKey: [
      promptKey,
      configContent,
      databasePath != null ? databasePath : "",
      (_f = params.runtimeEnv.OPENCODE_DB) != null ? _f : "",
      (_g = params.runtimeEnv.XDG_DATA_HOME) != null ? _g : ""
    ].join("::"),
    systemPromptPath
  };
}
function buildOpencodeManagedConfig(baseConfig, systemPromptPath, userName, managedAgents = DEFAULT_OPENCODE_MANAGED_AGENT_CONFIGS, defaultAgentId) {
  const config2 = {
    ...baseConfig,
    $schema: typeof baseConfig.$schema === "string" ? baseConfig.$schema : "https://opencode.ai/config.json"
  };
  const existingAgents = isPlainObject5(baseConfig.agent) ? { ...baseConfig.agent } : {};
  const nextAgents = { ...existingAgents };
  const agentConfigs = managedAgents.length > 0 ? managedAgents : DEFAULT_OPENCODE_MANAGED_AGENT_CONFIGS;
  for (const agentConfig of agentConfigs) {
    const existingAgentValue = existingAgents[agentConfig.id];
    const existingAgent = isPlainObject5(existingAgentValue) ? { ...existingAgentValue } : {};
    nextAgents[agentConfig.id] = {
      ...existingAgent,
      ...isPlainObject5(agentConfig.definition) ? agentConfig.definition : {},
      prompt: `{file:${systemPromptPath}}`
    };
  }
  config2.agent = nextAgents;
  const trimmedDefaultAgentId = defaultAgentId == null ? void 0 : defaultAgentId.trim();
  if (trimmedDefaultAgentId) {
    config2.default_agent = trimmedDefaultAgentId;
  }
  const trimmedUserName = userName == null ? void 0 : userName.trim();
  if (trimmedUserName) {
    config2.username = trimmedUserName;
  }
  return config2;
}
async function writeIfChanged(filePath, content) {
  try {
    const existing = await fs20.readFile(filePath, "utf-8");
    if (existing === content) {
      return;
    }
  } catch (e2) {
  }
  await fs20.writeFile(filePath, content, "utf-8");
}
async function loadOpencodeBaseConfig(configuredPath, workspaceRoot) {
  const trimmedPath = configuredPath == null ? void 0 : configuredPath.trim();
  if (!trimmedPath) {
    return {};
  }
  const expandedPath = expandHomePath(trimmedPath);
  const resolvedPath = path18.isAbsolute(expandedPath) ? expandedPath : path18.resolve(workspaceRoot, expandedPath);
  try {
    const rawConfig = await fs20.readFile(resolvedPath, "utf8");
    const parsedConfig = JSON.parse(rawConfig);
    return isPlainObject5(parsedConfig) ? parsedConfig : {};
  } catch (e2) {
    return {};
  }
}
function isPlainObject5(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
function normalizeSystemPrompt(systemPrompt) {
  return systemPrompt.endsWith("\n") ? systemPrompt : `${systemPrompt}
`;
}
function requireSettings(params) {
  if (params.settings) {
    return params.settings;
  }
  throw new Error("prepareOpencodeLaunchArtifacts requires settings when no systemPromptText is provided");
}

// src/providers/opencode/runtime/OpencodeRuntimeEnvironment.ts
init_env();
function buildOpencodeRuntimeEnv(settings11, cliPath, databasePathOverride) {
  const envText = getRuntimeEnvironmentText(settings11, "opencode");
  const envVars = parseEnvironmentVariables(envText);
  return {
    ...process.env,
    ...envVars,
    OPENCODE_DISABLE_CLAUDE_CODE_PROMPT: "true",
    ...databasePathOverride ? { OPENCODE_DB: databasePathOverride } : {},
    PATH: getEnhancedPath(envVars.PATH, cliPath || void 0)
  };
}

// src/providers/opencode/runtime/OpencodeChatRuntime.ts
var StreamChunkQueue = class {
  constructor() {
    this.closed = false;
    this.items = [];
    this.waiters = [];
  }
  push(chunk) {
    const waiter = this.waiters.shift();
    if (waiter) {
      waiter(chunk);
      return;
    }
    this.items.push(chunk);
  }
  close() {
    var _a3;
    if (this.closed) {
      return;
    }
    this.closed = true;
    while (this.waiters.length > 0) {
      (_a3 = this.waiters.shift()) == null ? void 0 : _a3(null);
    }
  }
  async next() {
    var _a3;
    if (this.items.length > 0) {
      return (_a3 = this.items.shift()) != null ? _a3 : null;
    }
    if (this.closed) {
      return null;
    }
    return new Promise((resolve8) => {
      this.waiters.push(resolve8);
    });
  }
};
var OpencodeChatRuntime = class {
  constructor(plugin) {
    this.plugin = plugin;
    this.providerId = "opencode";
    this.activeTurn = null;
    this.approvalCallback = null;
    this.connection = null;
    this.contextUsage = null;
    this.currentDatabasePath = null;
    this.currentLaunchKey = null;
    this.currentSessionModelId = null;
    this.currentSessionModeId = null;
    this.currentTurnMetadata = {};
    this.loadedSessionId = null;
    this.permissionModeSyncCallback = null;
    this.process = null;
    this.promptUsage = null;
    this.readyListeners = [];
    this.ready = false;
    this.sessionInvalidated = false;
    this.supportedCommandWaiters = [];
    this.supportedCommands = [];
    this.sessionCwds = /* @__PURE__ */ new Map();
    this.sessionId = null;
    this.sessionUpdateNormalizer = new AcpSessionUpdateNormalizer();
    this.toolStreamAdapter = createOpencodeToolStreamAdapter();
    this.transport = null;
  }
  getCapabilities() {
    return OPENCODE_PROVIDER_CAPABILITIES;
  }
  prepareTurn(request) {
    var _a3;
    return {
      isCompact: false,
      mcpMentions: (_a3 = request.enabledMcpServers) != null ? _a3 : /* @__PURE__ */ new Set(),
      persistedContent: "",
      prompt: buildOpencodePromptText(request),
      request
    };
  }
  onReadyStateChange(listener) {
    this.readyListeners.push(listener);
    return () => {
      const index = this.readyListeners.indexOf(listener);
      if (index >= 0) {
        this.readyListeners.splice(index, 1);
      }
    };
  }
  setResumeCheckpoint(_checkpointId) {
  }
  syncConversationState(conversation) {
    var _a3;
    const previousSessionId = this.sessionId;
    const nextSessionId = (_a3 = conversation == null ? void 0 : conversation.sessionId) != null ? _a3 : null;
    if (this.sessionId !== nextSessionId) {
      this.currentSessionModelId = null;
      this.currentSessionModeId = null;
      this.sessionInvalidated = false;
      this.setSupportedCommands([]);
    }
    this.sessionId = nextSessionId;
    const state = getOpencodeState(conversation == null ? void 0 : conversation.providerState);
    if (state.databasePath) {
      this.currentDatabasePath = state.databasePath;
      return;
    }
    if (!nextSessionId || nextSessionId !== previousSessionId) {
      this.currentDatabasePath = null;
    }
  }
  async reloadMcpServers() {
  }
  async ensureReady(options) {
    var _a3, _b2;
    const settings11 = getOpencodeProviderSettings(this.plugin.settings);
    if (!settings11.enabled) {
      this.setReady(false);
      return false;
    }
    const cwd = (_a3 = getVaultPath(this.plugin.app)) != null ? _a3 : process.cwd();
    const targetSessionId = this.sessionId;
    const resolvedCliPath = (_b2 = this.plugin.getResolvedProviderCliPath("opencode")) != null ? _b2 : "opencode";
    const runtimeEnv = this.buildRuntimeEnv(
      resolvedCliPath,
      this.currentDatabasePath
    );
    const promptSettings = this.getSystemPromptSettings(cwd);
    const artifacts = await prepareOpencodeLaunchArtifacts({
      runtimeEnv,
      settings: promptSettings,
      workspaceRoot: cwd
    });
    this.currentDatabasePath = artifacts.databasePath;
    const nextLaunchKey = JSON.stringify({
      command: resolvedCliPath,
      configPath: artifacts.configPath,
      envText: getRuntimeEnvironmentText(this.plugin.settings, "opencode"),
      promptKey: computeSystemPromptKey(promptSettings),
      artifactKey: artifacts.launchKey
    });
    const shouldRestart = !this.process || !this.transport || !this.connection || !this.process.isAlive() || (options == null ? void 0 : options.force) === true || this.currentLaunchKey !== nextLaunchKey;
    if (shouldRestart) {
      await this.shutdownProcess();
      await this.startProcess({
        command: resolvedCliPath,
        configPath: artifacts.configPath,
        cwd,
        runtimeEnv
      });
      this.currentLaunchKey = nextLaunchKey;
      this.loadedSessionId = null;
    }
    if (targetSessionId) {
      if (this.loadedSessionId !== targetSessionId) {
        const loaded = await this.loadSession(targetSessionId, cwd);
        if (!loaded) {
          this.sessionInvalidated = true;
          this.clearActiveSession();
        }
      }
      return true;
    }
    if (!this.sessionId && !this.sessionInvalidated) {
      if ((options == null ? void 0 : options.allowSessionCreation) === false) {
        return true;
      }
      return Boolean(await this.createSession(cwd));
    }
    return true;
  }
  async *query(turn, conversationHistory, queryOptions) {
    var _a3, _b2;
    const previousMessages = conversationHistory != null ? conversationHistory : [];
    const expectedSessionId = this.sessionId;
    let shouldBootstrapHistory = previousMessages.length > 0 && (!expectedSessionId || this.sessionInvalidated);
    if (!await this.ensureReady()) {
      yield { type: "error", content: "Failed to start OpenCode. Check the CLI path and login state." };
      yield { type: "done" };
      return;
    }
    if (!this.connection) {
      yield { type: "error", content: "OpenCode runtime is not ready." };
      yield { type: "done" };
      return;
    }
    const cwd = (_a3 = getVaultPath(this.plugin.app)) != null ? _a3 : process.cwd();
    if (expectedSessionId && !this.sessionId) {
      shouldBootstrapHistory = previousMessages.length > 0;
    }
    if (!this.sessionId) {
      const sessionId2 = await this.createSession(cwd);
      if (!sessionId2) {
        yield { type: "error", content: "Failed to create an OpenCode session." };
        yield { type: "done" };
        return;
      }
    }
    const sessionId = this.sessionId;
    (_b2 = this.activeTurn) == null ? void 0 : _b2.queue.close();
    this.activeTurn = {
      queue: new StreamChunkQueue(),
      sessionId
    };
    this.currentTurnMetadata = {};
    this.contextUsage = null;
    this.promptUsage = null;
    this.sessionUpdateNormalizer.reset();
    this.toolStreamAdapter.reset();
    const activeTurn = this.activeTurn;
    try {
      await this.applySelectedMode(sessionId);
      await this.applySelectedModel(sessionId, queryOptions);
    } catch (error48) {
      yield {
        type: "error",
        content: this.formatRuntimeError(error48)
      };
      yield { type: "done" };
      activeTurn.queue.close();
      this.activeTurn = null;
      return;
    }
    const promptPromise = this.connection.prompt({
      prompt: buildOpencodePromptBlocks(
        turn.request,
        shouldBootstrapHistory ? previousMessages : []
      ),
      sessionId
    }).then((response) => {
      var _a4;
      if (response.userMessageId) {
        this.currentTurnMetadata.userMessageId = response.userMessageId;
      }
      this.promptUsage = (_a4 = response.usage) != null ? _a4 : null;
      const usage = buildAcpUsageInfo({
        contextWindow: this.contextUsage,
        model: this.getActiveDisplayModel(queryOptions),
        promptUsage: this.promptUsage
      });
      if (usage) {
        activeTurn.queue.push({ sessionId, type: "usage", usage });
      }
      activeTurn.queue.push({ type: "done" });
      activeTurn.queue.close();
    }).catch((error48) => {
      activeTurn.queue.push({
        type: "error",
        content: this.formatRuntimeError(error48)
      });
      activeTurn.queue.push({ type: "done" });
      activeTurn.queue.close();
    }).finally(() => {
      if (this.activeTurn === activeTurn) {
        this.activeTurn = null;
      }
    });
    try {
      while (true) {
        const chunk = await activeTurn.queue.next();
        if (!chunk) {
          break;
        }
        yield chunk;
      }
      await promptPromise;
    } finally {
      if (this.activeTurn === activeTurn) {
        this.activeTurn = null;
      }
    }
  }
  cancel() {
    if (this.connection && this.sessionId) {
      this.connection.cancel({ sessionId: this.sessionId });
    }
  }
  resetSession() {
    this.clearActiveSession();
    this.sessionInvalidated = false;
  }
  getSessionId() {
    return this.sessionId;
  }
  consumeSessionInvalidation() {
    const invalidated = this.sessionInvalidated;
    this.sessionInvalidated = false;
    return invalidated;
  }
  isReady() {
    return this.ready;
  }
  async getSupportedCommands() {
    if (this.supportedCommands.length > 0 && this.loadedSessionId === this.sessionId) {
      return [...this.supportedCommands];
    }
    if (this.sessionId && this.loadedSessionId !== this.sessionId) {
      const ready = await this.ensureReady({ allowSessionCreation: false });
      if (!ready) {
        return [];
      }
    }
    if (!this.sessionId) {
      return [];
    }
    if (this.supportedCommands.length > 0) {
      return [...this.supportedCommands];
    }
    if (!this.sessionId || this.loadedSessionId !== this.sessionId) {
      return [];
    }
    return this.waitForSupportedCommands();
  }
  cleanup() {
    var _a3;
    (_a3 = this.activeTurn) == null ? void 0 : _a3.queue.close();
    void this.shutdownProcess();
  }
  async rewind(_userMessageId, _assistantMessageId) {
    return { canRewind: false };
  }
  setApprovalCallback(callback) {
    this.approvalCallback = callback;
  }
  setApprovalDismisser(_dismisser) {
  }
  setAskUserQuestionCallback(_callback) {
  }
  setExitPlanModeCallback(_callback) {
  }
  setPermissionModeSyncCallback(callback) {
    this.permissionModeSyncCallback = callback;
  }
  setSubagentHookProvider(_getState) {
  }
  setAutoTurnCallback(_callback) {
  }
  consumeTurnMetadata() {
    const metadata = this.currentTurnMetadata;
    this.currentTurnMetadata = {};
    return metadata;
  }
  buildSessionUpdates(params) {
    var _a3;
    const existingState = params.conversation ? getOpencodeState(params.conversation.providerState) : null;
    const providerState = {
      ...this.currentDatabasePath || (existingState == null ? void 0 : existingState.databasePath) ? { databasePath: (_a3 = this.currentDatabasePath) != null ? _a3 : existingState == null ? void 0 : existingState.databasePath } : {}
    };
    const updates = {
      providerState: Object.keys(providerState).length > 0 ? providerState : void 0,
      sessionId: this.sessionId
    };
    if (params.sessionInvalidated) {
      if (!this.sessionId) {
        updates.providerState = void 0;
        updates.sessionId = null;
      }
    }
    return { updates };
  }
  resolveSessionIdForFork(conversation) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.sessionId) != null ? _a3 : conversation == null ? void 0 : conversation.sessionId) != null ? _b2 : null;
  }
  async loadSubagentToolCalls(_agentId) {
    return [];
  }
  async loadSubagentFinalResult(_agentId) {
    return null;
  }
  async startProcess(params) {
    var _a3, _b2;
    const processEnv = {
      ...process.env,
      ...params.runtimeEnv,
      OPENCODE_CONFIG: params.configPath,
      PATH: getEnhancedPath(
        params.runtimeEnv.PATH,
        path19.isAbsolute(params.command) ? params.command : void 0
      )
    };
    this.process = new AcpSubprocess({
      args: ["acp", `--cwd=${params.cwd}`],
      command: params.command,
      cwd: params.cwd,
      env: processEnv
    });
    this.process.start();
    this.transport = new AcpJsonRpcTransport({
      input: this.process.stdout,
      onClose: (listener) => this.process.onClose(listener),
      output: this.process.stdin
    });
    this.connection = new AcpClientConnection({
      clientInfo: {
        name: "claudian",
        version: (_b2 = (_a3 = this.plugin.manifest) == null ? void 0 : _a3.version) != null ? _b2 : "0.0.0"
      },
      delegate: {
        fileSystem: {
          readTextFile: (request) => this.readTextFile(request),
          writeTextFile: (request) => this.writeTextFile(request)
        },
        onSessionNotification: (notification) => this.handleSessionNotification(notification),
        requestPermission: (request) => this.handlePermissionRequest(request)
      },
      transport: this.transport
    });
    this.transport.start();
    await this.connection.initialize();
    this.setReady(true);
  }
  async shutdownProcess() {
    var _a3, _b2, _c;
    this.setReady(false);
    (_a3 = this.activeTurn) == null ? void 0 : _a3.queue.close();
    this.activeTurn = null;
    this.currentSessionModelId = null;
    this.currentSessionModeId = null;
    this.setSupportedCommands([]);
    (_b2 = this.connection) == null ? void 0 : _b2.dispose();
    this.connection = null;
    (_c = this.transport) == null ? void 0 : _c.dispose();
    this.transport = null;
    if (this.process) {
      await this.process.shutdown().catch(() => {
      });
      this.process = null;
    }
  }
  setReady(ready) {
    if (this.ready === ready) {
      return;
    }
    this.ready = ready;
    for (const listener of this.readyListeners) {
      listener(ready);
    }
  }
  getSystemPromptSettings(vaultPath) {
    return {
      customPrompt: this.plugin.settings.systemPrompt,
      mediaFolder: this.plugin.settings.mediaFolder,
      userName: this.plugin.settings.userName,
      vaultPath
    };
  }
  buildRuntimeEnv(cliPath, databasePathOverride) {
    return buildOpencodeRuntimeEnv(
      this.plugin.settings,
      cliPath,
      databasePathOverride
    );
  }
  getProviderSettings() {
    return ProviderSettingsCoordinator.getProviderSettingsSnapshot(
      this.plugin.settings,
      this.providerId
    );
  }
  resolveSelectedRawModelId(queryOptions) {
    const providerSettings = this.getProviderSettings();
    const selectedModel = typeof (queryOptions == null ? void 0 : queryOptions.model) === "string" ? queryOptions.model : typeof providerSettings.model === "string" ? providerSettings.model : "";
    if (!isOpencodeModelSelectionId(selectedModel)) {
      return null;
    }
    const selectedBaseRawModelId = decodeOpencodeModelId(selectedModel);
    if (!selectedBaseRawModelId) {
      return null;
    }
    const discoveredModels = getOpencodeProviderSettings(providerSettings).discoveredModels;
    const effortLevel = typeof providerSettings.effortLevel === "string" ? providerSettings.effortLevel : OPENCODE_DEFAULT_THINKING_LEVEL;
    const normalizedBaseRawModelId = resolveOpencodeBaseModelRawId(selectedBaseRawModelId, discoveredModels);
    const resolvedRawModelId = combineOpencodeRawModelSelection(
      normalizedBaseRawModelId,
      effortLevel,
      discoveredModels
    );
    if (!resolvedRawModelId) {
      return null;
    }
    const availableModelIds = new Set(discoveredModels.map((model) => model.rawId));
    if (availableModelIds.size > 0 && !availableModelIds.has(resolvedRawModelId)) {
      return null;
    }
    return resolvedRawModelId;
  }
  getAuxiliaryModel() {
    var _a3;
    return (_a3 = this.getActiveDisplayModel()) != null ? _a3 : null;
  }
  getActiveDisplayModel(queryOptions) {
    const providerSettings = this.getProviderSettings();
    const selectedModel = typeof (queryOptions == null ? void 0 : queryOptions.model) === "string" ? queryOptions.model : typeof providerSettings.model === "string" ? providerSettings.model : "";
    if (selectedModel && selectedModel !== OPENCODE_SYNTHETIC_MODEL_ID && isOpencodeModelSelectionId(selectedModel)) {
      const selectedRawModelId = this.resolveSelectedRawModelId(queryOptions);
      return selectedRawModelId ? encodeOpencodeModelId(selectedRawModelId) : selectedModel;
    }
    return this.currentSessionModelId ? encodeOpencodeModelId(this.currentSessionModelId) : selectedModel && isOpencodeModelSelectionId(selectedModel) ? selectedModel : void 0;
  }
  resolveSelectedModeId() {
    var _a3;
    const providerSettings = this.getProviderSettings();
    const opencodeSettings = getOpencodeProviderSettings(providerSettings);
    const availableModes = getManagedOpencodeModes(opencodeSettings.availableModes);
    const mappedModeId = resolveOpencodeModeForPermissionMode(
      providerSettings.permissionMode,
      opencodeSettings.availableModes
    );
    if (mappedModeId) {
      return mappedModeId;
    }
    if (opencodeSettings.selectedMode) {
      if (availableModes.some((mode) => mode.id === opencodeSettings.selectedMode)) {
        return opencodeSettings.selectedMode;
      }
    }
    return ((_a3 = availableModes[0]) == null ? void 0 : _a3.id) || null;
  }
  async applySelectedMode(sessionId) {
    if (!this.connection) {
      return;
    }
    const selectedModeId = this.resolveSelectedModeId();
    if (!selectedModeId || selectedModeId === this.currentSessionModeId) {
      return;
    }
    const response = await this.connection.setConfigOption({
      configId: "mode",
      sessionId,
      type: "select",
      value: selectedModeId
    });
    this.currentSessionModeId = selectedModeId;
    await this.syncSessionModeState({
      configOptions: response.configOptions
    });
  }
  async applySelectedModel(sessionId, queryOptions) {
    if (!this.connection) {
      return;
    }
    const selectedRawModelId = this.resolveSelectedRawModelId(queryOptions);
    if (!selectedRawModelId || selectedRawModelId === this.currentSessionModelId) {
      return;
    }
    const response = await this.connection.setConfigOption({
      configId: "model",
      sessionId,
      type: "select",
      value: selectedRawModelId
    });
    this.currentSessionModelId = selectedRawModelId;
    await this.syncSessionModelState({
      configOptions: response.configOptions
    });
  }
  async syncSessionModelState(params) {
    const acpState = extractAcpSessionModelState(params);
    const currentRawModelId = acpState.currentModelId;
    const discoveredModels = normalizeOpencodeDiscoveredModels(
      acpState.availableModels.map((model) => ({
        ...model.description ? { description: model.description } : {},
        label: model.name,
        rawId: model.id
      }))
    );
    if (currentRawModelId) {
      this.currentSessionModelId = currentRawModelId;
    }
    const settingsBag = this.plugin.settings;
    const currentSettings = getOpencodeProviderSettings(settingsBag);
    const currentBaseRawModelId = currentRawModelId ? resolveOpencodeBaseModelRawId(currentRawModelId, discoveredModels) : null;
    const currentThinkingLevel = currentRawModelId ? extractOpencodeModelVariantValue(currentRawModelId, discoveredModels) : null;
    const nextVisibleModels = currentSettings.visibleModels.length === 0 && currentBaseRawModelId ? [currentBaseRawModelId] : currentSettings.visibleModels;
    const nextPreferredThinkingByModel = currentBaseRawModelId && currentThinkingLevel ? {
      ...currentSettings.preferredThinkingByModel,
      [currentBaseRawModelId]: currentThinkingLevel
    } : currentSettings.preferredThinkingByModel;
    const shouldSeedVisibleModels = !sameStringList(currentSettings.visibleModels, nextVisibleModels);
    const shouldSeedPreferredThinking = !sameStringMap(
      currentSettings.preferredThinkingByModel,
      nextPreferredThinkingByModel
    );
    const discoveryChanged = discoveredModels.length > 0 && !sameDiscoveredModels(currentSettings.discoveredModels, discoveredModels) && updateOpencodeDiscoveryState(settingsBag, { discoveredModels });
    let changed = shouldSeedVisibleModels || shouldSeedPreferredThinking;
    if (changed) {
      updateOpencodeProviderSettings(settingsBag, {
        ...shouldSeedPreferredThinking ? { preferredThinkingByModel: nextPreferredThinkingByModel } : {},
        ...shouldSeedVisibleModels ? { visibleModels: nextVisibleModels } : {}
      });
    }
    if (currentBaseRawModelId) {
      const seeded = this.seedActiveModelSelection(
        settingsBag,
        encodeOpencodeModelId(currentBaseRawModelId),
        currentThinkingLevel
      );
      changed = changed || seeded;
    }
    if (!changed && !discoveryChanged) {
      return;
    }
    if (changed) {
      await this.plugin.saveSettings();
    }
    this.refreshModelSelectors();
  }
  seedActiveModelSelection(settingsBag, modelSelection, thinkingLevel) {
    let changed = false;
    const savedProviderModel = ensureProviderProjectionMap(settingsBag, "savedProviderModel");
    const savedModel = typeof savedProviderModel.opencode === "string" ? savedProviderModel.opencode : "";
    if (!savedModel || savedModel === OPENCODE_SYNTHETIC_MODEL_ID) {
      savedProviderModel.opencode = modelSelection;
      changed = true;
    }
    if (thinkingLevel) {
      const savedProviderEffort = ensureProviderProjectionMap(settingsBag, "savedProviderEffort");
      if (typeof savedProviderEffort.opencode !== "string" || !savedProviderEffort.opencode) {
        savedProviderEffort.opencode = thinkingLevel;
        changed = true;
      }
    }
    if (ProviderRegistry.resolveSettingsProviderId(settingsBag) !== this.providerId) {
      return changed;
    }
    const activeModel = typeof settingsBag.model === "string" ? settingsBag.model : "";
    if (!activeModel || activeModel === OPENCODE_SYNTHETIC_MODEL_ID) {
      settingsBag.model = modelSelection;
      changed = true;
    }
    if (thinkingLevel) {
      const activeEffort = typeof settingsBag.effortLevel === "string" ? settingsBag.effortLevel : "";
      if (!activeEffort) {
        settingsBag.effortLevel = thinkingLevel;
        changed = true;
      }
    }
    return changed;
  }
  async syncSessionModeState(params) {
    var _a3;
    const acpState = extractAcpSessionModeState(params);
    const availableModes = normalizeOpencodeAvailableModes(acpState.availableModes);
    const currentModeId = (_a3 = params.currentModeId) != null ? _a3 : acpState.currentModeId;
    if (currentModeId) {
      this.currentSessionModeId = currentModeId;
      this.emitPermissionModeSync(currentModeId);
    }
    const settingsBag = this.plugin.settings;
    const currentSettings = getOpencodeProviderSettings(settingsBag);
    const shouldSeedSelectedMode = typeof currentModeId === "string" && !currentSettings.selectedMode && isManagedOpencodeModeId(currentModeId);
    const discoveryChanged = availableModes.length > 0 && !sameModes(currentSettings.availableModes, availableModes) && updateOpencodeDiscoveryState(settingsBag, { availableModes });
    if (!discoveryChanged && !shouldSeedSelectedMode) {
      return;
    }
    if (shouldSeedSelectedMode && currentModeId) {
      updateOpencodeProviderSettings(settingsBag, { selectedMode: currentModeId });
      await this.plugin.saveSettings();
    }
    this.refreshModelSelectors();
  }
  refreshModelSelectors() {
    for (const view of this.plugin.getAllViews()) {
      view.refreshModelSelector();
    }
  }
  emitPermissionModeSync(modeId) {
    const permissionMode = resolvePermissionModeForManagedOpencodeMode(modeId);
    if (!permissionMode || !this.permissionModeSyncCallback) {
      return;
    }
    try {
      this.permissionModeSyncCallback(permissionMode);
    } catch (e2) {
    }
  }
  async createSession(cwd) {
    var _a3, _b2, _c, _d2;
    if (!this.connection) {
      return null;
    }
    try {
      this.setSupportedCommands([]);
      const response = await this.connection.newSession({
        cwd,
        mcpServers: []
      });
      this.loadedSessionId = response.sessionId;
      this.sessionId = response.sessionId;
      this.sessionCwds.set(response.sessionId, cwd);
      await this.syncSessionModelState({
        configOptions: (_a3 = response.configOptions) != null ? _a3 : null,
        models: (_b2 = response.models) != null ? _b2 : null
      });
      await this.syncSessionModeState({
        configOptions: (_c = response.configOptions) != null ? _c : null,
        modes: (_d2 = response.modes) != null ? _d2 : null
      });
      return response.sessionId;
    } catch (e2) {
      return null;
    }
  }
  async loadSession(sessionId, cwd) {
    var _a3, _b2, _c, _d2;
    if (!this.connection) {
      return false;
    }
    try {
      this.setSupportedCommands([]);
      const response = await this.connection.loadSession({
        cwd,
        mcpServers: [],
        sessionId
      });
      this.sessionInvalidated = false;
      this.loadedSessionId = response.sessionId;
      this.sessionId = response.sessionId;
      this.sessionCwds.set(response.sessionId, cwd);
      await this.syncSessionModelState({
        configOptions: (_a3 = response.configOptions) != null ? _a3 : null,
        models: (_b2 = response.models) != null ? _b2 : null
      });
      await this.syncSessionModeState({
        configOptions: (_c = response.configOptions) != null ? _c : null,
        modes: (_d2 = response.modes) != null ? _d2 : null
      });
      return true;
    } catch (e2) {
      return false;
    }
  }
  async handleSessionNotification(notification) {
    if (notification.sessionId !== this.sessionId) {
      return;
    }
    const normalized = this.sessionUpdateNormalizer.normalize(notification.update);
    if (normalized.type === "config_options") {
      await this.syncSessionModelState({
        configOptions: normalized.configOptions
      });
      await this.syncSessionModeState({
        configOptions: normalized.configOptions
      });
      return;
    }
    if (normalized.type === "current_mode") {
      await this.syncSessionModeState({
        currentModeId: normalized.currentModeId
      });
      return;
    }
    if (normalized.type === "commands") {
      this.setSupportedCommands(normalized.commands);
      return;
    }
    if (!this.activeTurn || this.activeTurn.sessionId !== notification.sessionId) {
      return;
    }
    switch (normalized.type) {
      case "message_chunk": {
        if (normalized.role === "assistant" && normalized.messageId) {
          this.currentTurnMetadata.assistantMessageId = normalized.messageId;
        }
        if (normalized.role === "user" && normalized.messageId) {
          this.currentTurnMetadata.userMessageId = normalized.messageId;
        }
        for (const chunk of normalized.streamChunks) {
          this.activeTurn.queue.push(chunk);
        }
        return;
      }
      case "tool_call":
      case "tool_call_update": {
        const streamChunks = normalized.type === "tool_call" ? this.toolStreamAdapter.normalizeToolCall(normalized.toolCall, normalized.streamChunks) : this.toolStreamAdapter.normalizeToolCallUpdate(normalized.toolCallUpdate, normalized.streamChunks);
        for (const chunk of streamChunks) {
          this.activeTurn.queue.push(chunk);
        }
        return;
      }
      case "usage": {
        this.contextUsage = normalized.usage;
        const usage = buildAcpUsageInfo({
          contextWindow: normalized.usage,
          model: this.getActiveDisplayModel(),
          promptUsage: this.promptUsage
        });
        if (usage) {
          this.activeTurn.queue.push({
            sessionId: notification.sessionId,
            type: "usage",
            usage
          });
        }
        return;
      }
      default:
        return;
    }
  }
  async handlePermissionRequest(request) {
    if (!this.approvalCallback) {
      return { outcome: { outcome: "cancelled" } };
    }
    const input = normalizeApprovalInput(request.toolCall.rawInput);
    const presentation = buildOpencodePermissionPresentation(request.toolCall.title, input, request.toolCall.locations);
    const decision = await this.approvalCallback(
      presentation.toolName,
      input,
      presentation.description,
      {
        ...presentation.blockedPath ? { blockedPath: presentation.blockedPath } : {},
        ...presentation.decisionReason ? { decisionReason: presentation.decisionReason } : {},
        decisionOptions: buildAcpApprovalDecisionOptions(request.options)
      }
    );
    return mapApprovalDecision(decision, request.options);
  }
  setSupportedCommands(commands) {
    this.supportedCommands = commands.map((command) => ({ ...command }));
    const waiters = this.supportedCommandWaiters.splice(0);
    for (const waiter of waiters) {
      waiter(this.supportedCommands);
    }
  }
  waitForSupportedCommands(timeoutMs = 250) {
    if (this.supportedCommands.length > 0) {
      return Promise.resolve([...this.supportedCommands]);
    }
    return new Promise((resolve8) => {
      const waiter = (commands) => {
        clearTimeout(timeoutId);
        resolve8([...commands]);
      };
      const timeoutId = setTimeout(() => {
        const index = this.supportedCommandWaiters.indexOf(waiter);
        if (index >= 0) {
          this.supportedCommandWaiters.splice(index, 1);
        }
        resolve8([...this.supportedCommands]);
      }, timeoutMs);
      this.supportedCommandWaiters.push(waiter);
    });
  }
  async readTextFile(request) {
    var _a3;
    const resolvedPath = this.resolveSessionPath(request.sessionId, request.path);
    const content = await fs21.readFile(resolvedPath, "utf-8");
    if (request.line === void 0 && request.limit === void 0) {
      return { content };
    }
    const lines = content.split(/\r?\n/);
    const startIndex = Math.max(0, ((_a3 = request.line) != null ? _a3 : 1) - 1);
    const endIndex = request.limit ? startIndex + Math.max(0, request.limit) : lines.length;
    return {
      content: lines.slice(startIndex, endIndex).join("\n")
    };
  }
  async writeTextFile(request) {
    const resolvedPath = this.resolveSessionPath(request.sessionId, request.path);
    await fs21.mkdir(path19.dirname(resolvedPath), { recursive: true });
    await fs21.writeFile(resolvedPath, request.content, "utf-8");
    return {};
  }
  resolveSessionPath(sessionId, rawPath) {
    var _a3, _b2;
    if (path19.isAbsolute(rawPath)) {
      return rawPath;
    }
    const cwd = (_b2 = (_a3 = this.sessionCwds.get(sessionId)) != null ? _a3 : getVaultPath(this.plugin.app)) != null ? _b2 : process.cwd();
    return path19.resolve(cwd, rawPath);
  }
  formatRuntimeError(error48) {
    var _a3;
    const baseMessage = error48 instanceof Error ? error48.message : "OpenCode request failed";
    const stderr = (_a3 = this.process) == null ? void 0 : _a3.getStderrSnapshot();
    return stderr ? `${baseMessage}

${stderr}` : baseMessage;
  }
  clearActiveSession() {
    this.currentDatabasePath = null;
    this.sessionId = null;
    this.loadedSessionId = null;
    this.currentSessionModelId = null;
    this.currentSessionModeId = null;
    this.setSupportedCommands([]);
  }
};
function normalizeApprovalInput(rawInput) {
  if (rawInput && typeof rawInput === "object" && !Array.isArray(rawInput)) {
    return rawInput;
  }
  if (rawInput === void 0) {
    return {};
  }
  return { value: rawInput };
}
function buildOpencodePermissionPresentation(rawTitle, input, locations) {
  const permissionId = normalizePermissionId(rawTitle);
  const blockedPath = extractPermissionPath(input, locations);
  switch (permissionId) {
    case "bash":
      return {
        decisionReason: "Command execution permission required",
        description: "OpenCode wants to run a shell command.",
        toolName: "bash"
      };
    case "codesearch":
      return {
        description: "OpenCode wants to search indexed code outside the active buffer.",
        toolName: "codesearch"
      };
    case "doom_loop": {
      const repeatedTool = typeof input.tool === "string" ? input.tool.trim() : "";
      return {
        decisionReason: "OpenCode detected repeated identical tool calls",
        description: repeatedTool ? `Allow another repeated \`${repeatedTool}\` call.` : "Allow another repeated tool call.",
        toolName: "Doom Loop Guard"
      };
    }
    case "edit":
      return {
        ...blockedPath ? { blockedPath } : {},
        decisionReason: "File write permission required",
        description: blockedPath ? "OpenCode wants to modify this file." : "OpenCode wants to apply file changes.",
        toolName: "edit"
      };
    case "external_directory":
      return {
        ...blockedPath ? { blockedPath } : {},
        decisionReason: "Path is outside the session working directory",
        description: blockedPath ? "OpenCode wants to access a path outside the working directory." : "OpenCode wants to access files outside the working directory.",
        toolName: "External Directory"
      };
    case "glob":
      return {
        description: "OpenCode wants to scan file paths with a glob pattern.",
        toolName: "glob"
      };
    case "grep":
      return {
        description: "OpenCode wants to search file contents with a pattern.",
        toolName: "grep"
      };
    case "lsp":
      return {
        description: "OpenCode wants to query language server data.",
        toolName: "lsp"
      };
    case "plan_enter":
      return {
        description: "OpenCode wants to switch this session into planning mode.",
        toolName: "Enter Plan Mode"
      };
    case "plan_exit":
      return {
        description: "OpenCode wants to leave planning mode and resume implementation.",
        toolName: "Exit Plan Mode"
      };
    case "question":
      return {
        description: "OpenCode wants to ask you a direct question before continuing.",
        toolName: "Ask Question"
      };
    case "read":
      return {
        ...blockedPath ? { blockedPath } : {},
        description: blockedPath ? "OpenCode wants to read this path." : "OpenCode wants to read project files.",
        toolName: "read"
      };
    case "skill":
      return {
        description: "OpenCode wants to load a skill into the current session.",
        toolName: "skill"
      };
    case "todowrite":
      return {
        description: "OpenCode wants to update the shared task list.",
        toolName: "todowrite"
      };
    case "webfetch":
      return {
        description: "OpenCode wants to fetch content from a URL.",
        toolName: "webfetch"
      };
    case "websearch":
      return {
        description: "OpenCode wants to search the web.",
        toolName: "websearch"
      };
    case "workflow_tool_approval": {
      const summary = summarizeWorkflowTools(input);
      return {
        decisionReason: "Session-level workflow approval requested",
        description: summary ? `Pre-approve workflow tools for this session: ${summary}.` : "Pre-approve workflow tools for this session.",
        toolName: "Workflow Approval"
      };
    }
    default:
      return {
        ...blockedPath ? { blockedPath } : {},
        description: blockedPath ? `OpenCode wants permission to use ${formatPermissionLabel(permissionId)} on this path.` : `OpenCode wants permission to use ${formatPermissionLabel(permissionId)}.`,
        toolName: formatPermissionLabel(permissionId)
      };
  }
}
function normalizePermissionId(value) {
  return (value == null ? void 0 : value.trim().toLowerCase()) || "tool";
}
function extractPermissionPath(input, locations) {
  var _a3;
  const candidateKeys = ["filepath", "filePath", "path", "parentDir"];
  for (const key of candidateKeys) {
    const value = input[key];
    if (typeof value === "string" && value.trim()) {
      return value.trim();
    }
  }
  const locationPath = (_a3 = locations == null ? void 0 : locations.find((location) => location.path.trim())) == null ? void 0 : _a3.path;
  return (locationPath == null ? void 0 : locationPath.trim()) || void 0;
}
function summarizeWorkflowTools(input) {
  const tools = Array.isArray(input.tools) ? input.tools : [];
  const names = tools.flatMap((tool) => {
    if (!tool || typeof tool !== "object" || Array.isArray(tool)) {
      return [];
    }
    const entry = tool;
    const name = typeof entry.name === "string" ? entry.name.trim() : "";
    if (!name) {
      return [];
    }
    let title = "";
    if (typeof entry.args === "string") {
      try {
        const parsedArgs = JSON.parse(entry.args);
        title = typeof parsedArgs.title === "string" ? parsedArgs.title.trim() : typeof parsedArgs.name === "string" ? parsedArgs.name.trim() : "";
      } catch (e2) {
        title = "";
      }
    }
    return [title ? `${name}: ${title}` : name];
  });
  if (names.length === 0) {
    return "";
  }
  if (names.length <= 3) {
    return names.join(", ");
  }
  return `${names.slice(0, 3).join(", ")} +${names.length - 3} more`;
}
function formatPermissionLabel(permissionId) {
  return permissionId.split(/[_\s]+/).filter(Boolean).map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1)).join(" ");
}
function mapApprovalDecision(decision, options) {
  if (decision === "allow") {
    return selectPermissionOption(options, ["allow_once", "allow_always"]);
  }
  if (decision === "allow-always") {
    return selectPermissionOption(options, ["allow_always", "allow_once"]);
  }
  if (decision === "deny") {
    return selectPermissionOption(options, ["reject_once", "reject_always"]);
  }
  if (typeof decision === "object" && decision.type === "select-option") {
    return {
      outcome: {
        optionId: decision.value,
        outcome: "selected"
      }
    };
  }
  return { outcome: { outcome: "cancelled" } };
}
function buildAcpApprovalDecisionOptions(options) {
  return options.map((option) => ({
    ...option.kind === "allow_once" ? { decision: "allow" } : option.kind === "allow_always" ? { decision: "allow-always" } : {},
    label: option.name,
    value: option.optionId
  }));
}
function selectPermissionOption(options, preferredKinds) {
  for (const kind of preferredKinds) {
    const option = options.find((entry) => entry.kind === kind);
    if (option) {
      return {
        outcome: {
          optionId: option.optionId,
          outcome: "selected"
        }
      };
    }
  }
  return { outcome: { outcome: "cancelled" } };
}

// src/providers/opencode/app/OpencodeRuntimeCommandLoader.ts
var OPENCODE_METADATA_WARMUP_DB = ":memory:";
var OpencodeRuntimeCommandLoader = class {
  isAvailable(settings11) {
    return getOpencodeProviderSettings(settings11).enabled;
  }
  async loadCommands(context) {
    var _a3, _b2, _c;
    const shouldWarmBlankSession = context.allowSessionCreation === true && !((_a3 = context.conversation) == null ? void 0 : _a3.sessionId);
    const shouldWarmPreSessionConversation = !!context.conversation && !context.conversation.sessionId && context.conversation.messages.length > 0;
    if (!context.runtime && !((_b2 = context.conversation) == null ? void 0 : _b2.sessionId) && !shouldWarmBlankSession && !shouldWarmPreSessionConversation) {
      return [];
    }
    const canReuseRuntime = ((_c = context.runtime) == null ? void 0 : _c.providerId) === "opencode" && !shouldWarmPreSessionConversation;
    const runtime = canReuseRuntime ? context.runtime : new OpencodeChatRuntime(context.plugin);
    try {
      if (context.conversation) {
        runtime.syncConversationState(context.conversation, context.externalContextPaths);
      } else if (shouldWarmBlankSession) {
        runtime.syncConversationState({
          providerState: { databasePath: OPENCODE_METADATA_WARMUP_DB },
          sessionId: null
        });
      }
      const ready = await runtime.ensureReady({
        allowSessionCreation: shouldWarmBlankSession || shouldWarmPreSessionConversation
      });
      if (!ready) {
        return [];
      }
      return await runtime.getSupportedCommands();
    } finally {
      if (runtime !== context.runtime) {
        runtime.cleanup();
      }
    }
  }
};

// src/providers/opencode/app/OpencodeWorkspaceServices.ts
var opencodeTabWarmupPolicy = {
  resolveMode() {
    return "commands";
  }
};
async function createOpencodeWorkspaceServices(vaultAdapter) {
  const agentStorage = new OpencodeAgentStorage(vaultAdapter);
  const agentMentionProvider = new OpencodeAgentMentionProvider(agentStorage);
  await agentMentionProvider.loadAgents();
  return {
    agentStorage,
    agentMentionProvider,
    commandCatalog: new OpencodeCommandCatalog(),
    cliResolver: new OpencodeCliResolver(),
    runtimeCommandLoader: new OpencodeRuntimeCommandLoader(),
    settingsTabRenderer: opencodeSettingsTabRenderer,
    tabWarmupPolicy: opencodeTabWarmupPolicy,
    refreshAgentMentions: async () => {
      await agentMentionProvider.loadAgents();
    }
  };
}
var opencodeWorkspaceRegistration = {
  initialize: async ({ vaultAdapter }) => createOpencodeWorkspaceServices(vaultAdapter)
};
function maybeGetOpencodeWorkspaceServices() {
  return ProviderWorkspaceRegistry.getServices("opencode");
}

// src/providers/opencode/runtime/OpencodeAuxQueryRunner.ts
var fs22 = __toESM(require("node:fs/promises"));
var path20 = __toESM(require("node:path"));
init_path();

// src/providers/opencode/ui/OpencodeChatUIConfig.ts
var OPENCODE_MODELS = [
  { value: OPENCODE_SYNTHETIC_MODEL_ID, label: "OpenCode", description: "ACP runtime" }
];
var DEFAULT_CONTEXT_WINDOW3 = 2e5;
var OPENCODE_PERMISSION_MODE_TOGGLE = {
  inactiveValue: "normal",
  inactiveLabel: "Safe",
  activeValue: "yolo",
  activeLabel: "YOLO",
  planValue: "plan",
  planLabel: "Plan"
};
var opencodeChatUIConfig = {
  getModelOptions(settings11) {
    var _a3, _b2;
    const opencodeSettings = getOpencodeProviderSettings(settings11);
    const applyAlias = (rawId, option) => {
      const alias = opencodeSettings.modelAliases[rawId];
      return alias ? { ...option, label: alias } : option;
    };
    const discoveredModels = new Map(buildOpencodeBaseModels(opencodeSettings.discoveredModels).map((model) => {
      var _a4;
      return [
        encodeOpencodeModelId(model.rawId),
        applyAlias(model.rawId, {
          description: (_a4 = model.description) != null ? _a4 : "ACP runtime",
          label: model.label,
          value: encodeOpencodeModelId(model.rawId)
        })
      ];
    }));
    const savedProviderModel = settings11.savedProviderModel && typeof settings11.savedProviderModel === "object" && !Array.isArray(settings11.savedProviderModel) ? settings11.savedProviderModel : null;
    const seenValues = /* @__PURE__ */ new Set();
    const options = [];
    for (const rawModelId of opencodeSettings.visibleModels) {
      const encodedModelId = encodeOpencodeModelId(rawModelId);
      pushOption(
        options,
        seenValues,
        encodedModelId,
        (_a3 = discoveredModels.get(encodedModelId)) != null ? _a3 : applyAlias(rawModelId, {
          description: "Configured model",
          label: rawModelId,
          value: encodedModelId
        })
      );
    }
    const selectedModelValues = [
      typeof settings11.model === "string" ? settings11.model : "",
      typeof (savedProviderModel == null ? void 0 : savedProviderModel.opencode) === "string" ? savedProviderModel.opencode : ""
    ];
    for (const model of selectedModelValues) {
      const rawModelId = decodeOpencodeModelId(model);
      if (!model || !isOpencodeModelSelectionId(model) || model === OPENCODE_SYNTHETIC_MODEL_ID || !rawModelId) {
        continue;
      }
      const baseRawId = resolveOpencodeBaseModelRawId(rawModelId, opencodeSettings.discoveredModels);
      const baseModelId = encodeOpencodeModelId(baseRawId);
      pushOption(
        options,
        seenValues,
        baseModelId,
        (_b2 = discoveredModels.get(baseModelId)) != null ? _b2 : applyAlias(baseRawId, {
          description: "Selected in an existing session",
          label: baseRawId,
          value: baseModelId
        })
      );
    }
    return options.length > 0 ? options : [...OPENCODE_MODELS];
  },
  ownsModel(model) {
    return isOpencodeModelSelectionId(model);
  },
  isAdaptiveReasoningModel(_model, _settings) {
    return true;
  },
  getReasoningOptions(model, settings11) {
    const rawModelId = decodeOpencodeModelId(model);
    if (!rawModelId) {
      return [];
    }
    const opencodeSettings = getOpencodeProviderSettings(settings11);
    const baseRawId = resolveOpencodeBaseModelRawId(rawModelId, opencodeSettings.discoveredModels);
    const variants = getOpencodeModelVariants(baseRawId, opencodeSettings.discoveredModels);
    if (variants.length === 0) {
      return [];
    }
    return [
      { value: OPENCODE_DEFAULT_THINKING_LEVEL, label: "Default" },
      ...variants.map((variant) => ({
        description: variant.description,
        label: variant.label,
        value: variant.value
      }))
    ];
  },
  getDefaultReasoningValue(model, settings11) {
    const rawModelId = decodeOpencodeModelId(model);
    if (!rawModelId) {
      return OPENCODE_DEFAULT_THINKING_LEVEL;
    }
    const opencodeSettings = getOpencodeProviderSettings(settings11);
    const baseRawId = resolveOpencodeBaseModelRawId(rawModelId, opencodeSettings.discoveredModels);
    return getDefaultThinkingLevelForModel(baseRawId, settings11);
  },
  getContextWindowSize(model, customLimits) {
    var _a3;
    return (_a3 = customLimits == null ? void 0 : customLimits[model]) != null ? _a3 : DEFAULT_CONTEXT_WINDOW3;
  },
  isDefaultModel(model) {
    return isOpencodeModelSelectionId(model);
  },
  applyModelDefaults(model, settings11) {
    if (!settings11 || typeof settings11 !== "object" || Array.isArray(settings11)) {
      return;
    }
    const settingsBag = settings11;
    const rawModelId = decodeOpencodeModelId(model);
    if (!rawModelId) {
      settingsBag.effortLevel = OPENCODE_DEFAULT_THINKING_LEVEL;
      return;
    }
    const opencodeSettings = getOpencodeProviderSettings(settingsBag);
    const baseRawId = resolveOpencodeBaseModelRawId(rawModelId, opencodeSettings.discoveredModels);
    settingsBag.model = encodeOpencodeModelId(baseRawId);
    settingsBag.effortLevel = getDefaultThinkingLevelForModel(baseRawId, settingsBag);
  },
  applyReasoningSelection(model, value, settings11) {
    if (!settings11 || typeof settings11 !== "object" || Array.isArray(settings11)) {
      return;
    }
    const settingsBag = settings11;
    const rawModelId = decodeOpencodeModelId(model);
    if (!rawModelId) {
      return;
    }
    const opencodeSettings = getOpencodeProviderSettings(settingsBag);
    const baseRawId = resolveOpencodeBaseModelRawId(rawModelId, opencodeSettings.discoveredModels);
    const supportedValues = new Set(
      getOpencodeModelVariants(baseRawId, opencodeSettings.discoveredModels).map((variant) => variant.value)
    );
    const nextPreferredThinkingByModel = {
      ...opencodeSettings.preferredThinkingByModel
    };
    if (!value || value === OPENCODE_DEFAULT_THINKING_LEVEL || !supportedValues.has(value)) {
      delete nextPreferredThinkingByModel[baseRawId];
    } else {
      nextPreferredThinkingByModel[baseRawId] = value;
    }
    updateOpencodeProviderSettings(settingsBag, {
      preferredThinkingByModel: nextPreferredThinkingByModel
    });
  },
  normalizeModelVariant(model, settings11) {
    const rawModelId = decodeOpencodeModelId(model);
    if (!rawModelId) {
      return model;
    }
    const opencodeSettings = getOpencodeProviderSettings(settings11);
    const baseRawId = resolveOpencodeBaseModelRawId(rawModelId, opencodeSettings.discoveredModels);
    return encodeOpencodeModelId(baseRawId);
  },
  getCustomModelIds() {
    return /* @__PURE__ */ new Set();
  },
  getModeSelector() {
    return null;
  },
  getPermissionModeToggle() {
    return OPENCODE_PERMISSION_MODE_TOGGLE;
  },
  resolvePermissionMode(settings11) {
    const selectedMode = getOpencodeProviderSettings(settings11).selectedMode;
    return resolvePermissionModeForManagedOpencodeMode(selectedMode);
  },
  applyPermissionMode(value, settings11) {
    if (!settings11 || typeof settings11 !== "object" || Array.isArray(settings11)) {
      return;
    }
    const settingsBag = settings11;
    settingsBag.permissionMode = value;
    updateOpencodeProviderSettings(settingsBag, {
      selectedMode: resolveOpencodeModeForPermissionMode(
        value,
        getOpencodeProviderSettings(settingsBag).availableModes
      )
    });
  },
  getProviderIcon() {
    return OPENCODE_PROVIDER_ICON;
  }
};
function getDefaultThinkingLevelForModel(baseRawId, settings11) {
  const opencodeSettings = getOpencodeProviderSettings(settings11);
  const preferred = opencodeSettings.preferredThinkingByModel[baseRawId];
  const supportedValues = new Set(
    getOpencodeModelVariants(baseRawId, opencodeSettings.discoveredModels).map((variant) => variant.value)
  );
  if (preferred && supportedValues.has(preferred)) {
    return preferred;
  }
  return OPENCODE_DEFAULT_THINKING_LEVEL;
}
function pushOption(target, seenValues, value, option) {
  if (seenValues.has(value)) {
    return;
  }
  seenValues.add(value);
  target.push(option);
}

// src/providers/opencode/runtime/OpencodeAuxQueryRunner.ts
var OPENCODE_AUX_AGENT_IDS = {
  passive: "claudian-aux-passive",
  readonly: "claudian-aux-readonly"
};
var OPENCODE_AUX_READ_PERMISSION = Object.freeze({
  "*": "allow",
  "*.env": "deny",
  "*.env.*": "deny",
  "*.env.example": "allow"
});
var OpencodeAuxQueryRunner = class {
  constructor(plugin, options) {
    this.plugin = plugin;
    this.options = options;
    this.availableModelIds = /* @__PURE__ */ new Set();
    this.connection = null;
    this.currentModelId = null;
    this.currentLaunchKey = null;
    this.process = null;
    this.sessionCwds = /* @__PURE__ */ new Map();
    this.sessionId = null;
    this.sessionUpdateNormalizer = new AcpSessionUpdateNormalizer();
    this.transport = null;
  }
  async query(config2, prompt) {
    var _a3, _b2, _c, _d2, _e, _f;
    const cwd = (_a3 = getVaultPath(this.plugin.app)) != null ? _a3 : process.cwd();
    await this.ensureReady(cwd, config2.systemPrompt);
    if (!this.connection) {
      throw new Error("OpenCode runtime is not ready.");
    }
    if (!this.sessionId) {
      const sessionId2 = await this.createSession(cwd);
      if (!sessionId2) {
        throw new Error("Failed to create an OpenCode session.");
      }
    }
    const sessionId = this.sessionId;
    const selectedModel = this.resolveSelectedRawModel(config2.model);
    const nextModel = this.resolveApplicableModel(selectedModel);
    if (nextModel) {
      const response = await this.connection.setConfigOption({
        configId: "model",
        sessionId,
        type: "select",
        value: nextModel
      });
      this.syncSessionModelState({
        configOptions: response.configOptions
      });
    }
    this.sessionUpdateNormalizer.reset();
    let accumulatedText = "";
    const removeListener = this.connection.onSessionNotification((notification) => {
      var _a4;
      if (notification.sessionId !== sessionId) {
        return;
      }
      const normalized = this.sessionUpdateNormalizer.normalize(notification.update);
      if (normalized.type !== "message_chunk" || normalized.role !== "assistant") {
        return;
      }
      for (const chunk of normalized.streamChunks) {
        if (chunk.type !== "text") {
          continue;
        }
        accumulatedText += chunk.content;
        (_a4 = config2.onTextChunk) == null ? void 0 : _a4.call(config2, accumulatedText);
      }
    });
    const abortHandler = () => {
      if (this.connection && this.sessionId) {
        this.connection.cancel({ sessionId: this.sessionId });
      }
    };
    (_b2 = config2.abortController) == null ? void 0 : _b2.signal.addEventListener("abort", abortHandler, { once: true });
    try {
      if ((_c = config2.abortController) == null ? void 0 : _c.signal.aborted) {
        throw new Error("Cancelled");
      }
      await this.connection.prompt({
        prompt: [{ type: "text", text: prompt }],
        sessionId
      });
      if ((_d2 = config2.abortController) == null ? void 0 : _d2.signal.aborted) {
        throw new Error("Cancelled");
      }
      return accumulatedText;
    } catch (error48) {
      const message = error48 instanceof Error ? error48.message : "OpenCode request failed";
      const stderr = (_e = this.process) == null ? void 0 : _e.getStderrSnapshot();
      throw new Error(
        stderr ? `${message}

${stderr}` : message,
        error48 instanceof Error ? { cause: error48 } : void 0
      );
    } finally {
      (_f = config2.abortController) == null ? void 0 : _f.signal.removeEventListener("abort", abortHandler);
      removeListener();
    }
  }
  reset() {
    var _a3, _b2;
    this.availableModelIds.clear();
    this.sessionId = null;
    this.sessionCwds.clear();
    this.currentModelId = null;
    this.currentLaunchKey = null;
    (_a3 = this.connection) == null ? void 0 : _a3.dispose();
    this.connection = null;
    (_b2 = this.transport) == null ? void 0 : _b2.dispose();
    this.transport = null;
    if (this.process) {
      void this.process.shutdown().catch(() => {
      });
    }
    this.process = null;
    this.sessionUpdateNormalizer.reset();
  }
  async ensureReady(cwd, systemPrompt) {
    var _a3;
    const resolvedCliPath = (_a3 = this.plugin.getResolvedProviderCliPath("opencode")) != null ? _a3 : "opencode";
    const settings11 = this.plugin.settings;
    const runtimeEnv = buildOpencodeRuntimeEnv(settings11, resolvedCliPath);
    const auxAgentId = OPENCODE_AUX_AGENT_IDS[this.options.agentProfile];
    const artifacts = await prepareOpencodeLaunchArtifacts({
      artifactsSubdir: `opencode/aux/${this.options.artifactPurpose}`,
      defaultAgentId: auxAgentId,
      managedAgents: [buildOpencodeAuxAgentConfig(this.options.agentProfile)],
      runtimeEnv,
      systemPromptKey: systemPrompt,
      systemPromptText: systemPrompt,
      userName: typeof settings11.userName === "string" ? settings11.userName : void 0,
      workspaceRoot: cwd
    });
    const nextLaunchKey = JSON.stringify({
      artifactKey: artifacts.launchKey,
      command: resolvedCliPath,
      configPath: artifacts.configPath,
      envText: getRuntimeEnvironmentText(settings11, "opencode")
    });
    const shouldRestart = !this.process || !this.transport || !this.connection || !this.process.isAlive() || this.currentLaunchKey !== nextLaunchKey;
    if (!shouldRestart) {
      return;
    }
    this.reset();
    await this.startProcess({
      command: resolvedCliPath,
      configPath: artifacts.configPath,
      configContent: artifacts.configContent,
      cwd,
      runtimeEnv
    });
    this.currentLaunchKey = nextLaunchKey;
  }
  async createSession(cwd) {
    var _a3, _b2;
    if (!this.connection) {
      return null;
    }
    try {
      const response = await this.connection.newSession({
        cwd,
        mcpServers: []
      });
      this.syncSessionModelState({
        configOptions: (_a3 = response.configOptions) != null ? _a3 : null,
        models: (_b2 = response.models) != null ? _b2 : null
      });
      await this.connection.setConfigOption({
        configId: "mode",
        sessionId: response.sessionId,
        type: "select",
        value: OPENCODE_AUX_AGENT_IDS[this.options.agentProfile]
      });
      this.sessionId = response.sessionId;
      this.sessionCwds.set(response.sessionId, cwd);
      return response.sessionId;
    } catch (e2) {
      return null;
    }
  }
  async startProcess(params) {
    var _a3, _b2;
    const processEnv = {
      ...process.env,
      ...params.runtimeEnv,
      OPENCODE_CONFIG: params.configPath,
      OPENCODE_CONFIG_CONTENT: params.configContent,
      PATH: params.runtimeEnv.PATH
    };
    this.process = new AcpSubprocess({
      args: ["acp", `--cwd=${params.cwd}`],
      command: params.command,
      cwd: params.cwd,
      env: processEnv
    });
    this.process.start();
    this.transport = new AcpJsonRpcTransport({
      input: this.process.stdout,
      onClose: (listener) => this.process.onClose(listener),
      output: this.process.stdin
    });
    this.connection = new AcpClientConnection({
      clientInfo: {
        name: "claudian-aux",
        version: (_b2 = (_a3 = this.plugin.manifest) == null ? void 0 : _a3.version) != null ? _b2 : "0.0.0"
      },
      delegate: {
        fileSystem: this.options.allowReadTextFile ? {
          readTextFile: (request) => this.readTextFile(request)
        } : void 0,
        requestPermission: (request) => this.handlePermissionRequest(request)
      },
      transport: this.transport
    });
    this.transport.start();
    await this.connection.initialize();
  }
  async readTextFile(request) {
    var _a3;
    const resolvedPath = this.resolveSessionPath(request.sessionId, request.path);
    const content = await fs22.readFile(resolvedPath, "utf-8");
    if (request.line === void 0 && request.limit === void 0) {
      return { content };
    }
    const lines = content.split(/\r?\n/);
    const startIndex = Math.max(0, ((_a3 = request.line) != null ? _a3 : 1) - 1);
    const endIndex = request.limit ? startIndex + Math.max(0, request.limit) : lines.length;
    return {
      content: lines.slice(startIndex, endIndex).join("\n")
    };
  }
  async handlePermissionRequest(request) {
    return selectPermissionOption2(request.options, ["reject_once", "reject_always"]);
  }
  resolveSelectedRawModel(explicitModel) {
    var _a3, _b2;
    const projectedSettings = ProviderSettingsCoordinator.getProviderSettingsSnapshot(
      this.plugin.settings,
      "opencode"
    );
    if (explicitModel) {
      const trimmed = explicitModel.trim();
      if (!trimmed) {
        return void 0;
      }
      return opencodeChatUIConfig.ownsModel(trimmed, projectedSettings) ? (_a3 = decodeOpencodeModelId(trimmed)) != null ? _a3 : void 0 : trimmed;
    }
    const selectedModel = typeof projectedSettings.model === "string" ? projectedSettings.model : "";
    return opencodeChatUIConfig.ownsModel(selectedModel, projectedSettings) ? (_b2 = decodeOpencodeModelId(selectedModel)) != null ? _b2 : void 0 : void 0;
  }
  resolveApplicableModel(selectedModel) {
    if (!selectedModel) {
      return null;
    }
    if (selectedModel === this.currentModelId) {
      return null;
    }
    if (this.availableModelIds.size === 0) {
      return selectedModel;
    }
    return this.availableModelIds.has(selectedModel) ? selectedModel : null;
  }
  syncSessionModelState(params) {
    const state = extractAcpSessionModelState(params);
    this.currentModelId = state.currentModelId;
    this.availableModelIds = new Set(state.availableModels.map((model) => model.id));
  }
  resolveSessionPath(sessionId, rawPath) {
    var _a3, _b2;
    const cwd = (_b2 = (_a3 = this.sessionCwds.get(sessionId)) != null ? _a3 : getVaultPath(this.plugin.app)) != null ? _b2 : process.cwd();
    const resolvedPath = path20.isAbsolute(rawPath) ? path20.resolve(rawPath) : path20.resolve(cwd, rawPath);
    const relative4 = path20.relative(cwd, resolvedPath);
    if (relative4 === "" || !relative4.startsWith("..") && !path20.isAbsolute(relative4)) {
      return resolvedPath;
    }
    throw new Error("OpenCode aux read access is limited to the current workspace.");
  }
};
function buildOpencodeAuxAgentConfig(profile) {
  const id = OPENCODE_AUX_AGENT_IDS[profile];
  if (profile === "readonly") {
    return {
      definition: {
        description: "Internal Claudian read-only agent for OpenCode auxiliary tasks.",
        mode: "primary",
        permission: {
          "*": "deny",
          codesearch: "allow",
          external_directory: "deny",
          glob: "allow",
          grep: "allow",
          lsp: "allow",
          read: OPENCODE_AUX_READ_PERMISSION,
          webfetch: "allow",
          websearch: "allow"
        }
      },
      id
    };
  }
  return {
    definition: {
      description: "Internal Claudian no-tool agent for OpenCode auxiliary tasks.",
      mode: "primary",
      permission: {
        "*": "deny",
        external_directory: "deny"
      }
    },
    id
  };
}
function selectPermissionOption2(options, preferredKinds) {
  for (const kind of preferredKinds) {
    const option = options.find((entry) => entry.kind === kind);
    if (option) {
      return {
        outcome: {
          optionId: option.optionId,
          outcome: "selected"
        }
      };
    }
  }
  return { outcome: { outcome: "cancelled" } };
}

// src/providers/opencode/auxiliary/OpencodeInlineEditService.ts
var OpencodeInlineEditService = class extends QueryBackedInlineEditService {
  constructor(plugin) {
    super(new OpencodeAuxQueryRunner(plugin, {
      agentProfile: "readonly",
      artifactPurpose: "inline",
      allowReadTextFile: true
    }));
  }
};

// src/providers/opencode/auxiliary/OpencodeInstructionRefineService.ts
var OpencodeInstructionRefineService = class extends QueryBackedInstructionRefineService {
  constructor(plugin) {
    super(new OpencodeAuxQueryRunner(plugin, {
      agentProfile: "passive",
      artifactPurpose: "instructions"
    }));
  }
};

// src/providers/opencode/auxiliary/OpencodeTaskResultInterpreter.ts
var OpencodeTaskResultInterpreter = class {
  hasAsyncLaunchMarker(_toolUseResult) {
    return false;
  }
  extractAgentId(_toolUseResult) {
    return null;
  }
  extractStructuredResult(_toolUseResult) {
    return null;
  }
  resolveTerminalStatus(_toolUseResult, fallbackStatus) {
    return fallbackStatus;
  }
  extractTagValue(_payload, _tagName) {
    return null;
  }
};

// src/providers/opencode/auxiliary/OpencodeTitleGenerationService.ts
var OpencodeTitleGenerationService = class extends QueryBackedTitleGenerationService {
  constructor(plugin) {
    super({
      createRunner: () => new OpencodeAuxQueryRunner(plugin, {
        agentProfile: "passive",
        artifactPurpose: "title-gen"
      }),
      resolveModel: () => {
        var _a3;
        const settings11 = plugin.settings;
        const titleModel = typeof settings11.titleGenerationModel === "string" ? settings11.titleGenerationModel : "";
        if (!opencodeChatUIConfig.ownsModel(titleModel, settings11)) {
          return void 0;
        }
        return (_a3 = decodeOpencodeModelId(titleModel)) != null ? _a3 : void 0;
      }
    });
  }
};

// src/providers/opencode/env/OpencodeSettingsReconciler.ts
init_env();
var OPENCODE_ENV_HASH_KEYS = [
  "OPENCODE_CONFIG",
  "OPENCODE_DB",
  "OPENCODE_DISABLE_PROJECT_CONFIG",
  "XDG_DATA_HOME"
];
function computeOpencodeEnvHash(envText) {
  const envVars = parseEnvironmentVariables(envText || "");
  return OPENCODE_ENV_HASH_KEYS.filter((key) => envVars[key]).map((key) => `${key}=${envVars[key]}`).sort().join("|");
}
var opencodeSettingsReconciler = {
  handleEnvironmentChange(settings11) {
    return clearOpencodeDiscoveryState(settings11);
  },
  reconcileModelWithEnvironment(settings11, conversations) {
    const envText = getRuntimeEnvironmentText(settings11, "opencode");
    const currentHash = computeOpencodeEnvHash(envText);
    const savedHash = getOpencodeProviderSettings(settings11).environmentHash;
    if (currentHash === savedHash) {
      return { changed: false, invalidatedConversations: [] };
    }
    const invalidatedConversations = [];
    for (const conversation of conversations) {
      if (conversation.providerId !== "opencode") {
        continue;
      }
      const state = getOpencodeState(conversation.providerState);
      if (!conversation.sessionId && !state.databasePath) {
        continue;
      }
      conversation.sessionId = null;
      conversation.providerState = void 0;
      invalidatedConversations.push(conversation);
    }
    updateOpencodeProviderSettings(settings11, { environmentHash: currentHash });
    return { changed: true, invalidatedConversations };
  },
  normalizeModelVariantSettings(settings11) {
    const hadLegacyDiscoveryFields = hasLegacyOpencodeDiscoveryFields(settings11);
    if (hadLegacyDiscoveryFields) {
      updateOpencodeProviderSettings(settings11, {});
    }
    const opencodeSettings = getOpencodeProviderSettings(settings11);
    let changed = hadLegacyDiscoveryFields;
    const normalizeSelection = (value) => {
      if (typeof value !== "string" || !isOpencodeModelSelectionId(value)) {
        return { baseModelId: null, variant: null };
      }
      const rawModelId = decodeOpencodeModelId(value);
      if (!rawModelId) {
        return { baseModelId: value, variant: null };
      }
      const baseRawId = resolveOpencodeBaseModelRawId(rawModelId, opencodeSettings.discoveredModels);
      return {
        baseModelId: encodeOpencodeModelId(baseRawId),
        variant: extractOpencodeModelVariantValue(rawModelId, opencodeSettings.discoveredModels)
      };
    };
    const modelSelection = normalizeSelection(settings11.model);
    if (typeof settings11.model === "string" && modelSelection.baseModelId && settings11.model !== modelSelection.baseModelId) {
      settings11.model = modelSelection.baseModelId;
      changed = true;
    }
    if (modelSelection.variant && (typeof settings11.effortLevel !== "string" || settings11.effortLevel.trim().length === 0)) {
      settings11.effortLevel = modelSelection.variant;
      changed = true;
    }
    const titleModelSelection = normalizeSelection(settings11.titleGenerationModel);
    if (typeof settings11.titleGenerationModel === "string" && titleModelSelection.baseModelId && settings11.titleGenerationModel !== titleModelSelection.baseModelId) {
      settings11.titleGenerationModel = titleModelSelection.baseModelId;
      changed = true;
    }
    const savedProviderModelRaw = settings11.savedProviderModel;
    if (savedProviderModelRaw && typeof savedProviderModelRaw === "object" && !Array.isArray(savedProviderModelRaw)) {
      const savedProviderModel = savedProviderModelRaw;
      const savedSelection = normalizeSelection(savedProviderModel.opencode);
      if (typeof savedProviderModel.opencode === "string" && savedSelection.baseModelId && savedProviderModel.opencode !== savedSelection.baseModelId) {
        savedProviderModel.opencode = savedSelection.baseModelId;
        changed = true;
      }
      if (savedSelection.variant) {
        const savedEffort = ensureProviderProjectionMap(settings11, "savedProviderEffort");
        if (typeof savedEffort.opencode !== "string") {
          savedEffort.opencode = savedSelection.variant;
          changed = true;
        }
      }
    }
    const normalizedVisibleModels = normalizeOpencodeVisibleModels(
      opencodeSettings.visibleModels,
      opencodeSettings.discoveredModels
    );
    const normalizedPreferredThinking = normalizeOpencodePreferredThinkingByModel(
      opencodeSettings.preferredThinkingByModel,
      opencodeSettings.discoveredModels
    );
    const shouldUpdateProviderSettings = !sameStringList(normalizedVisibleModels, opencodeSettings.visibleModels) || !sameStringMap(normalizedPreferredThinking, opencodeSettings.preferredThinkingByModel);
    if (shouldUpdateProviderSettings) {
      updateOpencodeProviderSettings(settings11, {
        preferredThinkingByModel: normalizedPreferredThinking,
        visibleModels: normalizedVisibleModels
      });
      changed = true;
    }
    if (typeof settings11.effortLevel === "string" && !settings11.effortLevel.trim()) {
      settings11.effortLevel = OPENCODE_DEFAULT_THINKING_LEVEL;
      changed = true;
    }
    return changed;
  }
};

// src/providers/opencode/history/OpencodeHistoryStore.ts
var import_node_child_process2 = require("node:child_process");
var fs23 = __toESM(require("node:fs"));
async function loadOpencodeSessionMessages(sessionId, providerState) {
  const databasePath = resolveExistingOpencodeDatabasePath(providerState == null ? void 0 : providerState.databasePath);
  if (!databasePath || databasePath === ":memory:" || !fs23.existsSync(databasePath)) {
    return [];
  }
  const rows = await loadOpencodeSessionRows(databasePath, sessionId);
  if (!rows) {
    return [];
  }
  return mapOpencodeMessages(
    hydrateStoredMessages(rows.messageRows, rows.partRows)
  );
}
function mapOpencodeMessages(messages) {
  return mergeAdjacentAssistantMessages(messages.map((message) => mapStoredMessage(message)).filter((message) => message !== null));
}
function hydrateStoredMessages(messageRows, partRows) {
  var _a3;
  const partsByMessage = /* @__PURE__ */ new Map();
  for (const row of partRows) {
    const messageId = getString(row.message_id);
    const id = getString(row.id);
    const data = parseJsonObject2(row.data);
    if (!messageId || !id || !data) {
      continue;
    }
    const parts = (_a3 = partsByMessage.get(messageId)) != null ? _a3 : [];
    parts.push({ ...data, id });
    partsByMessage.set(messageId, parts);
  }
  return messageRows.flatMap((row) => {
    var _a4;
    const id = getString(row.id);
    const data = parseJsonObject2(row.data);
    if (!id || !data) {
      return [];
    }
    return [{
      info: { ...data, id, time_created: row.time_created },
      parts: (_a4 = partsByMessage.get(id)) != null ? _a4 : []
    }];
  });
}
function mapStoredMessage(message) {
  var _a3, _b2;
  const role = getString(message.info.role);
  const id = getString(message.info.id);
  if (!id || role !== "user" && role !== "assistant") {
    return null;
  }
  const createdAt = (_b2 = (_a3 = getNestedNumber(message.info, ["time", "created"])) != null ? _a3 : getNumber(message.info.time_created)) != null ? _b2 : Date.now();
  if (role === "user") {
    const promptText = extractUserQuery(getJoinedTextParts(message.parts));
    return {
      assistantMessageId: void 0,
      content: promptText,
      id,
      role: "user",
      timestamp: createdAt,
      userMessageId: id
    };
  }
  const contentBlocks = buildAssistantContentBlocks(message.parts);
  const toolCalls = buildAssistantToolCalls(message.parts);
  const completedAt = getNestedNumber(message.info, ["time", "completed"]);
  const durationSeconds = completedAt && completedAt >= createdAt ? Math.max(0, (completedAt - createdAt) / 1e3) : void 0;
  return {
    assistantMessageId: id,
    content: contentBlocks.filter((block) => block.type === "text").map((block) => block.content).join(""),
    contentBlocks: contentBlocks.length > 0 ? contentBlocks : void 0,
    durationSeconds,
    id,
    role: "assistant",
    timestamp: createdAt,
    toolCalls: toolCalls.length > 0 ? toolCalls : void 0
  };
}
function mergeAdjacentAssistantMessages(messages) {
  var _a3, _b2;
  const merged = [];
  for (const message of messages) {
    const previous = merged[merged.length - 1];
    if (message.role === "assistant" && (previous == null ? void 0 : previous.role) === "assistant" && !message.isInterrupt && !previous.isInterrupt) {
      previous.content += message.content;
      previous.assistantMessageId = (_a3 = message.assistantMessageId) != null ? _a3 : previous.assistantMessageId;
      previous.durationFlavorWord = (_b2 = message.durationFlavorWord) != null ? _b2 : previous.durationFlavorWord;
      previous.durationSeconds = mergeAssistantDurationSeconds(previous, message);
      previous.toolCalls = mergeOptionalArrays(previous.toolCalls, message.toolCalls);
      previous.contentBlocks = mergeOptionalArrays(previous.contentBlocks, message.contentBlocks);
      continue;
    }
    merged.push(message);
  }
  return merged;
}
function mergeOptionalArrays(left, right) {
  if (!(left == null ? void 0 : left.length) && !(right == null ? void 0 : right.length)) {
    return void 0;
  }
  return [
    ...left != null ? left : [],
    ...right != null ? right : []
  ];
}
function mergeAssistantDurationSeconds(first, next) {
  const firstEnd = getMessageCompletionTime(first);
  const nextEnd = getMessageCompletionTime(next);
  if (firstEnd === null && nextEnd === null) {
    return void 0;
  }
  const end = Math.max(firstEnd != null ? firstEnd : first.timestamp, nextEnd != null ? nextEnd : next.timestamp);
  return Math.max(0, (end - first.timestamp) / 1e3);
}
function getMessageCompletionTime(message) {
  if (typeof message.durationSeconds !== "number") {
    return null;
  }
  return message.timestamp + message.durationSeconds * 1e3;
}
function buildAssistantContentBlocks(parts) {
  var _a3;
  const blocks = [];
  for (const part of parts) {
    switch (getString(part.type)) {
      case "reasoning": {
        const text = (_a3 = getString(part.text)) == null ? void 0 : _a3.trim();
        if (!text) {
          break;
        }
        blocks.push({
          content: text,
          durationSeconds: getDurationSeconds(part),
          type: "thinking"
        });
        break;
      }
      case "text": {
        const text = getString(part.text);
        if (!text || getBoolean(part.ignored)) {
          break;
        }
        blocks.push({
          content: text,
          type: "text"
        });
        break;
      }
      case "tool": {
        const toolId = getString(part.callID);
        if (!toolId) {
          break;
        }
        blocks.push({
          toolId,
          type: "tool_use"
        });
        break;
      }
    }
  }
  return blocks;
}
function buildAssistantToolCalls(parts) {
  return parts.flatMap((part) => {
    var _a3, _b2, _c, _d2;
    if (getString(part.type) !== "tool") {
      return [];
    }
    const id = getString(part.callID);
    const rawName = getString(part.tool);
    const state = getObject(part.state);
    const status = mapToolStatus(getString(state == null ? void 0 : state.status));
    if (!id || !rawName || !status) {
      return [];
    }
    const input = normalizeOpencodeToolInput(rawName, (_a3 = getObject(state == null ? void 0 : state.input)) != null ? _a3 : {});
    const name = normalizeOpencodeToolName(rawName);
    const result = (_c = (_b2 = getString(state == null ? void 0 : state.output)) != null ? _b2 : getString(state == null ? void 0 : state.error)) != null ? _c : void 0;
    const toolUseResult = normalizeOpencodeToolUseResult(rawName, input, {
      ...result ? { output: result } : {},
      ...getObject(state == null ? void 0 : state.metadata) ? { metadata: getObject(state == null ? void 0 : state.metadata) } : {}
    });
    const toolCall = {
      id,
      input,
      name,
      result,
      status
    };
    if (name === TOOL_ASK_USER_QUESTION) {
      toolCall.resolvedAnswers = (_d2 = toolUseResult == null ? void 0 : toolUseResult.answers) != null ? _d2 : extractResolvedAnswersFromResultText(result);
    }
    if (status === "completed" && isWriteEditTool(name)) {
      const diffData = extractDiffData(toolUseResult, toolCall);
      if (diffData) {
        toolCall.diffData = diffData;
      }
    }
    return [toolCall];
  });
}
function getJoinedTextParts(parts) {
  return parts.filter((part) => getString(part.type) === "text" && !getBoolean(part.ignored)).map((part) => {
    var _a3;
    return (_a3 = getString(part.text)) != null ? _a3 : "";
  }).join("");
}
function getDurationSeconds(part) {
  const start = getNestedNumber(part, ["time", "start"]);
  const end = getNestedNumber(part, ["time", "end"]);
  if (start === null || end === null || end < start) {
    return void 0;
  }
  return Math.max(0, (end - start) / 1e3);
}
function mapToolStatus(status) {
  switch (status) {
    case "pending":
    case "running":
      return "running";
    case "completed":
      return "completed";
    case "error":
      return "error";
    default:
      return null;
  }
}
function parseJsonObject2(value) {
  if (typeof value !== "string") {
    return null;
  }
  try {
    const parsed = JSON.parse(value);
    return isPlainObject6(parsed) ? parsed : null;
  } catch (e2) {
    return null;
  }
}
function isPlainObject6(value) {
  return value !== null && typeof value === "object" && !Array.isArray(value);
}
function getBoolean(value) {
  return value === true;
}
function getObject(value) {
  return isPlainObject6(value) ? value : null;
}
function getString(value) {
  return typeof value === "string" ? value : null;
}
function getNumber(value) {
  return typeof value === "number" ? value : null;
}
function getNestedNumber(value, keys) {
  let current = value;
  for (const key of keys) {
    if (!isPlainObject6(current)) {
      return null;
    }
    current = current[key];
  }
  return getNumber(current);
}
async function loadSqliteModule() {
  try {
    return await import("node:sqlite");
  } catch (e2) {
    return null;
  }
}
async function loadOpencodeSessionRows(databasePath, sessionId) {
  const viaNodeSqlite = await loadSessionRowsWithNodeSqlite(databasePath, sessionId);
  if (viaNodeSqlite) {
    return viaNodeSqlite;
  }
  return loadSessionRowsWithSqliteCli(databasePath, sessionId);
}
async function loadSessionRowsWithNodeSqlite(databasePath, sessionId) {
  const sqlite = await loadSqliteModule();
  if (!sqlite) {
    return null;
  }
  let db2 = null;
  try {
    db2 = new sqlite.DatabaseSync(databasePath, { readonly: true });
    const messageRows = db2.prepare(
      "select id, time_created, data from message where session_id = ? order by time_created asc, id asc"
    ).all(sessionId);
    const partRows = db2.prepare(
      "select id, message_id, data from part where session_id = ? order by message_id asc, id asc"
    ).all(sessionId);
    return { messageRows, partRows };
  } catch (e2) {
    return null;
  } finally {
    db2 == null ? void 0 : db2.close();
  }
}
function loadSessionRowsWithSqliteCli(databasePath, sessionId) {
  const escapedSessionId = escapeSqlLiteral(sessionId);
  const messageRows = runSqlite3JsonQuery(
    databasePath,
    `select id, time_created, data from message where session_id = '${escapedSessionId}' order by time_created asc, id asc;`
  );
  const partRows = runSqlite3JsonQuery(
    databasePath,
    `select id, message_id, data from part where session_id = '${escapedSessionId}' order by message_id asc, id asc;`
  );
  if (!messageRows || !partRows) {
    return null;
  }
  return { messageRows, partRows };
}
function runSqlite3JsonQuery(databasePath, sql) {
  const result = (0, import_node_child_process2.spawnSync)(
    "sqlite3",
    ["-json", databasePath, sql],
    {
      encoding: "utf8"
    }
  );
  if (result.error || result.status !== 0) {
    return null;
  }
  try {
    const parsed = JSON.parse(result.stdout || "[]");
    return Array.isArray(parsed) ? parsed.filter((row) => isPlainObject6(row)) : null;
  } catch (e2) {
    return null;
  }
}
function escapeSqlLiteral(value) {
  return value.replaceAll("'", "''");
}

// src/providers/opencode/history/OpencodeConversationHistoryService.ts
var OpencodeConversationHistoryService = class {
  constructor() {
    this.hydratedKeys = /* @__PURE__ */ new Map();
  }
  async hydrateConversationHistory(conversation, _vaultPath) {
    var _a3;
    const sessionId = conversation.sessionId;
    if (!sessionId) {
      this.hydratedKeys.delete(conversation.id);
      return;
    }
    const state = getOpencodeState(conversation.providerState);
    const hydrationKey = `${sessionId}::${(_a3 = state.databasePath) != null ? _a3 : ""}`;
    if (conversation.messages.length > 0 && this.hydratedKeys.get(conversation.id) === hydrationKey) {
      return;
    }
    const messages = await loadOpencodeSessionMessages(sessionId, state);
    if (messages.length === 0) {
      this.hydratedKeys.delete(conversation.id);
      return;
    }
    conversation.messages = messages;
    this.hydratedKeys.set(conversation.id, hydrationKey);
  }
  async deleteConversationSession(_conversation, _vaultPath) {
  }
  resolveSessionIdForConversation(conversation) {
    var _a3;
    return (_a3 = conversation == null ? void 0 : conversation.sessionId) != null ? _a3 : null;
  }
  isPendingForkConversation(_conversation) {
    return false;
  }
  buildForkProviderState(_sourceSessionId, _resumeAt, _sourceProviderState) {
    return {};
  }
  buildPersistedProviderState(conversation) {
    const state = getOpencodeState(conversation.providerState);
    const providerState = {
      ...state.databasePath ? { databasePath: state.databasePath } : {}
    };
    return Object.keys(providerState).length > 0 ? providerState : void 0;
  }
};

// src/providers/opencode/registration.ts
var opencodeProviderRegistration = {
  blankTabOrder: 10,
  capabilities: OPENCODE_PROVIDER_CAPABILITIES,
  chatUIConfig: opencodeChatUIConfig,
  createInlineEditService: (plugin) => new OpencodeInlineEditService(plugin),
  createInstructionRefineService: (plugin) => new OpencodeInstructionRefineService(plugin),
  createRuntime: ({ plugin }) => new OpencodeChatRuntime(plugin),
  createTitleGenerationService: (plugin) => new OpencodeTitleGenerationService(plugin),
  displayName: "OpenCode",
  environmentKeyPatterns: [/^OPENCODE_/i],
  historyService: new OpencodeConversationHistoryService(),
  isEnabled: (settings11) => getOpencodeProviderSettings(settings11).enabled,
  settingsReconciler: opencodeSettingsReconciler,
  taskResultInterpreter: new OpencodeTaskResultInterpreter()
};

// src/providers/index.ts
var builtInProvidersRegistered = false;
function registerBuiltInProviders() {
  if (builtInProvidersRegistered) {
    return;
  }
  ProviderRegistry.register("claude", claudeProviderRegistration);
  ProviderRegistry.register("codex", codexProviderRegistration);
  ProviderRegistry.register("opencode", opencodeProviderRegistration);
  ProviderWorkspaceRegistry.register("claude", claudeWorkspaceRegistration);
  ProviderWorkspaceRegistry.register("codex", codexWorkspaceRegistration);
  ProviderWorkspaceRegistry.register("opencode", opencodeWorkspaceRegistration);
  builtInProvidersRegistered = true;
}
registerBuiltInProviders();

// src/main.ts
var import_obsidian47 = require("obsidian");

// src/app/storage/SharedStorageService.ts
var import_obsidian20 = require("obsidian");
var SharedStorageService = class {
  constructor(plugin) {
    this.plugin = plugin;
    this.adapter = new VaultFileAdapter(plugin.app);
    this.claudianSettings = new ClaudianSettingsStorage(this.adapter);
    this.sessions = new SessionStorage(this.adapter);
  }
  async initialize() {
    await this.ensureDirectories();
    const claudian = await this.claudianSettings.load();
    return { claudian };
  }
  async saveClaudianSettings(settings11) {
    await this.claudianSettings.save(settings11);
  }
  async setTabManagerState(state) {
    try {
      const data = await this.plugin.loadData() || {};
      data.tabManagerState = state;
      await this.plugin.saveData(data);
    } catch (e2) {
      new import_obsidian20.Notice("Failed to save tab layout");
    }
  }
  async getTabManagerState() {
    try {
      const data = await this.plugin.loadData();
      if (!(data == null ? void 0 : data.tabManagerState)) {
        return null;
      }
      return this.validateTabManagerState(data.tabManagerState);
    } catch (e2) {
      return null;
    }
  }
  getAdapter() {
    return this.adapter;
  }
  async ensureDirectories() {
    await this.adapter.ensureFolder(CLAUDIAN_STORAGE_PATH);
    await this.adapter.ensureFolder(SESSIONS_PATH);
  }
  validateTabManagerState(data) {
    if (!data || typeof data !== "object") {
      return null;
    }
    const state = data;
    if (!Array.isArray(state.openTabs)) {
      return null;
    }
    const validatedTabs = [];
    for (const tab of state.openTabs) {
      if (!tab || typeof tab !== "object") {
        continue;
      }
      const tabObj = tab;
      if (typeof tabObj.tabId !== "string") {
        continue;
      }
      validatedTabs.push({
        tabId: tabObj.tabId,
        conversationId: typeof tabObj.conversationId === "string" ? tabObj.conversationId : null,
        ...typeof tabObj.draftModel === "string" ? { draftModel: tabObj.draftModel } : {}
      });
    }
    return {
      openTabs: validatedTabs,
      activeTabId: typeof state.activeTabId === "string" ? state.activeTabId : null
    };
  }
};

// src/features/chat/ClaudianView.ts
var import_obsidian44 = require("obsidian");

// src/features/chat/tabs/Tab.ts
var import_obsidian41 = require("obsidian");

// src/core/providers/modelRouting.ts
function getProviderForModel(model, settings11) {
  return ProviderRegistry.resolveProviderForModel(model, settings11);
}
function getEnabledProviderForModel(model, settings11, fallbackProviderId) {
  return ProviderRegistry.resolveProviderForModel(model, settings11, {
    onlyEnabledProviders: true,
    fallbackProviderId
  });
}

// src/core/commands/builtInCommands.ts
var BUILT_IN_COMMANDS = [
  {
    name: "clear",
    aliases: ["new"],
    description: "Start a new conversation",
    action: "clear"
  },
  {
    name: "add-dir",
    description: "Add external context directory",
    action: "add-dir",
    hasArgs: true,
    argumentHint: "[path/to/directory]"
  },
  {
    name: "resume",
    description: "Resume a previous conversation",
    action: "resume",
    requiredCapability: "supportsNativeHistory"
  },
  {
    name: "fork",
    description: "Fork entire conversation to new session",
    action: "fork",
    requiredCapability: "supportsFork"
  }
];
var commandMap = /* @__PURE__ */ new Map();
for (const cmd of BUILT_IN_COMMANDS) {
  commandMap.set(cmd.name.toLowerCase(), cmd);
  if (cmd.aliases) {
    for (const alias of cmd.aliases) {
      commandMap.set(alias.toLowerCase(), cmd);
    }
  }
}
function resolveCapabilities(context) {
  if (typeof context !== "string") {
    return context;
  }
  try {
    return ProviderRegistry.getCapabilities(context);
  } catch (e2) {
    return null;
  }
}
function isBuiltInCommandSupported(command, context) {
  if (!command.requiredCapability || !context) {
    return true;
  }
  const capabilities = resolveCapabilities(context);
  return capabilities ? capabilities[command.requiredCapability] : false;
}
function detectBuiltInCommand(input) {
  const trimmed = input.trim();
  if (!trimmed.startsWith("/")) return null;
  const match = trimmed.match(/^\/([a-zA-Z0-9_-]+)(?:\s(.*))?$/);
  if (!match) return null;
  const cmdName = match[1].toLowerCase();
  const command = commandMap.get(cmdName);
  if (!command) return null;
  const args = (match[2] || "").trim();
  return { command, args };
}
function getBuiltInCommandsForDropdown(context) {
  return BUILT_IN_COMMANDS.filter((cmd) => isBuiltInCommandSupported(cmd, context)).map((cmd) => ({
    id: `builtin:${cmd.name}`,
    name: cmd.name,
    description: cmd.description,
    content: "",
    // Built-in commands don't have prompt content
    argumentHint: cmd.argumentHint
  }));
}

// src/shared/components/SlashCommandDropdown.ts
var SlashCommandDropdown = class {
  constructor(containerEl, inputEl, callbacks, options = {}) {
    this.dropdownEl = null;
    this.enabled = true;
    this.triggerStartIndex = -1;
    this.activeTriggerChar = "/";
    this.selectedIndex = 0;
    this.filteredItems = [];
    this.cachedProviderEntries = [];
    this.providerEntriesFetched = false;
    this.requestId = 0;
    var _a3, _b2, _c, _d2;
    this.containerEl = containerEl;
    this.inputEl = inputEl;
    this.callbacks = callbacks;
    this.isFixed = (_a3 = options.fixed) != null ? _a3 : false;
    this.hiddenCommands = (_b2 = options.hiddenCommands) != null ? _b2 : /* @__PURE__ */ new Set();
    this.providerConfig = (_c = options.providerConfig) != null ? _c : null;
    this.getProviderEntries = (_d2 = options.getProviderEntries) != null ? _d2 : null;
    this.onInput = () => this.handleInputChange();
    this.inputEl.addEventListener("input", this.onInput);
  }
  setEnabled(enabled) {
    this.enabled = enabled;
    if (!enabled) {
      this.hide();
    }
  }
  setHiddenCommands(commands) {
    this.hiddenCommands = commands;
  }
  setProviderCatalog(config2, getEntries) {
    this.providerConfig = config2;
    this.getProviderEntries = getEntries;
    this.cachedProviderEntries = [];
    this.providerEntriesFetched = false;
    this.requestId = 0;
  }
  handleInputChange() {
    var _a3, _b2;
    if (!this.enabled) return;
    const text = this.getInputValue();
    const cursorPos = this.getCursorPosition();
    const textBeforeCursor = text.substring(0, cursorPos);
    const triggerChars = (_b2 = (_a3 = this.providerConfig) == null ? void 0 : _a3.triggerChars) != null ? _b2 : ["/"];
    let triggerIndex = -1;
    let triggerChar = "";
    for (let i2 = cursorPos - 1; i2 >= 0; i2--) {
      const ch = textBeforeCursor.charAt(i2);
      if (/\s/.test(ch)) break;
      if (triggerChars.includes(ch)) {
        if (i2 === 0 || /\s/.test(textBeforeCursor.charAt(i2 - 1))) {
          triggerIndex = i2;
          triggerChar = ch;
        }
        break;
      }
    }
    if (triggerIndex === -1) {
      this.hide();
      return;
    }
    const searchText = textBeforeCursor.substring(triggerIndex + 1);
    if (/\s/.test(searchText)) {
      this.hide();
      return;
    }
    this.triggerStartIndex = triggerIndex;
    this.activeTriggerChar = triggerChar;
    const isAtPosition0 = triggerIndex === 0;
    this.showDropdown(searchText, isAtPosition0);
  }
  handleKeydown(e2) {
    if (!this.enabled || !this.isVisible()) return false;
    switch (e2.key) {
      case "ArrowDown":
        e2.preventDefault();
        this.navigate(1);
        return true;
      case "ArrowUp":
        e2.preventDefault();
        this.navigate(-1);
        return true;
      case "Enter":
      case "Tab":
        if (this.filteredItems.length > 0) {
          e2.preventDefault();
          this.selectItem();
          return true;
        }
        return false;
      case "Escape":
        e2.preventDefault();
        this.hide();
        return true;
    }
    return false;
  }
  isVisible() {
    var _a3, _b2;
    return (_b2 = (_a3 = this.dropdownEl) == null ? void 0 : _a3.hasClass("visible")) != null ? _b2 : false;
  }
  hide() {
    if (this.dropdownEl) {
      this.dropdownEl.removeClass("visible");
    }
    this.triggerStartIndex = -1;
    this.callbacks.onHide();
  }
  destroy() {
    this.inputEl.removeEventListener("input", this.onInput);
    if (this.dropdownEl) {
      this.dropdownEl.remove();
      this.dropdownEl = null;
    }
  }
  resetSdkSkillsCache() {
    this.cachedProviderEntries = [];
    this.providerEntriesFetched = false;
    this.requestId = 0;
  }
  getInputValue() {
    return this.inputEl.value;
  }
  getCursorPosition() {
    return this.inputEl.selectionStart || 0;
  }
  setInputValue(value) {
    this.inputEl.value = value;
  }
  setCursorPosition(pos) {
    this.inputEl.selectionStart = pos;
    this.inputEl.selectionEnd = pos;
  }
  async showDropdown(searchText, isAtPosition0 = true) {
    const currentRequest = ++this.requestId;
    const searchLower = searchText.toLowerCase();
    await this.fetchProviderEntries(currentRequest);
    if (currentRequest !== this.requestId) return;
    const includeBuiltIns = isAtPosition0 && this.activeTriggerChar === "/";
    const allItems = this.buildItemList(includeBuiltIns);
    this.filteredItems = allItems.filter(
      (item) => {
        var _a3;
        return item.name.toLowerCase().includes(searchLower) || ((_a3 = item.description) == null ? void 0 : _a3.toLowerCase().includes(searchLower));
      }
    ).sort((a2, b10) => a2.name.localeCompare(b10.name));
    if (currentRequest !== this.requestId) return;
    if (searchText.length > 0 && this.filteredItems.length === 0) {
      this.hide();
      return;
    }
    this.selectedIndex = 0;
    this.render();
  }
  async fetchProviderEntries(currentRequest) {
    if (this.providerEntriesFetched || !this.getProviderEntries) return;
    try {
      const entries = await this.getProviderEntries();
      if (currentRequest !== this.requestId) return;
      if (entries.length > 0) {
        this.cachedProviderEntries = entries;
        this.providerEntriesFetched = true;
      }
    } catch (e2) {
      if (currentRequest !== this.requestId) return;
    }
  }
  buildItemList(includeBuiltIns) {
    var _a3;
    const seenNames = /* @__PURE__ */ new Set();
    const items = [];
    if (includeBuiltIns) {
      const builtIns = getBuiltInCommandsForDropdown((_a3 = this.providerConfig) == null ? void 0 : _a3.providerId);
      for (const cmd of builtIns) {
        const nameLower = cmd.name.toLowerCase();
        if (!seenNames.has(nameLower)) {
          seenNames.add(nameLower);
          items.push({
            name: cmd.name,
            description: cmd.description,
            argumentHint: cmd.argumentHint,
            content: cmd.content,
            displayPrefix: "/",
            insertPrefix: "/",
            isBuiltIn: true,
            slashCommand: cmd
          });
        }
      }
    }
    for (const entry of this.cachedProviderEntries) {
      const nameLower = entry.name.toLowerCase();
      if (seenNames.has(nameLower) || this.hiddenCommands.has(nameLower)) {
        continue;
      }
      seenNames.add(nameLower);
      items.push({
        name: entry.name,
        description: entry.description,
        argumentHint: entry.argumentHint,
        content: entry.content,
        displayPrefix: entry.displayPrefix,
        insertPrefix: entry.insertPrefix,
        isBuiltIn: false,
        providerEntry: entry,
        slashCommand: {
          id: entry.id,
          name: entry.name,
          description: entry.description,
          content: entry.content,
          argumentHint: entry.argumentHint,
          allowedTools: entry.allowedTools,
          model: entry.model,
          source: entry.source,
          kind: entry.kind,
          disableModelInvocation: entry.disableModelInvocation,
          userInvocable: entry.userInvocable,
          context: entry.context,
          agent: entry.agent,
          hooks: entry.hooks
        }
      });
    }
    return items;
  }
  render() {
    if (!this.dropdownEl) {
      this.dropdownEl = this.createDropdownElement();
    }
    this.dropdownEl.empty();
    if (this.filteredItems.length === 0) {
      const emptyEl = this.dropdownEl.createDiv({ cls: "claudian-slash-empty" });
      emptyEl.setText("No matching commands");
    } else {
      for (let i2 = 0; i2 < this.filteredItems.length; i2++) {
        const item = this.filteredItems[i2];
        const itemEl = this.dropdownEl.createDiv({ cls: "claudian-slash-item" });
        if (i2 === this.selectedIndex) {
          itemEl.addClass("selected");
        }
        const nameEl = itemEl.createSpan({ cls: "claudian-slash-name" });
        nameEl.setText(`${item.displayPrefix}${item.name}`);
        if (item.argumentHint) {
          const hintEl = itemEl.createSpan({ cls: "claudian-slash-hint" });
          hintEl.setText(normalizeArgumentHint(item.argumentHint));
        }
        if (item.description) {
          const descEl = itemEl.createDiv({ cls: "claudian-slash-desc" });
          descEl.setText(item.description);
        }
        itemEl.addEventListener("click", () => {
          this.selectedIndex = i2;
          this.selectItem();
        });
        itemEl.addEventListener("mouseenter", () => {
          this.selectedIndex = i2;
          this.updateSelection();
        });
      }
    }
    this.dropdownEl.addClass("visible");
    if (this.isFixed) {
      this.positionFixed();
    }
  }
  createDropdownElement() {
    if (this.isFixed) {
      return this.containerEl.createDiv({
        cls: "claudian-slash-dropdown claudian-slash-dropdown-fixed"
      });
    } else {
      return this.containerEl.createDiv({ cls: "claudian-slash-dropdown" });
    }
  }
  positionFixed() {
    if (!this.dropdownEl || !this.isFixed) return;
    const inputRect = this.inputEl.getBoundingClientRect();
    this.dropdownEl.style.position = "fixed";
    this.dropdownEl.style.bottom = `${window.innerHeight - inputRect.top + 4}px`;
    this.dropdownEl.style.left = `${inputRect.left}px`;
    this.dropdownEl.style.right = "auto";
    this.dropdownEl.style.width = `${Math.max(inputRect.width, 280)}px`;
    this.dropdownEl.style.zIndex = "10001";
  }
  navigate(direction) {
    const maxIndex = this.filteredItems.length - 1;
    this.selectedIndex = Math.max(0, Math.min(maxIndex, this.selectedIndex + direction));
    this.updateSelection();
  }
  updateSelection() {
    var _a3;
    const items = (_a3 = this.dropdownEl) == null ? void 0 : _a3.querySelectorAll(".claudian-slash-item");
    items == null ? void 0 : items.forEach((item, index) => {
      if (index === this.selectedIndex) {
        item.addClass("selected");
        item.scrollIntoView({ block: "nearest" });
      } else {
        item.removeClass("selected");
      }
    });
  }
  selectItem() {
    if (this.filteredItems.length === 0) return;
    const selected = this.filteredItems[this.selectedIndex];
    if (!selected) return;
    const text = this.getInputValue();
    const beforeTrigger = text.substring(0, this.triggerStartIndex);
    const afterCursor = text.substring(this.getCursorPosition());
    const replacement = `${selected.insertPrefix}${selected.name} `;
    this.setInputValue(beforeTrigger + replacement + afterCursor);
    this.setCursorPosition(beforeTrigger.length + replacement.length);
    this.hide();
    if (selected.slashCommand) {
      this.callbacks.onSelect(selected.slashCommand);
    }
    this.inputEl.focus();
  }
};

// src/features/chat/tabs/Tab.ts
init_env();
init_path();

// src/features/chat/controllers/contextRowVisibility.ts
function updateContextRowHasContent(contextRowEl) {
  const editorIndicator = contextRowEl.querySelector(".claudian-selection-indicator");
  const browserIndicator = contextRowEl.querySelector(".claudian-browser-selection-indicator");
  const canvasIndicator = contextRowEl.querySelector(".claudian-canvas-indicator");
  const fileIndicator = contextRowEl.querySelector(".claudian-file-indicator");
  const imagePreview = contextRowEl.querySelector(".claudian-image-preview");
  const hasEditorSelection = (editorIndicator == null ? void 0 : editorIndicator.style.display) === "block";
  const hasBrowserSelection = browserIndicator !== null && browserIndicator.style.display === "block";
  const hasCanvasSelection = (canvasIndicator == null ? void 0 : canvasIndicator.style.display) === "block";
  const hasFileChips = (fileIndicator == null ? void 0 : fileIndicator.style.display) === "flex";
  const hasImageChips = (imagePreview == null ? void 0 : imagePreview.style.display) === "flex";
  contextRowEl.classList.toggle(
    "has-content",
    hasEditorSelection || hasBrowserSelection || hasCanvasSelection || hasFileChips || hasImageChips
  );
}

// src/features/chat/controllers/BrowserSelectionController.ts
var BROWSER_SELECTION_POLL_INTERVAL = 250;
var BrowserSelectionController = class {
  constructor(app, indicatorEl, inputEl, contextRowEl, onVisibilityChange) {
    this.storedSelection = null;
    this.pollInterval = null;
    this.pollInFlight = false;
    this.app = app;
    this.indicatorEl = indicatorEl;
    this.inputEl = inputEl;
    this.contextRowEl = contextRowEl;
    this.onVisibilityChange = onVisibilityChange != null ? onVisibilityChange : null;
  }
  start() {
    if (this.pollInterval) return;
    this.pollInterval = setInterval(() => {
      void this.poll();
    }, BROWSER_SELECTION_POLL_INTERVAL);
  }
  stop() {
    if (this.pollInterval) {
      clearInterval(this.pollInterval);
      this.pollInterval = null;
    }
    this.clear();
  }
  async poll() {
    if (this.pollInFlight) return;
    this.pollInFlight = true;
    try {
      const browserView = this.getActiveBrowserView();
      if (!browserView) {
        this.clearWhenInputIsNotFocused();
        return;
      }
      const selectedText = await this.extractSelectedText(browserView.containerEl);
      if (selectedText) {
        const nextContext = this.buildContext(browserView.view, browserView.viewType, browserView.containerEl, selectedText);
        if (!this.isSameSelection(nextContext, this.storedSelection)) {
          this.storedSelection = nextContext;
          this.updateIndicator();
        }
      } else {
        this.clearWhenInputIsNotFocused();
      }
    } catch (e2) {
    } finally {
      this.pollInFlight = false;
    }
  }
  getActiveBrowserView() {
    var _a3, _b2, _c, _d2, _e;
    const activeLeaf = (_c = this.app.workspace.activeLeaf) != null ? _c : (_b2 = (_a3 = this.app.workspace).getMostRecentLeaf) == null ? void 0 : _b2.call(_a3);
    const activeView = activeLeaf == null ? void 0 : activeLeaf.view;
    const containerEl = activeView.containerEl;
    if (!activeView || !containerEl) return null;
    const viewType = (_e = (_d2 = activeView.getViewType) == null ? void 0 : _d2.call(activeView)) != null ? _e : "";
    if (!this.isBrowserLikeView(viewType, containerEl)) return null;
    return { view: activeView, viewType, containerEl };
  }
  isBrowserLikeView(viewType, containerEl) {
    const normalized = viewType.toLowerCase();
    if (normalized.includes("surfing") || normalized.includes("browser") || normalized.includes("webview")) {
      return true;
    }
    return Boolean(containerEl.querySelector("iframe, webview"));
  }
  async extractSelectedText(containerEl) {
    const ownerDoc = containerEl.ownerDocument;
    const docSelection = this.extractSelectionFromDocument(ownerDoc, containerEl);
    if (docSelection) return docSelection;
    const frameSelection = this.extractSelectionFromIframes(containerEl);
    if (frameSelection) return frameSelection;
    return await this.extractSelectionFromWebviews(containerEl);
  }
  extractSelectionFromDocument(doc, scopeEl) {
    const selection = doc.getSelection();
    const selectedText = selection == null ? void 0 : selection.toString().trim();
    if (selectedText) {
      const anchorNode = selection == null ? void 0 : selection.anchorNode;
      const focusNode = selection == null ? void 0 : selection.focusNode;
      if (anchorNode && scopeEl.contains(anchorNode) || focusNode && scopeEl.contains(focusNode)) {
        return selectedText;
      }
    }
    return this.extractSelectionFromActiveInput(doc, scopeEl);
  }
  extractSelectionFromActiveInput(doc, scopeEl) {
    const activeEl = doc.activeElement;
    if (!activeEl || !scopeEl.contains(activeEl)) return null;
    if (activeEl instanceof HTMLTextAreaElement || activeEl instanceof HTMLInputElement) {
      const { value, selectionStart, selectionEnd } = activeEl;
      if (typeof selectionStart !== "number" || typeof selectionEnd !== "number" || selectionStart === selectionEnd) return null;
      return value.slice(selectionStart, selectionEnd).trim() || null;
    }
    return null;
  }
  extractSelectionFromIframes(containerEl) {
    var _a3, _b2;
    const iframes = Array.from(containerEl.querySelectorAll("iframe"));
    for (const iframe of iframes) {
      try {
        const frameDoc = (_b2 = iframe.contentDocument) != null ? _b2 : (_a3 = iframe.contentWindow) == null ? void 0 : _a3.document;
        if (!frameDoc || !frameDoc.body) continue;
        const frameSelection = this.extractSelectionFromDocument(frameDoc, frameDoc.body);
        if (frameSelection) return frameSelection;
      } catch (e2) {
      }
    }
    return null;
  }
  async extractSelectionFromWebviews(containerEl) {
    const webviews = Array.from(containerEl.querySelectorAll("webview"));
    for (const webview of webviews) {
      if (typeof webview.executeJavaScript !== "function") continue;
      try {
        const result = await webview.executeJavaScript(
          'window.getSelection ? window.getSelection().toString() : ""',
          true
        );
        if (typeof result === "string" && result.trim()) {
          return result.trim();
        }
      } catch (e2) {
      }
    }
    return null;
  }
  buildContext(view, viewType, containerEl, selectedText) {
    const title = this.extractViewTitle(view);
    const url2 = this.extractViewUrl(view, containerEl);
    const source = url2 ? `browser:${url2}` : `browser:${viewType || "unknown"}`;
    return {
      source,
      selectedText,
      title,
      url: url2
    };
  }
  extractViewTitle(view) {
    var _a3;
    const displayText = (_a3 = view.getDisplayText) == null ? void 0 : _a3.call(view);
    if (displayText == null ? void 0 : displayText.trim()) return displayText.trim();
    const title = view.title;
    return typeof title === "string" && title.trim() ? title.trim() : void 0;
  }
  extractViewUrl(view, containerEl) {
    const rawView = view;
    const directCandidates = [
      rawView.url,
      rawView.currentUrl,
      rawView.currentURL,
      rawView.src
    ];
    for (const candidate of directCandidates) {
      if (typeof candidate === "string" && candidate.trim()) {
        return candidate.trim();
      }
    }
    const embeddableEl = containerEl.querySelector("iframe[src], webview[src]");
    const embeddedSrc = embeddableEl == null ? void 0 : embeddableEl.getAttribute("src");
    if (embeddedSrc == null ? void 0 : embeddedSrc.trim()) {
      return embeddedSrc.trim();
    }
    return void 0;
  }
  isSameSelection(left, right) {
    if (!left || !right) return false;
    return left.source === right.source && left.selectedText === right.selectedText && left.title === right.title && left.url === right.url;
  }
  clearWhenInputIsNotFocused() {
    if (document.activeElement === this.inputEl) return;
    if (this.storedSelection) {
      this.storedSelection = null;
      this.updateIndicator();
    }
  }
  updateIndicator() {
    if (!this.indicatorEl) return;
    if (this.storedSelection) {
      const lineCount = this.storedSelection.selectedText.split(/\r?\n/).length;
      const lineLabel = lineCount === 1 ? "line" : "lines";
      this.indicatorEl.textContent = `${lineCount} ${lineLabel} selected`;
      this.indicatorEl.setAttribute("title", this.buildIndicatorTitle());
      this.indicatorEl.style.display = "block";
    } else {
      this.indicatorEl.style.display = "none";
      this.indicatorEl.textContent = "";
      this.indicatorEl.removeAttribute("title");
    }
    this.updateContextRowVisibility();
  }
  buildIndicatorTitle() {
    if (!this.storedSelection) return "";
    const charCount = this.storedSelection.selectedText.length;
    const charLabel = charCount === 1 ? "char" : "chars";
    const lines = [`${charCount} ${charLabel} selected`, `source=${this.storedSelection.source}`];
    if (this.storedSelection.title) {
      lines.push(`title=${this.storedSelection.title}`);
    }
    if (this.storedSelection.url) {
      lines.push(this.storedSelection.url);
    }
    return lines.join("\n");
  }
  updateContextRowVisibility() {
    var _a3;
    if (!this.contextRowEl) return;
    updateContextRowHasContent(this.contextRowEl);
    (_a3 = this.onVisibilityChange) == null ? void 0 : _a3.call(this);
  }
  getContext() {
    return this.storedSelection;
  }
  hasSelection() {
    return this.storedSelection !== null;
  }
  clear() {
    this.storedSelection = null;
    this.updateIndicator();
  }
};

// src/features/chat/controllers/CanvasSelectionController.ts
var CANVAS_POLL_INTERVAL = 250;
var CanvasSelectionController = class {
  constructor(app, indicatorEl, inputEl, contextRowEl, onVisibilityChange) {
    this.storedSelection = null;
    this.pollInterval = null;
    this.app = app;
    this.indicatorEl = indicatorEl;
    this.inputEl = inputEl;
    this.contextRowEl = contextRowEl;
    this.onVisibilityChange = onVisibilityChange != null ? onVisibilityChange : null;
  }
  start() {
    if (this.pollInterval) return;
    this.pollInterval = setInterval(() => this.poll(), CANVAS_POLL_INTERVAL);
  }
  stop() {
    if (this.pollInterval) {
      clearInterval(this.pollInterval);
      this.pollInterval = null;
    }
    this.clear();
  }
  poll() {
    var _a3;
    const canvasView = this.getCanvasView();
    if (!canvasView) return;
    const canvas = canvasView.canvas;
    if (!(canvas == null ? void 0 : canvas.selection)) return;
    const selection = canvas.selection;
    const canvasPath = (_a3 = canvasView.file) == null ? void 0 : _a3.path;
    if (!canvasPath) return;
    const nodeIds = [...selection].map((node) => node.id).filter(Boolean);
    if (nodeIds.length > 0) {
      const sameSelection = this.storedSelection && this.storedSelection.canvasPath === canvasPath && this.storedSelection.nodeIds.length === nodeIds.length && this.storedSelection.nodeIds.every((id) => nodeIds.includes(id));
      if (!sameSelection) {
        this.storedSelection = { canvasPath, nodeIds };
        this.updateIndicator();
      }
    } else if (document.activeElement !== this.inputEl) {
      if (this.storedSelection) {
        this.storedSelection = null;
        this.updateIndicator();
      }
    }
  }
  getCanvasView() {
    var _a3, _b2, _c, _d2;
    const activeLeaf = (_c = this.app.workspace.activeLeaf) != null ? _c : (_b2 = (_a3 = this.app.workspace).getMostRecentLeaf) == null ? void 0 : _b2.call(_a3);
    const activeView = activeLeaf == null ? void 0 : activeLeaf.view;
    if (((_d2 = activeView == null ? void 0 : activeView.getViewType) == null ? void 0 : _d2.call(activeView)) === "canvas" && activeView.file) {
      return activeView;
    }
    const leaves = this.app.workspace.getLeavesOfType("canvas");
    if (leaves.length === 0) return null;
    const leaf = leaves.find((l2) => l2.view.file);
    return leaf ? leaf.view : null;
  }
  updateIndicator() {
    if (!this.indicatorEl) return;
    if (this.storedSelection) {
      const { nodeIds } = this.storedSelection;
      this.indicatorEl.textContent = nodeIds.length === 1 ? `node "${nodeIds[0]}" selected` : `${nodeIds.length} nodes selected`;
      this.indicatorEl.style.display = "block";
    } else {
      this.indicatorEl.style.display = "none";
    }
    this.updateContextRowVisibility();
  }
  updateContextRowVisibility() {
    var _a3;
    if (!this.contextRowEl) return;
    updateContextRowHasContent(this.contextRowEl);
    (_a3 = this.onVisibilityChange) == null ? void 0 : _a3.call(this);
  }
  getContext() {
    if (!this.storedSelection) return null;
    return {
      canvasPath: this.storedSelection.canvasPath,
      nodeIds: [...this.storedSelection.nodeIds]
    };
  }
  hasSelection() {
    return this.storedSelection !== null;
  }
  clear() {
    this.storedSelection = null;
    this.updateIndicator();
  }
};

// src/features/chat/controllers/ConversationController.ts
var import_obsidian21 = require("obsidian");

// src/features/chat/rendering/collapsible.ts
function setupCollapsible(wrapperEl, headerEl, contentEl, state, options = {}) {
  const { initiallyExpanded = false, onToggle, baseAriaLabel } = options;
  const updateAriaLabel = (isExpanded) => {
    if (baseAriaLabel) {
      const action = isExpanded ? "click to collapse" : "click to expand";
      headerEl.setAttribute("aria-label", `${baseAriaLabel} - ${action}`);
    }
  };
  state.isExpanded = initiallyExpanded;
  if (initiallyExpanded) {
    wrapperEl.addClass("expanded");
    contentEl.style.display = "block";
    headerEl.setAttribute("aria-expanded", "true");
  } else {
    contentEl.style.display = "none";
    headerEl.setAttribute("aria-expanded", "false");
  }
  updateAriaLabel(initiallyExpanded);
  const toggleExpand = () => {
    state.isExpanded = !state.isExpanded;
    if (state.isExpanded) {
      wrapperEl.addClass("expanded");
      contentEl.style.display = "block";
      headerEl.setAttribute("aria-expanded", "true");
    } else {
      wrapperEl.removeClass("expanded");
      contentEl.style.display = "none";
      headerEl.setAttribute("aria-expanded", "false");
    }
    updateAriaLabel(state.isExpanded);
    onToggle == null ? void 0 : onToggle(state.isExpanded);
  };
  headerEl.addEventListener("click", toggleExpand);
  headerEl.addEventListener("keydown", (e2) => {
    if (e2.key === "Enter" || e2.key === " ") {
      e2.preventDefault();
      toggleExpand();
    }
  });
}
function collapseElement(wrapperEl, headerEl, contentEl, state) {
  state.isExpanded = false;
  wrapperEl.removeClass("expanded");
  contentEl.style.display = "none";
  headerEl.setAttribute("aria-expanded", "false");
}

// src/features/chat/rendering/ThinkingBlockRenderer.ts
function createThinkingBlock(parentEl, renderContent) {
  const wrapperEl = parentEl.createDiv({ cls: "claudian-thinking-block" });
  const header = wrapperEl.createDiv({ cls: "claudian-thinking-header" });
  header.setAttribute("tabindex", "0");
  header.setAttribute("role", "button");
  header.setAttribute("aria-expanded", "false");
  header.setAttribute("aria-label", "Extended thinking - click to expand");
  const labelEl = header.createSpan({ cls: "claudian-thinking-label" });
  const startTime = Date.now();
  labelEl.setText("Thinking 0s...");
  const timerInterval = setInterval(() => {
    const elapsed = Math.floor((Date.now() - startTime) / 1e3);
    labelEl.setText(`Thinking ${elapsed}s...`);
  }, 1e3);
  const contentEl = wrapperEl.createDiv({ cls: "claudian-thinking-content" });
  const state = {
    wrapperEl,
    contentEl,
    labelEl,
    content: "",
    startTime,
    timerInterval,
    isExpanded: false
  };
  setupCollapsible(wrapperEl, header, contentEl, state);
  return state;
}
function finalizeThinkingBlock(state) {
  if (state.timerInterval) {
    clearInterval(state.timerInterval);
    state.timerInterval = null;
  }
  const durationSeconds = Math.floor((Date.now() - state.startTime) / 1e3);
  state.labelEl.setText(`Thought for ${durationSeconds}s`);
  const header = state.wrapperEl.querySelector(".claudian-thinking-header");
  if (header) {
    collapseElement(state.wrapperEl, header, state.contentEl, state);
  }
  return durationSeconds;
}
function cleanupThinkingBlock(state) {
  if (state == null ? void 0 : state.timerInterval) {
    clearInterval(state.timerInterval);
  }
}
function renderStoredThinkingBlock(parentEl, content, durationSeconds, renderContent) {
  const wrapperEl = parentEl.createDiv({ cls: "claudian-thinking-block" });
  const header = wrapperEl.createDiv({ cls: "claudian-thinking-header" });
  header.setAttribute("tabindex", "0");
  header.setAttribute("role", "button");
  header.setAttribute("aria-label", "Extended thinking - click to expand");
  const labelEl = header.createSpan({ cls: "claudian-thinking-label" });
  const labelText = durationSeconds !== void 0 ? `Thought for ${durationSeconds}s` : "Thought";
  labelEl.setText(labelText);
  const contentEl = wrapperEl.createDiv({ cls: "claudian-thinking-content" });
  renderContent(contentEl, content);
  const state = { isExpanded: false };
  setupCollapsible(wrapperEl, header, contentEl, state);
  return wrapperEl;
}

// src/features/chat/rewind.ts
function findRewindContext(messages, userIndex) {
  let prevAssistantUuid;
  for (let i2 = userIndex - 1; i2 >= 0; i2--) {
    if (messages[i2].role === "assistant" && messages[i2].assistantMessageId) {
      prevAssistantUuid = messages[i2].assistantMessageId;
      break;
    }
  }
  let hasResponse = false;
  for (let i2 = userIndex + 1; i2 < messages.length; i2++) {
    if (messages[i2].role === "user") break;
    if (messages[i2].role === "assistant" && messages[i2].assistantMessageId) {
      hasResponse = true;
      break;
    }
  }
  return { prevAssistantUuid, hasResponse };
}

// src/features/chat/controllers/ConversationController.ts
var ConversationController = class {
  constructor(deps, callbacks = {}) {
    this.deps = deps;
    this.callbacks = callbacks;
  }
  getAgentService() {
    var _a3, _b2, _c;
    return (_c = (_b2 = (_a3 = this.deps).getAgentService) == null ? void 0 : _b2.call(_a3)) != null ? _c : null;
  }
  // ============================================
  // Conversation Lifecycle
  // ============================================
  /**
   * Resets to entry point state (New Chat).
   *
   * Entry point is a blank UI state - no conversation is created until the
   * first message is sent. This prevents empty conversations cluttering history.
   */
  async createNew(options = {}) {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k;
    const { plugin, state, subagentManager } = this.deps;
    const force = !!options.force;
    if (state.isStreaming && !force) return;
    if (state.isCreatingConversation) return;
    if (state.isSwitchingConversation) return;
    state.isCreatingConversation = true;
    try {
      (_b2 = (_a3 = this.deps).dismissPendingInlinePrompts) == null ? void 0 : _b2.call(_a3);
      if (force && state.isStreaming) {
        state.cancelRequested = true;
        state.bumpStreamGeneration();
        (_c = this.getAgentService()) == null ? void 0 : _c.cancel();
      }
      if (state.currentConversationId && state.messages.length > 0) {
        await this.save();
      }
      subagentManager.orphanAllActive();
      subagentManager.clear();
      cleanupThinkingBlock(state.currentThinkingState);
      state.currentContentEl = null;
      state.currentTextEl = null;
      state.currentTextContent = "";
      state.currentThinkingState = null;
      state.toolCallElements.clear();
      state.writeEditStates.clear();
      state.isStreaming = false;
      state.currentConversationId = null;
      state.clearMessages();
      state.usage = null;
      state.currentTodos = null;
      state.pendingNewSessionPlan = null;
      state.planFilePath = null;
      state.prePlanPermissionMode = null;
      state.autoScrollEnabled = (_d2 = plugin.settings.enableAutoScroll) != null ? _d2 : true;
      state.hasPendingConversationSave = false;
      (_e = this.getAgentService()) == null ? void 0 : _e.syncConversationState(
        null,
        plugin.settings.persistentExternalContextPaths || []
      );
      const messagesEl = this.deps.getMessagesEl();
      messagesEl.empty();
      const welcomeEl = messagesEl.createDiv({ cls: "claudian-welcome" });
      welcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: this.getGreeting() });
      this.deps.setWelcomeEl(welcomeEl);
      (_f = this.deps.getStatusPanel()) == null ? void 0 : _f.remount();
      this.deps.getInputEl().value = "";
      const fileCtx = this.deps.getFileContextManager();
      fileCtx == null ? void 0 : fileCtx.resetForNewConversation();
      fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile();
      (_g = this.deps.getImageContextManager()) == null ? void 0 : _g.clearImages();
      (_h = this.deps.getMcpServerSelector()) == null ? void 0 : _h.clearEnabled();
      (_i = this.deps.getExternalContextSelector()) == null ? void 0 : _i.clearExternalContexts(
        plugin.settings.persistentExternalContextPaths || []
      );
      this.deps.clearQueuedMessage();
      (_k = (_j2 = this.callbacks).onNewConversation) == null ? void 0 : _k.call(_j2);
    } finally {
      state.isCreatingConversation = false;
    }
  }
  /**
   * Loads the current tab conversation, or starts at entry point if none.
   *
   * Entry point (no conversation) shows welcome screen without
   * creating a conversation. Conversation is created lazily on first message.
   */
  async loadActive() {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2;
    const { plugin, state, renderer } = this.deps;
    const conversationId = state.currentConversationId;
    const conversation = conversationId ? await plugin.getConversationById(conversationId) : null;
    if (!conversation) {
      state.currentConversationId = null;
      state.clearMessages();
      state.usage = null;
      state.currentTodos = null;
      state.pendingNewSessionPlan = null;
      state.planFilePath = null;
      state.prePlanPermissionMode = null;
      state.autoScrollEnabled = (_a3 = plugin.settings.enableAutoScroll) != null ? _a3 : true;
      state.hasPendingConversationSave = false;
      (_b2 = this.getAgentService()) == null ? void 0 : _b2.syncConversationState(
        null,
        plugin.settings.persistentExternalContextPaths || []
      );
      const fileCtx = this.deps.getFileContextManager();
      fileCtx == null ? void 0 : fileCtx.resetForNewConversation();
      fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile();
      (_c = this.deps.getExternalContextSelector()) == null ? void 0 : _c.clearExternalContexts(
        plugin.settings.persistentExternalContextPaths || []
      );
      (_d2 = this.deps.getMcpServerSelector()) == null ? void 0 : _d2.clearEnabled();
      const welcomeEl = renderer.renderMessages(
        [],
        () => this.getGreeting()
      );
      this.deps.setWelcomeEl(welcomeEl);
      this.updateWelcomeVisibility();
      (_f = (_e = this.callbacks).onConversationLoaded) == null ? void 0 : _f.call(_e);
      return;
    }
    await ((_h = (_g = this.deps).ensureServiceForConversation) == null ? void 0 : _h.call(_g, conversation));
    this.restoreConversation(conversation, { autoAttachFile: true });
    this.updateWelcomeVisibility();
    (_j2 = (_i = this.callbacks).onConversationLoaded) == null ? void 0 : _j2.call(_i);
  }
  /** Switches to a different conversation. */
  async switchTo(id) {
    var _a3, _b2, _c, _d2, _e, _f, _g;
    const { plugin, state, subagentManager } = this.deps;
    if (id === state.currentConversationId) return;
    if (state.isStreaming) return;
    if (state.isSwitchingConversation) return;
    if (state.isCreatingConversation) return;
    state.isSwitchingConversation = true;
    try {
      (_b2 = (_a3 = this.deps).dismissPendingInlinePrompts) == null ? void 0 : _b2.call(_a3);
      await this.save();
      subagentManager.orphanAllActive();
      subagentManager.clear();
      const conversation = await plugin.switchConversation(id);
      if (!conversation) {
        return;
      }
      await ((_d2 = (_c = this.deps).ensureServiceForConversation) == null ? void 0 : _d2.call(_c, conversation));
      this.deps.getInputEl().value = "";
      this.deps.clearQueuedMessage();
      this.restoreConversation(conversation);
      (_e = this.deps.getHistoryDropdown()) == null ? void 0 : _e.removeClass("visible");
      this.updateWelcomeVisibility();
      (_g = (_f = this.callbacks).onConversationSwitched) == null ? void 0 : _g.call(_f);
    } finally {
      state.isSwitchingConversation = false;
    }
  }
  async rewind(userMessageId) {
    var _a3, _b2, _c;
    const { plugin, state, renderer } = this.deps;
    const agentServiceForCheck = this.getAgentService();
    if (agentServiceForCheck && !agentServiceForCheck.getCapabilities().supportsRewind) {
      new import_obsidian21.Notice(t("chat.rewind.failed", { error: "Rewind is not supported by this provider." }));
      return;
    }
    if (state.isStreaming) {
      new import_obsidian21.Notice(t("chat.rewind.unavailableStreaming"));
      return;
    }
    const msgs = state.messages;
    const userIdx = msgs.findIndex((m2) => m2.id === userMessageId);
    if (userIdx === -1) {
      new import_obsidian21.Notice(t("chat.rewind.failed", { error: "Message not found" }));
      return;
    }
    const userMsg = msgs[userIdx];
    if (!userMsg.userMessageId) {
      new import_obsidian21.Notice(t("chat.rewind.unavailableNoUuid"));
      return;
    }
    const rewindCtx = findRewindContext(msgs, userIdx);
    if (!rewindCtx.hasResponse || !rewindCtx.prevAssistantUuid) {
      new import_obsidian21.Notice(t("chat.rewind.unavailableNoUuid"));
      return;
    }
    const prevAssistantUuid = rewindCtx.prevAssistantUuid;
    const confirmed = await confirm2(
      plugin.app,
      t("chat.rewind.confirmMessage"),
      t("chat.rewind.confirmButton")
    );
    if (!confirmed) return;
    if (state.isStreaming) {
      new import_obsidian21.Notice(t("chat.rewind.unavailableStreaming"));
      return;
    }
    const agentService = this.getAgentService();
    if (!agentService) {
      new import_obsidian21.Notice(t("chat.rewind.failed", { error: "Agent service not available" }));
      return;
    }
    let result;
    try {
      result = await agentService.rewind(userMsg.userMessageId, prevAssistantUuid);
    } catch (e2) {
      new import_obsidian21.Notice(t("chat.rewind.failed", { error: e2 instanceof Error ? e2.message : "Unknown error" }));
      return;
    }
    if (!result.canRewind) {
      new import_obsidian21.Notice(t("chat.rewind.cannot", { error: (_a3 = result.error) != null ? _a3 : "Unknown error" }));
      return;
    }
    state.truncateAt(userMessageId);
    const inputEl = this.deps.getInputEl();
    inputEl.value = userMsg.content;
    inputEl.focus();
    const welcomeEl = renderer.renderMessages(state.messages, () => this.getGreeting());
    this.deps.setWelcomeEl(welcomeEl);
    this.updateWelcomeVisibility();
    const filesChanged = (_c = (_b2 = result.filesChanged) == null ? void 0 : _b2.length) != null ? _c : 0;
    let saveError = null;
    try {
      await this.save(false, { resumeAtMessageId: prevAssistantUuid });
    } catch (e2) {
      saveError = e2 instanceof Error ? e2.message : "Failed to save";
    }
    if (saveError) {
      new import_obsidian21.Notice(t("chat.rewind.noticeSaveFailed", { count: String(filesChanged), error: saveError }));
      return;
    }
    new import_obsidian21.Notice(t("chat.rewind.notice", { count: String(filesChanged) }));
  }
  /**
   * Saves the current conversation.
   *
   * If we're at an entry point (no conversation yet) and have messages,
   * creates a new conversation first (lazy creation).
   *
   * For native sessions (new conversations with sessionId from SDK),
   * only metadata is saved - the SDK handles message persistence.
   */
  async save(updateLastResponse = false, options) {
    var _a3, _b2, _c, _d2, _e;
    const { plugin, state } = this.deps;
    if (!state.currentConversationId && state.messages.length === 0) {
      return;
    }
    const agentService = this.getAgentService();
    const sessionInvalidated = (_b2 = (_a3 = agentService == null ? void 0 : agentService.consumeSessionInvalidation) == null ? void 0 : _a3.call(agentService)) != null ? _b2 : false;
    if (!state.currentConversationId && state.messages.length > 0) {
      const initialSessionId = (_c = agentService == null ? void 0 : agentService.getSessionId()) != null ? _c : void 0;
      const conversation2 = await plugin.createConversation({
        providerId: agentService == null ? void 0 : agentService.providerId,
        sessionId: initialSessionId
      });
      state.currentConversationId = conversation2.id;
    }
    const fileCtx = this.deps.getFileContextManager();
    const currentNote = (fileCtx == null ? void 0 : fileCtx.getCurrentNotePath()) || void 0;
    const externalContextSelector = this.deps.getExternalContextSelector();
    const externalContextPaths = (_d2 = externalContextSelector == null ? void 0 : externalContextSelector.getExternalContexts()) != null ? _d2 : [];
    const mcpServerSelector = this.deps.getMcpServerSelector();
    const enabledMcpServers = mcpServerSelector ? Array.from(mcpServerSelector.getEnabledServers()) : [];
    const conversation = plugin.getConversationSync(state.currentConversationId);
    const { updates: sessionUpdates } = agentService ? agentService.buildSessionUpdates({ conversation, sessionInvalidated }) : { updates: {} };
    const updates = {
      ...sessionUpdates,
      messages: state.messages,
      currentNote,
      externalContextPaths: externalContextPaths.length > 0 ? externalContextPaths : void 0,
      usage: (_e = state.usage) != null ? _e : void 0,
      enabledMcpServers: enabledMcpServers.length > 0 ? enabledMcpServers : void 0
    };
    if (updateLastResponse) {
      updates.lastResponseAt = Date.now();
    }
    if (options) {
      updates.resumeAtMessageId = options.resumeAtMessageId;
    }
    await plugin.updateConversation(state.currentConversationId, updates);
    state.hasPendingConversationSave = false;
  }
  /**
   * Shared logic for restoring a conversation into the current tab.
   * Used by both loadActive() and switchTo() to avoid duplication.
   */
  restoreConversation(conversation, options) {
    var _a3, _b2, _c;
    const { plugin, state, renderer } = this.deps;
    state.currentConversationId = conversation.id;
    state.messages = [...conversation.messages];
    state.usage = (_a3 = conversation.usage) != null ? _a3 : null;
    state.autoScrollEnabled = (_b2 = plugin.settings.enableAutoScroll) != null ? _b2 : true;
    state.hasPendingConversationSave = false;
    state.currentTodos = null;
    const hasMessages = state.messages.length > 0;
    const externalContextPaths = hasMessages ? conversation.externalContextPaths || [] : plugin.settings.persistentExternalContextPaths || [];
    (_c = this.getAgentService()) == null ? void 0 : _c.syncConversationState(conversation, externalContextPaths);
    const fileCtx = this.deps.getFileContextManager();
    fileCtx == null ? void 0 : fileCtx.resetForLoadedConversation(hasMessages);
    if (conversation.currentNote) {
      fileCtx == null ? void 0 : fileCtx.setCurrentNote(conversation.currentNote);
    } else if (!hasMessages && (options == null ? void 0 : options.autoAttachFile)) {
      fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile();
    }
    this.restoreExternalContextPaths(conversation.externalContextPaths, !hasMessages);
    const mcpServerSelector = this.deps.getMcpServerSelector();
    if (conversation.enabledMcpServers && conversation.enabledMcpServers.length > 0) {
      mcpServerSelector == null ? void 0 : mcpServerSelector.setEnabledServers(conversation.enabledMcpServers);
    } else {
      mcpServerSelector == null ? void 0 : mcpServerSelector.clearEnabled();
    }
    const welcomeEl = renderer.renderMessages(
      state.messages,
      () => this.getGreeting()
    );
    this.deps.setWelcomeEl(welcomeEl);
  }
  /**
   * Restores external context paths based on session state.
   * New or empty sessions get current persistent paths from settings.
   * Sessions with messages restore exactly what was saved.
   */
  restoreExternalContextPaths(savedPaths, isEmptySession) {
    const { plugin } = this.deps;
    const externalContextSelector = this.deps.getExternalContextSelector();
    if (!externalContextSelector) {
      return;
    }
    if (isEmptySession) {
      externalContextSelector.clearExternalContexts(
        plugin.settings.persistentExternalContextPaths || []
      );
    } else {
      externalContextSelector.setExternalContexts(savedPaths || []);
    }
  }
  // ============================================
  // History Dropdown
  // ============================================
  toggleHistoryDropdown() {
    const dropdown = this.deps.getHistoryDropdown();
    if (!dropdown) return;
    const isVisible = dropdown.hasClass("visible");
    if (isVisible) {
      dropdown.removeClass("visible");
    } else {
      this.updateHistoryDropdown();
      dropdown.addClass("visible");
    }
  }
  updateHistoryDropdown() {
    const dropdown = this.deps.getHistoryDropdown();
    if (!dropdown) return;
    this.renderHistoryItems(dropdown, {
      onSelectConversation: (id) => this.switchTo(id),
      onRerender: () => this.updateHistoryDropdown()
    });
  }
  /**
   * Renders history dropdown items to a container.
   * Shared implementation for updateHistoryDropdown() and renderHistoryDropdown().
   */
  renderHistoryItems(container, options) {
    var _a3;
    const { plugin, state } = this.deps;
    container.empty();
    const dropdownHeader = container.createDiv({ cls: "claudian-history-header" });
    dropdownHeader.createSpan({ text: "Conversations" });
    const list = container.createDiv({ cls: "claudian-history-list" });
    const allConversations = plugin.getConversationList();
    if (allConversations.length === 0) {
      list.createDiv({ cls: "claudian-history-empty", text: "No conversations" });
      return;
    }
    const conversations = [...allConversations].sort((a2, b10) => {
      var _a4, _b2;
      return ((_a4 = b10.lastResponseAt) != null ? _a4 : b10.createdAt) - ((_b2 = a2.lastResponseAt) != null ? _b2 : a2.createdAt);
    });
    for (const conv of conversations) {
      const isCurrent = conv.id === state.currentConversationId;
      const item = list.createDiv({
        cls: `claudian-history-item${isCurrent ? " active" : ""}`
      });
      const iconEl = item.createDiv({ cls: "claudian-history-item-icon" });
      (0, import_obsidian21.setIcon)(iconEl, isCurrent ? "message-square-dot" : "message-square");
      const content = item.createDiv({ cls: "claudian-history-item-content" });
      const titleEl = content.createDiv({ cls: "claudian-history-item-title", text: conv.title });
      titleEl.setAttribute("title", conv.title);
      content.createDiv({
        cls: "claudian-history-item-date",
        text: isCurrent ? "Current session" : this.formatDate((_a3 = conv.lastResponseAt) != null ? _a3 : conv.createdAt)
      });
      if (!isCurrent) {
        content.addEventListener("click", async (e2) => {
          e2.stopPropagation();
          if (this.isHistoryNewTabModifierClick(e2) && options.onOpenConversationInNewTab) {
            e2.preventDefault();
            await this.runHistoryAction(
              () => {
                var _a4;
                return (_a4 = options.onOpenConversationInNewTab) == null ? void 0 : _a4.call(options, conv.id, true);
              },
              "Failed to load conversation"
            );
            return;
          }
          await this.runHistoryAction(
            () => options.onSelectConversation(conv.id),
            "Failed to load conversation"
          );
        });
        if (options.onOpenConversationInNewTab) {
          content.addEventListener("auxclick", async (e2) => {
            if (e2.button !== 1) return;
            e2.preventDefault();
            e2.stopPropagation();
            await this.runHistoryAction(
              () => {
                var _a4;
                return (_a4 = options.onOpenConversationInNewTab) == null ? void 0 : _a4.call(options, conv.id, true);
              },
              "Failed to load conversation"
            );
          });
        }
      }
      item.addEventListener("contextmenu", (e2) => {
        e2.preventDefault();
        e2.stopPropagation();
        this.showHistoryContextMenu(item, conv.id, conv.title, isCurrent, options, e2);
      });
      const actions = item.createDiv({ cls: "claudian-history-item-actions" });
      if (conv.titleGenerationStatus === "pending") {
        const loadingEl = actions.createEl("span", { cls: "claudian-action-btn claudian-action-loading" });
        (0, import_obsidian21.setIcon)(loadingEl, "loader-2");
        loadingEl.setAttribute("aria-label", "Generating title...");
      } else if (conv.titleGenerationStatus === "failed") {
        const regenerateBtn = actions.createEl("button", { cls: "claudian-action-btn" });
        (0, import_obsidian21.setIcon)(regenerateBtn, "refresh-cw");
        regenerateBtn.setAttribute("aria-label", "Regenerate title");
        regenerateBtn.addEventListener("click", async (e2) => {
          e2.stopPropagation();
          try {
            await this.regenerateTitle(conv.id);
          } catch (e4) {
            new import_obsidian21.Notice("Failed to regenerate response");
          }
        });
      }
      const renameBtn = actions.createEl("button", { cls: "claudian-action-btn" });
      (0, import_obsidian21.setIcon)(renameBtn, "pencil");
      renameBtn.setAttribute("aria-label", "Rename");
      renameBtn.addEventListener("click", (e2) => {
        e2.stopPropagation();
        this.showRenameInput(item, conv.id, conv.title);
      });
      const deleteBtn = actions.createEl("button", { cls: "claudian-action-btn claudian-delete-btn" });
      (0, import_obsidian21.setIcon)(deleteBtn, "trash-2");
      deleteBtn.setAttribute("aria-label", "Delete");
      deleteBtn.addEventListener("click", async (e2) => {
        e2.stopPropagation();
        await this.runHistoryAction(
          () => this.deleteHistoryConversation(conv.id, options),
          "Failed to delete conversation"
        );
      });
    }
  }
  isHistoryNewTabModifierClick(event) {
    return !event.altKey && !event.shiftKey && (event.metaKey || event.ctrlKey);
  }
  async runHistoryAction(action, errorMessage) {
    try {
      await action();
    } catch (e2) {
      new import_obsidian21.Notice(errorMessage);
    }
  }
  showHistoryContextMenu(item, conversationId, title, isCurrent, options, event) {
    var _a3, _b2;
    const menu = new import_obsidian21.Menu();
    const openState = (_b2 = (_a3 = options.getConversationOpenState) == null ? void 0 : _a3.call(options, conversationId)) != null ? _b2 : isCurrent ? "current" : "closed";
    if (!isCurrent) {
      if (openState === "closed" && options.onOpenConversationInNewTab) {
        menu.addItem((menuItem) => menuItem.setTitle("Open in New Tab").onClick(() => {
          void this.runHistoryAction(
            () => {
              var _a4;
              return (_a4 = options.onOpenConversationInNewTab) == null ? void 0 : _a4.call(options, conversationId, true);
            },
            "Failed to load conversation"
          );
        }));
        menu.addItem((menuItem) => menuItem.setTitle("Open in Background Tab").onClick(() => {
          void this.runHistoryAction(
            () => {
              var _a4;
              return (_a4 = options.onOpenConversationInNewTab) == null ? void 0 : _a4.call(options, conversationId, false);
            },
            "Failed to load conversation"
          );
        }));
      } else if (openState === "open") {
        menu.addItem((menuItem) => menuItem.setTitle("Switch to Open Session").onClick(() => {
          void this.runHistoryAction(
            () => options.onSelectConversation(conversationId),
            "Failed to load conversation"
          );
        }));
      }
    }
    menu.addItem((menuItem) => menuItem.setTitle("Rename").onClick(() => {
      this.showRenameInput(item, conversationId, title);
    }));
    menu.addItem((menuItem) => menuItem.setTitle("Delete").onClick(() => {
      void this.runHistoryAction(
        () => this.deleteHistoryConversation(conversationId, options),
        "Failed to delete conversation"
      );
    }));
    menu.showAtMouseEvent(event);
  }
  async deleteHistoryConversation(conversationId, options) {
    const { plugin, state } = this.deps;
    if (state.isStreaming) return;
    await plugin.deleteConversation(conversationId);
    options.onRerender();
    if (conversationId === state.currentConversationId) {
      await this.loadActive();
    }
  }
  /** Shows inline rename input for a conversation. */
  showRenameInput(item, convId, currentTitle) {
    const titleEl = item.querySelector(".claudian-history-item-title");
    if (!titleEl) return;
    const input = document.createElement("input");
    input.type = "text";
    input.className = "claudian-rename-input";
    input.value = currentTitle;
    titleEl.replaceWith(input);
    input.focus();
    input.select();
    const finishRename = async () => {
      try {
        const newTitle = input.value.trim() || currentTitle;
        await this.deps.plugin.renameConversation(convId, newTitle);
        this.updateHistoryDropdown();
      } catch (e2) {
        new import_obsidian21.Notice("Failed to rename conversation");
      }
    };
    input.addEventListener("blur", finishRename);
    input.addEventListener("keydown", async (e2) => {
      if (e2.key === "Enter" && !e2.isComposing) {
        input.blur();
      } else if (e2.key === "Escape" && !e2.isComposing) {
        input.value = currentTitle;
        input.blur();
      }
    });
  }
  // ============================================
  // Welcome & Greeting
  // ============================================
  /** Generates a dynamic greeting based on time/day. */
  getGreeting() {
    var _a3;
    const now = /* @__PURE__ */ new Date();
    const hour = now.getHours();
    const day = now.getDay();
    const name = (_a3 = this.deps.plugin.settings.userName) == null ? void 0 : _a3.trim();
    const personalize = (base, noNameFallback) => name ? `${base}, ${name}` : noNameFallback != null ? noNameFallback : base;
    const dayGreetings = {
      0: [personalize("Happy Sunday"), "Sunday session?", "Welcome to the weekend"],
      1: [personalize("Happy Monday"), personalize("Back at it", "Back at it!")],
      2: [personalize("Happy Tuesday")],
      3: [personalize("Happy Wednesday")],
      4: [personalize("Happy Thursday")],
      5: [personalize("Happy Friday"), personalize("That Friday feeling")],
      6: [personalize("Happy Saturday", "Happy Saturday!"), personalize("Welcome to the weekend")]
    };
    const getTimeGreetings = () => {
      if (hour >= 5 && hour < 12) {
        return [personalize("Good morning"), "Coffee and Claudian time?"];
      } else if (hour >= 12 && hour < 18) {
        return [personalize("Good afternoon"), personalize("Hey there"), personalize("How's it going") + "?"];
      } else if (hour >= 18 && hour < 22) {
        return [personalize("Good evening"), personalize("Evening"), personalize("How was your day") + "?"];
      } else {
        return ["Hello, night owl", personalize("Evening")];
      }
    };
    const generalGreetings = [
      personalize("Hey there"),
      name ? `Hi ${name}, how are you?` : "Hi, how are you?",
      personalize("How's it going") + "?",
      personalize("Welcome back") + "!",
      personalize("What's new") + "?",
      ...name ? [`${name} returns!`] : [],
      "You are absolutely right!"
    ];
    const allGreetings = [
      ...dayGreetings[day] || [],
      ...getTimeGreetings(),
      ...generalGreetings
    ];
    return allGreetings[Math.floor(Math.random() * allGreetings.length)];
  }
  /** Updates welcome element visibility based on message count. */
  updateWelcomeVisibility() {
    const welcomeEl = this.deps.getWelcomeEl();
    if (!welcomeEl) return;
    if (this.deps.state.messages.length === 0) {
      welcomeEl.style.display = "";
    } else {
      welcomeEl.style.display = "none";
    }
  }
  /**
   * Initializes the welcome greeting for a new tab without a conversation.
   * Called when a new tab is activated and has no conversation loaded.
   */
  initializeWelcome() {
    const welcomeEl = this.deps.getWelcomeEl();
    if (!welcomeEl) return;
    const fileCtx = this.deps.getFileContextManager();
    fileCtx == null ? void 0 : fileCtx.resetForNewConversation();
    fileCtx == null ? void 0 : fileCtx.autoAttachActiveFile();
    if (!welcomeEl.querySelector(".claudian-welcome-greeting")) {
      welcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: this.getGreeting() });
    }
    this.updateWelcomeVisibility();
  }
  // ============================================
  // Utilities
  // ============================================
  /** Generates a fallback title from the first message (used when AI fails). */
  generateFallbackTitle(firstMessage) {
    const firstSentence = firstMessage.split(/[.!?\n]/)[0].trim();
    const autoTitle = firstSentence.substring(0, 50);
    const suffix = firstSentence.length > 50 ? "..." : "";
    return `${autoTitle}${suffix}`;
  }
  /** Regenerates AI title for a conversation. */
  async regenerateTitle(conversationId) {
    const { plugin } = this.deps;
    if (!plugin.settings.enableAutoTitleGeneration) return;
    const fullConv = await plugin.getConversationById(conversationId);
    if (!fullConv || fullConv.messages.length < 1) return;
    const titleService = this.deps.getTitleGenerationService();
    if (!titleService) return;
    const firstUserMsg = fullConv.messages.find((m2) => m2.role === "user");
    if (!firstUserMsg) return;
    const userContent = firstUserMsg.displayContent || firstUserMsg.content;
    const expectedTitle = fullConv.title;
    await plugin.updateConversation(conversationId, { titleGenerationStatus: "pending" });
    this.updateHistoryDropdown();
    await titleService.generateTitle(
      conversationId,
      userContent,
      async (convId, result) => {
        const currentConv = await plugin.getConversationById(convId);
        if (!currentConv) return;
        const userManuallyRenamed = currentConv.title !== expectedTitle;
        if (result.success && !userManuallyRenamed) {
          await plugin.renameConversation(convId, result.title);
          await plugin.updateConversation(convId, { titleGenerationStatus: "success" });
        } else if (!userManuallyRenamed) {
          await plugin.updateConversation(convId, { titleGenerationStatus: "failed" });
        } else {
          await plugin.updateConversation(convId, { titleGenerationStatus: void 0 });
        }
        this.updateHistoryDropdown();
      }
    );
  }
  /** Formats a timestamp for display. */
  formatDate(timestamp) {
    const date7 = new Date(timestamp);
    const now = /* @__PURE__ */ new Date();
    if (date7.toDateString() === now.toDateString()) {
      return date7.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", hour12: false });
    }
    return date7.toLocaleDateString(void 0, { month: "short", day: "numeric" });
  }
  // ============================================
  // History Dropdown Rendering (for ClaudianView)
  // ============================================
  /**
   * Renders the history dropdown content to a provided container.
   * Used by ClaudianView to render the dropdown with custom selection callback.
   */
  renderHistoryDropdown(container, options) {
    this.renderHistoryItems(container, {
      ...options,
      onRerender: () => this.renderHistoryDropdown(container, options)
    });
  }
};

// src/features/chat/controllers/InputController.ts
var import_obsidian26 = require("obsidian");

// src/shared/components/ResumeSessionDropdown.ts
var import_obsidian22 = require("obsidian");
var ResumeSessionDropdown = class {
  constructor(containerEl, inputEl, conversations, currentConversationId, callbacks) {
    this.selectedIndex = 0;
    this.containerEl = containerEl;
    this.inputEl = inputEl;
    this.conversations = this.sortConversations(conversations);
    this.currentConversationId = currentConversationId;
    this.callbacks = callbacks;
    this.dropdownEl = this.containerEl.createDiv({ cls: "claudian-resume-dropdown" });
    this.render();
    this.dropdownEl.addClass("visible");
    this.onInput = () => this.dismiss();
    this.inputEl.addEventListener("input", this.onInput);
  }
  handleKeydown(e2) {
    if (!this.isVisible()) return false;
    switch (e2.key) {
      case "ArrowDown":
        e2.preventDefault();
        this.navigate(1);
        return true;
      case "ArrowUp":
        e2.preventDefault();
        this.navigate(-1);
        return true;
      case "Enter":
      case "Tab":
        if (this.conversations.length > 0) {
          e2.preventDefault();
          this.selectItem();
          return true;
        }
        return false;
      case "Escape":
        e2.preventDefault();
        this.dismiss();
        return true;
    }
    return false;
  }
  isVisible() {
    var _a3, _b2;
    return (_b2 = (_a3 = this.dropdownEl) == null ? void 0 : _a3.hasClass("visible")) != null ? _b2 : false;
  }
  destroy() {
    var _a3;
    this.inputEl.removeEventListener("input", this.onInput);
    (_a3 = this.dropdownEl) == null ? void 0 : _a3.remove();
  }
  dismiss() {
    this.dropdownEl.removeClass("visible");
    this.callbacks.onDismiss();
  }
  selectItem() {
    if (this.conversations.length === 0) return;
    const selected = this.conversations[this.selectedIndex];
    if (!selected) return;
    if (selected.id === this.currentConversationId) {
      this.dismiss();
      return;
    }
    this.callbacks.onSelect(selected.id);
  }
  navigate(direction) {
    const maxIndex = this.conversations.length - 1;
    this.selectedIndex = Math.max(0, Math.min(maxIndex, this.selectedIndex + direction));
    this.updateSelection();
  }
  updateSelection() {
    const items = this.dropdownEl.querySelectorAll(".claudian-resume-item");
    items == null ? void 0 : items.forEach((item, index) => {
      if (index === this.selectedIndex) {
        item.addClass("selected");
        item.scrollIntoView({ block: "nearest" });
      } else {
        item.removeClass("selected");
      }
    });
  }
  sortConversations(conversations) {
    return [...conversations].sort((a2, b10) => {
      var _a3, _b2;
      return ((_a3 = b10.lastResponseAt) != null ? _a3 : b10.createdAt) - ((_b2 = a2.lastResponseAt) != null ? _b2 : a2.createdAt);
    });
  }
  render() {
    var _a3;
    this.dropdownEl.empty();
    const header = this.dropdownEl.createDiv({ cls: "claudian-resume-header" });
    header.createSpan({ text: "Resume conversation" });
    if (this.conversations.length === 0) {
      this.dropdownEl.createDiv({ cls: "claudian-resume-empty", text: "No conversations" });
      return;
    }
    const list = this.dropdownEl.createDiv({ cls: "claudian-resume-list" });
    for (let i2 = 0; i2 < this.conversations.length; i2++) {
      const conv = this.conversations[i2];
      const isCurrent = conv.id === this.currentConversationId;
      const item = list.createDiv({ cls: "claudian-resume-item" });
      if (isCurrent) item.addClass("current");
      if (i2 === this.selectedIndex) item.addClass("selected");
      const iconEl = item.createDiv({ cls: "claudian-resume-item-icon" });
      (0, import_obsidian22.setIcon)(iconEl, isCurrent ? "message-square-dot" : "message-square");
      const content = item.createDiv({ cls: "claudian-resume-item-content" });
      const titleEl = content.createDiv({ cls: "claudian-resume-item-title", text: conv.title });
      titleEl.setAttribute("title", conv.title);
      content.createDiv({
        cls: "claudian-resume-item-date",
        text: isCurrent ? "Current session" : this.formatDate((_a3 = conv.lastResponseAt) != null ? _a3 : conv.createdAt)
      });
      item.addEventListener("click", () => {
        if (isCurrent) {
          this.dismiss();
          return;
        }
        this.callbacks.onSelect(conv.id);
      });
      item.addEventListener("mouseenter", () => {
        this.selectedIndex = i2;
        this.updateSelection();
      });
    }
  }
  formatDate(timestamp) {
    const date7 = new Date(timestamp);
    const now = /* @__PURE__ */ new Date();
    if (date7.toDateString() === now.toDateString()) {
      return date7.toLocaleTimeString(void 0, { hour: "2-digit", minute: "2-digit", hour12: false });
    }
    return date7.toLocaleDateString(void 0, { month: "short", day: "numeric" });
  }
};

// src/shared/modals/InstructionConfirmModal.ts
var import_obsidian23 = require("obsidian");
var InstructionModal = class extends import_obsidian23.Modal {
  constructor(app, rawInstruction, callbacks) {
    super(app);
    this.state = "loading";
    this.resolved = false;
    // UI elements
    this.contentSectionEl = null;
    this.loadingEl = null;
    this.clarificationEl = null;
    this.confirmationEl = null;
    this.buttonsEl = null;
    // Clarification state
    this.clarificationTextEl = null;
    this.responseTextarea = null;
    this.isSubmitting = false;
    // Confirmation state
    this.refinedInstruction = "";
    this.editTextarea = null;
    this.isEditing = false;
    this.refinedDisplayEl = null;
    this.editContainerEl = null;
    this.editBtnEl = null;
    this.rawInstruction = rawInstruction;
    this.callbacks = callbacks;
  }
  onOpen() {
    const { contentEl } = this;
    contentEl.addClass("claudian-instruction-modal");
    this.setTitle("Add Custom Instruction");
    const inputSection = contentEl.createDiv({ cls: "claudian-instruction-section" });
    const inputLabel = inputSection.createDiv({ cls: "claudian-instruction-label" });
    inputLabel.setText("Your input:");
    const inputText = inputSection.createDiv({ cls: "claudian-instruction-original" });
    inputText.setText(this.rawInstruction);
    this.contentSectionEl = contentEl.createDiv({ cls: "claudian-instruction-content-section" });
    this.loadingEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-loading" });
    this.loadingEl.createDiv({ cls: "claudian-instruction-spinner" });
    this.loadingEl.createSpan({ text: "Processing your instruction..." });
    this.clarificationEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-clarification-section" });
    this.clarificationEl.style.display = "none";
    this.clarificationTextEl = this.clarificationEl.createDiv({ cls: "claudian-instruction-clarification" });
    const responseSection = this.clarificationEl.createDiv({ cls: "claudian-instruction-section" });
    const responseLabel = responseSection.createDiv({ cls: "claudian-instruction-label" });
    responseLabel.setText("Your response:");
    this.responseTextarea = new import_obsidian23.TextAreaComponent(responseSection);
    this.responseTextarea.inputEl.addClass("claudian-instruction-response-textarea");
    this.responseTextarea.inputEl.rows = 3;
    this.responseTextarea.inputEl.placeholder = "Provide more details...";
    this.responseTextarea.inputEl.addEventListener("keydown", (e2) => {
      if (e2.key === "Enter" && !e2.shiftKey && !e2.isComposing && !this.isSubmitting) {
        e2.preventDefault();
        this.submitClarification();
      }
    });
    this.confirmationEl = this.contentSectionEl.createDiv({ cls: "claudian-instruction-confirmation-section" });
    this.confirmationEl.style.display = "none";
    const refinedSection = this.confirmationEl.createDiv({ cls: "claudian-instruction-section" });
    const refinedLabel = refinedSection.createDiv({ cls: "claudian-instruction-label" });
    refinedLabel.setText("Refined snippet:");
    this.refinedDisplayEl = refinedSection.createDiv({ cls: "claudian-instruction-refined" });
    this.editContainerEl = refinedSection.createDiv({ cls: "claudian-instruction-edit-container" });
    this.editContainerEl.style.display = "none";
    this.editTextarea = new import_obsidian23.TextAreaComponent(this.editContainerEl);
    this.editTextarea.inputEl.addClass("claudian-instruction-edit-textarea");
    this.editTextarea.inputEl.rows = 4;
    this.buttonsEl = contentEl.createDiv({ cls: "claudian-instruction-buttons" });
    this.updateButtons();
    this.showState("loading");
  }
  showClarification(clarification) {
    var _a3;
    if (this.clarificationTextEl) {
      this.clarificationTextEl.setText(clarification);
    }
    if (this.responseTextarea) {
      this.responseTextarea.setValue("");
    }
    this.isSubmitting = false;
    this.showState("clarification");
    (_a3 = this.responseTextarea) == null ? void 0 : _a3.inputEl.focus();
  }
  showConfirmation(refinedInstruction) {
    this.refinedInstruction = refinedInstruction;
    if (this.refinedDisplayEl) {
      this.refinedDisplayEl.setText(refinedInstruction);
    }
    if (this.editTextarea) {
      this.editTextarea.setValue(refinedInstruction);
    }
    this.showState("confirmation");
  }
  showError(error48) {
    this.resolved = true;
    this.close();
  }
  showClarificationLoading() {
    this.isSubmitting = true;
    if (this.loadingEl) {
      this.loadingEl.querySelector(".claudian-instruction-spinner");
      const text = this.loadingEl.querySelector("span");
      if (text) text.textContent = "Processing...";
    }
    this.showState("loading");
  }
  showState(state) {
    this.state = state;
    if (this.loadingEl) {
      this.loadingEl.style.display = state === "loading" ? "flex" : "none";
    }
    if (this.clarificationEl) {
      this.clarificationEl.style.display = state === "clarification" ? "block" : "none";
    }
    if (this.confirmationEl) {
      this.confirmationEl.style.display = state === "confirmation" ? "block" : "none";
    }
    this.updateButtons();
  }
  updateButtons() {
    if (!this.buttonsEl) return;
    this.buttonsEl.empty();
    const cancelBtn = this.buttonsEl.createEl("button", {
      text: "Cancel",
      cls: "claudian-instruction-btn claudian-instruction-reject-btn",
      attr: { "aria-label": "Cancel" }
    });
    cancelBtn.addEventListener("click", () => this.handleReject());
    if (this.state === "clarification") {
      const submitBtn = this.buttonsEl.createEl("button", {
        text: "Submit",
        cls: "claudian-instruction-btn claudian-instruction-accept-btn",
        attr: { "aria-label": "Submit response" }
      });
      submitBtn.addEventListener("click", () => this.submitClarification());
    } else if (this.state === "confirmation") {
      this.editBtnEl = this.buttonsEl.createEl("button", {
        text: "Edit",
        cls: "claudian-instruction-btn claudian-instruction-edit-btn",
        attr: { "aria-label": "Edit instruction" }
      });
      this.editBtnEl.addEventListener("click", () => this.toggleEdit());
      const acceptBtn = this.buttonsEl.createEl("button", {
        text: "Accept",
        cls: "claudian-instruction-btn claudian-instruction-accept-btn",
        attr: { "aria-label": "Accept instruction" }
      });
      acceptBtn.addEventListener("click", () => this.handleAccept());
      acceptBtn.focus();
    }
  }
  async submitClarification() {
    var _a3;
    const response = (_a3 = this.responseTextarea) == null ? void 0 : _a3.getValue().trim();
    if (!response || this.isSubmitting) return;
    this.showClarificationLoading();
    try {
      await this.callbacks.onClarificationSubmit(response);
    } catch (e2) {
      this.isSubmitting = false;
      this.showState("clarification");
    }
  }
  toggleEdit() {
    var _a3, _b2;
    this.isEditing = !this.isEditing;
    if (this.isEditing) {
      if (this.refinedDisplayEl) this.refinedDisplayEl.style.display = "none";
      if (this.editContainerEl) this.editContainerEl.style.display = "block";
      if (this.editBtnEl) this.editBtnEl.setText("Preview");
      (_a3 = this.editTextarea) == null ? void 0 : _a3.inputEl.focus();
    } else {
      const edited = ((_b2 = this.editTextarea) == null ? void 0 : _b2.getValue()) || this.refinedInstruction;
      this.refinedInstruction = edited;
      if (this.refinedDisplayEl) {
        this.refinedDisplayEl.setText(edited);
        this.refinedDisplayEl.style.display = "block";
      }
      if (this.editContainerEl) this.editContainerEl.style.display = "none";
      if (this.editBtnEl) this.editBtnEl.setText("Edit");
    }
  }
  handleAccept() {
    var _a3;
    if (this.resolved) return;
    this.resolved = true;
    const finalInstruction = this.isEditing ? ((_a3 = this.editTextarea) == null ? void 0 : _a3.getValue()) || this.refinedInstruction : this.refinedInstruction;
    this.callbacks.onAccept(finalInstruction);
    this.close();
  }
  handleReject() {
    if (this.resolved) return;
    this.resolved = true;
    this.callbacks.onReject();
    this.close();
  }
  onClose() {
    if (!this.resolved) {
      this.resolved = true;
      this.callbacks.onReject();
    }
    this.contentEl.empty();
  }
};

// src/utils/markdown.ts
function appendMarkdownSnippet(existingPrompt, snippet) {
  const trimmedSnippet = snippet.trim();
  if (!trimmedSnippet) {
    return existingPrompt;
  }
  if (!existingPrompt.trim()) {
    return trimmedSnippet;
  }
  const separator = existingPrompt.endsWith("\n\n") ? "" : existingPrompt.endsWith("\n") ? "\n" : "\n\n";
  return existingPrompt + separator + trimmedSnippet;
}

// src/features/chat/constants.ts
var COMPLETION_FLAVOR_WORDS = [
  "Baked",
  "Cooked",
  "Crunched",
  "Brewed",
  "Crafted",
  "Forged",
  "Conjured",
  "Whipped up",
  "Stirred",
  "Simmered",
  "Toasted",
  "Saut\xE9ed",
  "Finagled",
  "Marinated",
  "Distilled",
  "Fermented",
  "Percolated",
  "Steeped",
  "Roasted",
  "Cured",
  "Smoked",
  "Cogitated"
];
var FLAVOR_TEXTS = [
  // Classic
  "Thinking...",
  "Pondering...",
  "Processing...",
  "Analyzing...",
  "Considering...",
  "Working on it...",
  "Vibing...",
  "One moment...",
  "On it...",
  // Thoughtful
  "Ruminating...",
  "Contemplating...",
  "Reflecting...",
  "Mulling it over...",
  "Let me think...",
  "Hmm...",
  "Cogitating...",
  "Deliberating...",
  "Weighing options...",
  "Gathering thoughts...",
  // Playful
  "Brewing ideas...",
  "Connecting dots...",
  "Assembling thoughts...",
  "Spinning up neurons...",
  "Loading brilliance...",
  "Consulting the oracle...",
  "Summoning knowledge...",
  "Crunching thoughts...",
  "Dusting off neurons...",
  "Wrangling ideas...",
  "Herding thoughts...",
  "Juggling concepts...",
  "Untangling this...",
  "Piecing it together...",
  // Cozy
  "Sipping coffee...",
  "Warming up...",
  "Getting cozy with this...",
  "Settling in...",
  "Making tea...",
  "Grabbing a snack...",
  // Technical
  "Parsing...",
  "Compiling thoughts...",
  "Running inference...",
  "Querying the void...",
  "Defragmenting brain...",
  "Allocating memory...",
  "Optimizing...",
  "Indexing...",
  "Syncing neurons...",
  // Zen
  "Breathing...",
  "Finding clarity...",
  "Channeling focus...",
  "Centering...",
  "Aligning chakras...",
  "Meditating on this...",
  // Whimsical
  "Asking the stars...",
  "Reading tea leaves...",
  "Shaking the magic 8-ball...",
  "Consulting ancient scrolls...",
  "Decoding the matrix...",
  "Communing with the ether...",
  "Peering into the abyss...",
  "Channeling the cosmos...",
  // Action
  "Diving in...",
  "Rolling up sleeves...",
  "Getting to work...",
  "Tackling this...",
  "On the case...",
  "Investigating...",
  "Exploring...",
  "Digging deeper...",
  // Casual
  "Bear with me...",
  "Hang tight...",
  "Just a sec...",
  "Working my magic...",
  "Almost there...",
  "Give me a moment..."
];

// src/features/chat/rendering/InlineAskUserQuestion.ts
var HINTS_TEXT = "Enter to select \xB7 Tab/Arrow keys to navigate \xB7 Esc to cancel";
var HINTS_TEXT_IMMEDIATE = "Enter to select \xB7 Arrow keys to navigate \xB7 Esc to cancel";
var InlineAskUserQuestion = class {
  constructor(containerEl, input, resolve8, signal, config2) {
    this.resolved = false;
    this.questions = [];
    this.answers = /* @__PURE__ */ new Map();
    this.customInputs = /* @__PURE__ */ new Map();
    this.activeTabIndex = 0;
    this.focusedItemIndex = 0;
    this.isInputFocused = false;
    this.tabElements = [];
    this.currentItems = [];
    this.abortHandler = null;
    var _a3, _b2, _c;
    this.containerEl = containerEl;
    this.input = input;
    this.resolveCallback = resolve8;
    this.signal = signal;
    this.config = {
      title: (_a3 = config2 == null ? void 0 : config2.title) != null ? _a3 : "Question",
      headerEl: config2 == null ? void 0 : config2.headerEl,
      showCustomInput: (_b2 = config2 == null ? void 0 : config2.showCustomInput) != null ? _b2 : true,
      immediateSelect: (_c = config2 == null ? void 0 : config2.immediateSelect) != null ? _c : false
    };
    this.boundKeyDown = this.handleKeyDown.bind(this);
  }
  render() {
    this.rootEl = this.containerEl.createDiv({ cls: "claudian-ask-question-inline" });
    const titleEl = this.rootEl.createDiv({ cls: "claudian-ask-inline-title" });
    titleEl.setText(this.config.title);
    if (this.config.headerEl) {
      this.rootEl.appendChild(this.config.headerEl);
    }
    this.questions = this.parseQuestions();
    if (this.questions.length === 0) {
      this.handleResolve(null);
      return;
    }
    if (this.config.immediateSelect && this.questions.length !== 1) {
      this.config.immediateSelect = false;
    }
    for (let i2 = 0; i2 < this.questions.length; i2++) {
      this.answers.set(i2, /* @__PURE__ */ new Set());
      this.customInputs.set(i2, "");
    }
    if (!this.config.immediateSelect) {
      this.tabBar = this.rootEl.createDiv({ cls: "claudian-ask-tab-bar" });
      this.renderTabBar();
    }
    this.contentArea = this.rootEl.createDiv({ cls: "claudian-ask-content" });
    this.renderTabContent();
    this.rootEl.setAttribute("tabindex", "0");
    this.rootEl.addEventListener("keydown", this.boundKeyDown);
    requestAnimationFrame(() => {
      this.rootEl.focus();
      this.rootEl.scrollIntoView({ block: "nearest", behavior: "smooth" });
    });
    if (this.signal) {
      this.abortHandler = () => this.handleResolve(null);
      this.signal.addEventListener("abort", this.abortHandler, { once: true });
    }
  }
  destroy() {
    this.handleResolve(null);
  }
  parseQuestions() {
    const raw = this.input.questions;
    if (!Array.isArray(raw)) return [];
    return raw.filter(
      (q10) => typeof q10 === "object" && q10 !== null && typeof q10.question === "string" && (Array.isArray(q10.options) && q10.options.length > 0 || q10.isOther === true)
    ).map((q10, idx) => {
      var _a3;
      return {
        question: q10.question,
        id: typeof q10.id === "string" ? q10.id : void 0,
        header: typeof q10.header === "string" ? q10.header.slice(0, 12) : `Q${idx + 1}`,
        options: this.deduplicateOptions(((_a3 = q10.options) != null ? _a3 : []).map((o2) => this.coerceOption(o2))),
        multiSelect: q10.multiSelect === true,
        isOther: q10.isOther === true,
        isSecret: q10.isSecret === true
      };
    });
  }
  coerceOption(opt) {
    if (typeof opt === "object" && opt !== null) {
      const obj = opt;
      const label = this.extractLabel(obj);
      const description = typeof obj.description === "string" ? obj.description : "";
      const value = this.extractValue(obj, label);
      return { label, description, ...value !== label ? { value } : {} };
    }
    return { label: typeof opt === "string" ? opt : String(opt), description: "" };
  }
  deduplicateOptions(options) {
    const seen = /* @__PURE__ */ new Set();
    return options.filter((o2) => {
      if (seen.has(o2.label)) return false;
      seen.add(o2.label);
      return true;
    });
  }
  extractLabel(obj) {
    if (typeof obj.label === "string") return obj.label;
    if (typeof obj.value === "string") return obj.value;
    if (typeof obj.text === "string") return obj.text;
    if (typeof obj.name === "string") return obj.name;
    return String(obj);
  }
  extractValue(obj, fallback) {
    if (typeof obj.value === "string") return obj.value;
    if (typeof obj.id === "string") return obj.id;
    return fallback;
  }
  renderTabBar() {
    this.tabBar.empty();
    this.tabElements = [];
    for (let idx = 0; idx < this.questions.length; idx++) {
      const answered = this.isQuestionAnswered(idx);
      const tab = this.tabBar.createSpan({ cls: "claudian-ask-tab" });
      tab.createSpan({ text: this.questions[idx].header, cls: "claudian-ask-tab-label" });
      tab.createSpan({ text: answered ? " \u2713" : "", cls: "claudian-ask-tab-tick" });
      tab.setAttribute("title", this.questions[idx].question);
      if (idx === this.activeTabIndex) tab.addClass("is-active");
      if (answered) tab.addClass("is-answered");
      tab.addEventListener("click", () => this.switchTab(idx));
      this.tabElements.push(tab);
    }
    const allAnswered = this.questions.every((_10, i2) => this.isQuestionAnswered(i2));
    const submitTab = this.tabBar.createSpan({ cls: "claudian-ask-tab" });
    submitTab.createSpan({ text: allAnswered ? "\u2713 " : "", cls: "claudian-ask-tab-submit-check" });
    submitTab.createSpan({ text: "Submit", cls: "claudian-ask-tab-label" });
    if (this.activeTabIndex === this.questions.length) submitTab.addClass("is-active");
    submitTab.addEventListener("click", () => this.switchTab(this.questions.length));
    this.tabElements.push(submitTab);
  }
  isQuestionAnswered(idx) {
    return this.answers.get(idx).size > 0 || this.customInputs.get(idx).trim().length > 0;
  }
  switchTab(index) {
    const clamped = Math.max(0, Math.min(index, this.questions.length));
    if (clamped === this.activeTabIndex) return;
    this.activeTabIndex = clamped;
    this.focusedItemIndex = 0;
    this.isInputFocused = false;
    if (!this.config.immediateSelect) {
      this.renderTabBar();
    }
    this.renderTabContent();
    this.rootEl.focus();
  }
  renderTabContent() {
    this.contentArea.empty();
    this.currentItems = [];
    if (this.activeTabIndex < this.questions.length) {
      this.renderQuestionTab(this.activeTabIndex);
    } else {
      this.renderSubmitTab();
    }
  }
  renderQuestionTab(idx) {
    var _a3;
    const q10 = this.questions[idx];
    const isMulti = q10.multiSelect;
    const selected = this.answers.get(idx);
    this.contentArea.createDiv({
      text: q10.question,
      cls: "claudian-ask-question-text"
    });
    const listEl = this.contentArea.createDiv({ cls: "claudian-ask-list" });
    for (let optIdx = 0; optIdx < q10.options.length; optIdx++) {
      const option = q10.options[optIdx];
      const isFocused = optIdx === this.focusedItemIndex;
      const optionValue = this.getOptionValue(option);
      const isSelected = selected.has(optionValue);
      const row = listEl.createDiv({ cls: "claudian-ask-item" });
      if (isFocused) row.addClass("is-focused");
      if (isSelected) row.addClass("is-selected");
      row.createSpan({ text: isFocused ? "\u203A" : "\xA0", cls: "claudian-ask-cursor" });
      row.createSpan({ text: `${optIdx + 1}. `, cls: "claudian-ask-item-num" });
      if (isMulti) {
        this.renderMultiSelectCheckbox(row, isSelected);
      }
      const labelBlock = row.createDiv({ cls: "claudian-ask-item-content" });
      const labelRow = labelBlock.createDiv({ cls: "claudian-ask-label-row" });
      labelRow.createSpan({ text: option.label, cls: "claudian-ask-item-label" });
      if (!isMulti && isSelected) {
        labelRow.createSpan({ text: " \u2713", cls: "claudian-ask-check-mark" });
      }
      if (option.description) {
        labelBlock.createDiv({ text: option.description, cls: "claudian-ask-item-desc" });
      }
      row.addEventListener("click", () => {
        this.focusedItemIndex = optIdx;
        this.updateFocusIndicator();
        this.selectOption(idx, option);
      });
      this.currentItems.push(row);
    }
    if (this.canShowCustomInputForQuestion(q10)) {
      const customIdx = q10.options.length;
      const customFocused = customIdx === this.focusedItemIndex;
      const customText = (_a3 = this.customInputs.get(idx)) != null ? _a3 : "";
      const hasCustomText = customText.trim().length > 0;
      const customRow = listEl.createDiv({ cls: "claudian-ask-item claudian-ask-custom-item" });
      if (customFocused) customRow.addClass("is-focused");
      customRow.createSpan({ text: customFocused ? "\u203A" : "\xA0", cls: "claudian-ask-cursor" });
      customRow.createSpan({ text: `${customIdx + 1}. `, cls: "claudian-ask-item-num" });
      if (isMulti) {
        this.renderMultiSelectCheckbox(customRow, hasCustomText);
      }
      const inputEl = customRow.createEl("input", {
        cls: "claudian-ask-custom-text",
        value: customText
      });
      inputEl.setAttribute("type", q10.isSecret ? "password" : "text");
      inputEl.setAttribute("placeholder", q10.isSecret ? "Enter secret." : "Type something.");
      inputEl.addEventListener("input", () => {
        this.customInputs.set(idx, inputEl.value);
        if (!isMulti && inputEl.value.trim()) {
          selected.clear();
          this.updateOptionVisuals(idx);
        }
        this.updateTabIndicators();
      });
      inputEl.addEventListener("focus", () => {
        this.isInputFocused = true;
      });
      inputEl.addEventListener("blur", () => {
        this.isInputFocused = false;
      });
      this.currentItems.push(customRow);
    }
    this.contentArea.createDiv({
      text: this.config.immediateSelect ? HINTS_TEXT_IMMEDIATE : HINTS_TEXT,
      cls: "claudian-ask-hints"
    });
  }
  renderSubmitTab() {
    this.contentArea.createDiv({
      text: "Review your answers",
      cls: "claudian-ask-review-title"
    });
    const reviewEl = this.contentArea.createDiv({ cls: "claudian-ask-review" });
    for (let idx = 0; idx < this.questions.length; idx++) {
      const q10 = this.questions[idx];
      const answerText = this.getAnswerText(idx);
      const pairEl = reviewEl.createDiv({ cls: "claudian-ask-review-pair" });
      pairEl.createDiv({ text: `${idx + 1}.`, cls: "claudian-ask-review-num" });
      const bodyEl = pairEl.createDiv({ cls: "claudian-ask-review-body" });
      bodyEl.createDiv({ text: q10.question, cls: "claudian-ask-review-q-text" });
      bodyEl.createDiv({
        text: answerText || "Not answered",
        cls: answerText ? "claudian-ask-review-a-text" : "claudian-ask-review-empty"
      });
      pairEl.addEventListener("click", () => this.switchTab(idx));
    }
    this.contentArea.createDiv({
      text: "Ready to submit your answers?",
      cls: "claudian-ask-review-prompt"
    });
    const actionsEl = this.contentArea.createDiv({ cls: "claudian-ask-list" });
    const allAnswered = this.questions.every((_10, i2) => this.isQuestionAnswered(i2));
    const submitRow = actionsEl.createDiv({ cls: "claudian-ask-item" });
    if (this.focusedItemIndex === 0) submitRow.addClass("is-focused");
    if (!allAnswered) submitRow.addClass("is-disabled");
    submitRow.createSpan({ text: this.focusedItemIndex === 0 ? "\u203A" : "\xA0", cls: "claudian-ask-cursor" });
    submitRow.createSpan({ text: "1. ", cls: "claudian-ask-item-num" });
    submitRow.createSpan({ text: "Submit answers", cls: "claudian-ask-item-label" });
    submitRow.addEventListener("click", () => {
      this.focusedItemIndex = 0;
      this.updateFocusIndicator();
      this.handleSubmit();
    });
    this.currentItems.push(submitRow);
    const cancelRow = actionsEl.createDiv({ cls: "claudian-ask-item" });
    if (this.focusedItemIndex === 1) cancelRow.addClass("is-focused");
    cancelRow.createSpan({ text: this.focusedItemIndex === 1 ? "\u203A" : "\xA0", cls: "claudian-ask-cursor" });
    cancelRow.createSpan({ text: "2. ", cls: "claudian-ask-item-num" });
    cancelRow.createSpan({ text: "Cancel", cls: "claudian-ask-item-label" });
    cancelRow.addEventListener("click", () => {
      this.focusedItemIndex = 1;
      this.handleResolve(null);
    });
    this.currentItems.push(cancelRow);
    this.contentArea.createDiv({
      text: HINTS_TEXT,
      cls: "claudian-ask-hints"
    });
  }
  getAnswerText(idx) {
    const selected = this.getSelectedLabels(idx);
    const custom2 = this.customInputs.get(idx);
    const parts = [];
    if (selected.length > 0) parts.push(selected.join(", "));
    if (custom2.trim()) parts.push(custom2.trim());
    return parts.join(", ");
  }
  selectOption(qIdx, option) {
    var _a3;
    const q10 = this.questions[qIdx];
    const selected = this.answers.get(qIdx);
    const isMulti = q10.multiSelect;
    const optionValue = this.getOptionValue(option);
    if (isMulti) {
      if (selected.has(optionValue)) {
        selected.delete(optionValue);
      } else {
        selected.add(optionValue);
      }
    } else {
      selected.clear();
      selected.add(optionValue);
      this.customInputs.set(qIdx, "");
    }
    this.updateOptionVisuals(qIdx);
    if (this.config.immediateSelect) {
      const key = (_a3 = q10.id) != null ? _a3 : q10.question;
      const result = {};
      result[key] = optionValue;
      this.handleResolve(result);
      return;
    }
    this.updateTabIndicators();
    if (!isMulti) {
      this.switchTab(this.activeTabIndex + 1);
    }
  }
  renderMultiSelectCheckbox(parent, checked) {
    parent.createSpan({
      text: checked ? "[\u2713] " : "[ ] ",
      cls: `claudian-ask-check${checked ? " is-checked" : ""}`
    });
  }
  updateOptionVisuals(qIdx) {
    const q10 = this.questions[qIdx];
    const selected = this.answers.get(qIdx);
    const isMulti = q10.multiSelect;
    for (let i2 = 0; i2 < q10.options.length; i2++) {
      const item = this.currentItems[i2];
      const isSelected = selected.has(this.getOptionValue(q10.options[i2]));
      item.toggleClass("is-selected", isSelected);
      if (isMulti) {
        const checkSpan = item.querySelector(".claudian-ask-check");
        if (checkSpan) {
          checkSpan.textContent = isSelected ? "[\u2713] " : "[ ] ";
          checkSpan.toggleClass("is-checked", isSelected);
        }
      } else {
        const labelRow = item.querySelector(".claudian-ask-label-row");
        const existingMark = item.querySelector(".claudian-ask-check-mark");
        if (isSelected && !existingMark && labelRow) {
          labelRow.createSpan({ text: " \u2713", cls: "claudian-ask-check-mark" });
        } else if (!isSelected && existingMark) {
          existingMark.remove();
        }
      }
    }
  }
  updateFocusIndicator() {
    for (let i2 = 0; i2 < this.currentItems.length; i2++) {
      const item = this.currentItems[i2];
      const cursor = item.querySelector(".claudian-ask-cursor");
      if (i2 === this.focusedItemIndex) {
        item.addClass("is-focused");
        if (cursor) cursor.textContent = "\u203A";
        item.scrollIntoView({ block: "nearest" });
        if (item.hasClass("claudian-ask-custom-item")) {
          const input = item.querySelector(".claudian-ask-custom-text");
          if (input) {
            input.focus();
            this.isInputFocused = true;
          }
        }
      } else {
        item.removeClass("is-focused");
        if (cursor) cursor.textContent = "\xA0";
        if (item.hasClass("claudian-ask-custom-item")) {
          const input = item.querySelector(".claudian-ask-custom-text");
          if (input && document.activeElement === input) {
            input.blur();
            this.isInputFocused = false;
          }
        }
      }
    }
  }
  updateTabIndicators() {
    for (let idx = 0; idx < this.questions.length; idx++) {
      const tab = this.tabElements[idx];
      const tick = tab.querySelector(".claudian-ask-tab-tick");
      const answered = this.isQuestionAnswered(idx);
      tab.toggleClass("is-answered", answered);
      if (tick) tick.textContent = answered ? " \u2713" : "";
    }
    const submitTab = this.tabElements[this.questions.length];
    if (submitTab) {
      const submitCheck = submitTab.querySelector(".claudian-ask-tab-submit-check");
      const allAnswered = this.questions.every((_10, i2) => this.isQuestionAnswered(i2));
      if (submitCheck) submitCheck.textContent = allAnswered ? "\u2713 " : "";
    }
  }
  handleNavigationKey(e2, maxFocusIndex) {
    switch (e2.key) {
      case "ArrowDown":
        e2.preventDefault();
        e2.stopPropagation();
        this.focusedItemIndex = Math.min(this.focusedItemIndex + 1, maxFocusIndex);
        this.updateFocusIndicator();
        return true;
      case "ArrowUp":
        e2.preventDefault();
        e2.stopPropagation();
        this.focusedItemIndex = Math.max(this.focusedItemIndex - 1, 0);
        this.updateFocusIndicator();
        return true;
      case "ArrowLeft":
        if (this.config.immediateSelect) return false;
        e2.preventDefault();
        e2.stopPropagation();
        this.switchTab(this.activeTabIndex - 1);
        return true;
      case "Tab":
        if (this.config.immediateSelect) return false;
        e2.preventDefault();
        e2.stopPropagation();
        if (e2.shiftKey) {
          this.switchTab(this.activeTabIndex - 1);
        } else {
          this.switchTab(this.activeTabIndex + 1);
        }
        return true;
      case "Escape":
        e2.preventDefault();
        e2.stopPropagation();
        this.handleResolve(null);
        return true;
      default:
        return false;
    }
  }
  handleKeyDown(e2) {
    var _a3, _b2;
    if (this.isInputFocused) {
      if (e2.key === "Escape") {
        e2.preventDefault();
        e2.stopPropagation();
        this.isInputFocused = false;
        (_a3 = document.activeElement) == null ? void 0 : _a3.blur();
        this.rootEl.focus();
        return;
      }
      if (e2.key === "Tab" || e2.key === "Enter") {
        e2.preventDefault();
        e2.stopPropagation();
        this.isInputFocused = false;
        (_b2 = document.activeElement) == null ? void 0 : _b2.blur();
        if (e2.key === "Tab" && e2.shiftKey) {
          this.switchTab(this.activeTabIndex - 1);
        } else {
          this.switchTab(this.activeTabIndex + 1);
        }
        return;
      }
      return;
    }
    if (this.config.immediateSelect) {
      const q11 = this.questions[this.activeTabIndex];
      const maxIdx = q11.options.length - 1;
      if (this.handleNavigationKey(e2, maxIdx)) return;
      if (e2.key === "Enter") {
        e2.preventDefault();
        e2.stopPropagation();
        if (this.focusedItemIndex <= maxIdx) {
          this.selectOption(this.activeTabIndex, q11.options[this.focusedItemIndex]);
        }
      }
      return;
    }
    const isSubmitTab = this.activeTabIndex === this.questions.length;
    const q10 = this.questions[this.activeTabIndex];
    const maxFocusIndex = isSubmitTab ? 1 : this.canShowCustomInputForQuestion(q10) ? q10.options.length : q10.options.length - 1;
    if (this.handleNavigationKey(e2, maxFocusIndex)) return;
    if (isSubmitTab) {
      if (e2.key === "Enter") {
        e2.preventDefault();
        e2.stopPropagation();
        if (this.focusedItemIndex === 0) this.handleSubmit();
        else this.handleResolve(null);
      }
      return;
    }
    switch (e2.key) {
      case "ArrowRight":
        e2.preventDefault();
        e2.stopPropagation();
        this.switchTab(this.activeTabIndex + 1);
        break;
      case "Enter":
        e2.preventDefault();
        e2.stopPropagation();
        if (this.focusedItemIndex < q10.options.length) {
          this.selectOption(this.activeTabIndex, q10.options[this.focusedItemIndex]);
        } else if (this.canShowCustomInputForQuestion(q10)) {
          this.isInputFocused = true;
          const input = this.contentArea.querySelector(
            ".claudian-ask-custom-text"
          );
          input == null ? void 0 : input.focus();
        }
        break;
    }
  }
  handleSubmit() {
    var _a3;
    const allAnswered = this.questions.every((_10, i2) => this.isQuestionAnswered(i2));
    if (!allAnswered) return;
    const result = {};
    for (let i2 = 0; i2 < this.questions.length; i2++) {
      const question = this.questions[i2];
      const key = (_a3 = question.id) != null ? _a3 : question.question;
      const selectedValues = [...this.answers.get(i2)];
      const customInput = this.customInputs.get(i2).trim();
      if (question.multiSelect) {
        const answers = [...selectedValues];
        if (customInput) {
          answers.push(customInput);
        }
        result[key] = answers;
        continue;
      }
      result[key] = customInput || selectedValues[0] || "";
    }
    this.handleResolve(result);
  }
  canShowCustomInputForQuestion(question) {
    return this.config.showCustomInput && question.isOther === true;
  }
  getOptionValue(option) {
    var _a3;
    return (_a3 = option.value) != null ? _a3 : option.label;
  }
  getSelectedLabels(idx) {
    const selected = this.answers.get(idx);
    const question = this.questions[idx];
    return question.options.filter((option) => selected.has(this.getOptionValue(option))).map((option) => option.label);
  }
  handleResolve(result) {
    var _a3, _b2;
    if (!this.resolved) {
      this.resolved = true;
      (_a3 = this.rootEl) == null ? void 0 : _a3.removeEventListener("keydown", this.boundKeyDown);
      if (this.signal && this.abortHandler) {
        this.signal.removeEventListener("abort", this.abortHandler);
        this.abortHandler = null;
      }
      (_b2 = this.rootEl) == null ? void 0 : _b2.remove();
      this.resolveCallback(result);
    }
  }
};

// src/features/chat/rendering/InlineExitPlanMode.ts
var nodePath = __toESM(require("path"));
var HINTS_TEXT2 = "Arrow keys to navigate \xB7 Enter to select \xB7 Esc to cancel";
var InlineExitPlanMode = class {
  constructor(containerEl, input, resolve8, signal, renderContent, planPathPrefix) {
    this.resolved = false;
    this.planContent = null;
    this.planReadError = null;
    this.focusedIndex = 0;
    this.items = [];
    this.isInputFocused = false;
    this.abortHandler = null;
    this.containerEl = containerEl;
    this.input = input;
    this.resolveCallback = resolve8;
    this.signal = signal;
    this.renderContent = renderContent;
    this.planPathPrefix = planPathPrefix;
    this.boundKeyDown = this.handleKeyDown.bind(this);
  }
  render() {
    this.rootEl = this.containerEl.createDiv({ cls: "claudian-plan-approval-inline" });
    const titleEl = this.rootEl.createDiv({ cls: "claudian-plan-inline-title" });
    titleEl.setText("Plan complete");
    this.planContent = this.readPlanContent();
    if (this.planContent) {
      const contentEl = this.rootEl.createDiv({ cls: "claudian-plan-content-preview" });
      if (this.renderContent) {
        void this.renderContent(contentEl, this.planContent);
      } else {
        contentEl.createDiv({ cls: "claudian-plan-content-text", text: this.planContent });
      }
    } else if (this.planReadError) {
      this.rootEl.createDiv({
        cls: "claudian-plan-content-preview claudian-plan-read-error",
        text: `Could not read plan file: ${this.planReadError}. "Approve (new session)" will not include plan details.`
      });
    }
    const allowedPrompts = this.input.allowedPrompts;
    if (allowedPrompts && Array.isArray(allowedPrompts) && allowedPrompts.length > 0) {
      const permEl = this.rootEl.createDiv({ cls: "claudian-plan-permissions" });
      permEl.createDiv({ text: "Requested permissions:", cls: "claudian-plan-permissions-label" });
      const listEl = permEl.createEl("ul", { cls: "claudian-plan-permissions-list" });
      for (const perm of allowedPrompts) {
        listEl.createEl("li", { text: perm.prompt });
      }
    }
    const actionsEl = this.rootEl.createDiv({ cls: "claudian-ask-list" });
    const newSessionRow = actionsEl.createDiv({ cls: "claudian-ask-item" });
    newSessionRow.addClass("is-focused");
    newSessionRow.createSpan({ text: "\u203A", cls: "claudian-ask-cursor" });
    newSessionRow.createSpan({ text: "1. ", cls: "claudian-ask-item-num" });
    newSessionRow.createSpan({ text: "Approve (new session)", cls: "claudian-ask-item-label" });
    newSessionRow.addEventListener("click", () => {
      this.focusedIndex = 0;
      this.updateFocus();
      this.handleResolve({
        type: "approve-new-session",
        planContent: this.extractPlanContent()
      });
    });
    this.items.push(newSessionRow);
    const approveRow = actionsEl.createDiv({ cls: "claudian-ask-item" });
    approveRow.createSpan({ text: "\xA0", cls: "claudian-ask-cursor" });
    approveRow.createSpan({ text: "2. ", cls: "claudian-ask-item-num" });
    approveRow.createSpan({ text: "Approve (current session)", cls: "claudian-ask-item-label" });
    approveRow.addEventListener("click", () => {
      this.focusedIndex = 1;
      this.updateFocus();
      this.handleResolve({ type: "approve" });
    });
    this.items.push(approveRow);
    const feedbackRow = actionsEl.createDiv({ cls: "claudian-ask-item claudian-ask-custom-item" });
    feedbackRow.createSpan({ text: "\xA0", cls: "claudian-ask-cursor" });
    feedbackRow.createSpan({ text: "3. ", cls: "claudian-ask-item-num" });
    this.feedbackInput = feedbackRow.createEl("input", {
      type: "text",
      cls: "claudian-ask-custom-text",
      placeholder: "Enter feedback to continue planning..."
    });
    this.feedbackInput.addEventListener("focus", () => {
      this.isInputFocused = true;
    });
    this.feedbackInput.addEventListener("blur", () => {
      this.isInputFocused = false;
    });
    feedbackRow.addEventListener("click", () => {
      this.focusedIndex = 2;
      this.updateFocus();
    });
    this.items.push(feedbackRow);
    this.rootEl.createDiv({ text: HINTS_TEXT2, cls: "claudian-ask-hints" });
    this.rootEl.setAttribute("tabindex", "0");
    this.rootEl.addEventListener("keydown", this.boundKeyDown);
    requestAnimationFrame(() => {
      this.rootEl.focus();
      this.rootEl.scrollIntoView({ block: "nearest", behavior: "smooth" });
    });
    if (this.signal) {
      this.abortHandler = () => this.handleResolve(null);
      this.signal.addEventListener("abort", this.abortHandler, { once: true });
    }
  }
  destroy() {
    this.handleResolve(null);
  }
  readPlanContent() {
    const planFilePath = this.input.planFilePath;
    if (!planFilePath) return null;
    const resolved = nodePath.resolve(planFilePath).replace(/\\/g, "/");
    if (!this.planPathPrefix || !resolved.includes(this.planPathPrefix)) {
      this.planReadError = "path outside allowed plan directory";
      return null;
    }
    try {
      const fs26 = require("fs");
      const content = fs26.readFileSync(planFilePath, "utf-8");
      return content.trim() || null;
    } catch (err) {
      this.planReadError = err instanceof Error ? err.message : "unknown error";
      return null;
    }
  }
  extractPlanContent() {
    if (this.planContent) {
      return `Implement this plan:

${this.planContent}`;
    }
    return "Implement the approved plan.";
  }
  handleKeyDown(e2) {
    if (this.isInputFocused) {
      if (e2.key === "Escape") {
        e2.preventDefault();
        e2.stopPropagation();
        this.isInputFocused = false;
        this.feedbackInput.blur();
        this.rootEl.focus();
        return;
      }
      if (e2.key === "Enter" && this.feedbackInput.value.trim()) {
        e2.preventDefault();
        e2.stopPropagation();
        this.handleResolve({ type: "feedback", text: this.feedbackInput.value.trim() });
        return;
      }
      return;
    }
    switch (e2.key) {
      case "ArrowDown":
        e2.preventDefault();
        e2.stopPropagation();
        this.focusedIndex = Math.min(this.focusedIndex + 1, this.items.length - 1);
        this.updateFocus();
        break;
      case "ArrowUp":
        e2.preventDefault();
        e2.stopPropagation();
        this.focusedIndex = Math.max(this.focusedIndex - 1, 0);
        this.updateFocus();
        break;
      case "Enter":
        e2.preventDefault();
        e2.stopPropagation();
        if (this.focusedIndex === 0) {
          this.handleResolve({
            type: "approve-new-session",
            planContent: this.extractPlanContent()
          });
        } else if (this.focusedIndex === 1) {
          this.handleResolve({ type: "approve" });
        } else if (this.focusedIndex === 2) {
          this.feedbackInput.focus();
        }
        break;
      case "Escape":
        e2.preventDefault();
        e2.stopPropagation();
        this.handleResolve(null);
        break;
    }
  }
  updateFocus() {
    for (let i2 = 0; i2 < this.items.length; i2++) {
      const item = this.items[i2];
      const cursor = item.querySelector(".claudian-ask-cursor");
      if (i2 === this.focusedIndex) {
        item.addClass("is-focused");
        if (cursor) cursor.textContent = "\u203A";
        item.scrollIntoView({ block: "nearest" });
        if (item.hasClass("claudian-ask-custom-item")) {
          const input = item.querySelector(".claudian-ask-custom-text");
          if (input) {
            input.focus();
            this.isInputFocused = true;
          }
        }
      } else {
        item.removeClass("is-focused");
        if (cursor) cursor.textContent = "\xA0";
        if (item.hasClass("claudian-ask-custom-item")) {
          const input = item.querySelector(".claudian-ask-custom-text");
          if (input && document.activeElement === input) {
            input.blur();
            this.isInputFocused = false;
          }
        }
      }
    }
  }
  handleResolve(decision) {
    var _a3, _b2;
    if (!this.resolved) {
      this.resolved = true;
      (_a3 = this.rootEl) == null ? void 0 : _a3.removeEventListener("keydown", this.boundKeyDown);
      if (this.signal && this.abortHandler) {
        this.signal.removeEventListener("abort", this.abortHandler);
        this.abortHandler = null;
      }
      (_b2 = this.rootEl) == null ? void 0 : _b2.remove();
      this.resolveCallback(decision);
    }
  }
};

// src/features/chat/rendering/InlinePlanApproval.ts
var HINTS_TEXT3 = "Arrow keys to navigate \xB7 Enter to select \xB7 Esc to cancel";
var InlinePlanApproval = class {
  constructor(containerEl, resolve8) {
    this.resolved = false;
    this.focusedIndex = 0;
    this.items = [];
    this.isInputFocused = false;
    this.containerEl = containerEl;
    this.resolveCallback = resolve8;
    this.boundKeyDown = this.handleKeyDown.bind(this);
  }
  render() {
    this.rootEl = this.containerEl.createDiv({ cls: "claudian-plan-approval-inline" });
    this.rootEl.createDiv({ cls: "claudian-plan-inline-title", text: "Plan complete" });
    const actionsEl = this.rootEl.createDiv({ cls: "claudian-ask-list" });
    const implementRow = actionsEl.createDiv({ cls: "claudian-ask-item" });
    implementRow.addClass("is-focused");
    implementRow.createSpan({ text: "\u203A", cls: "claudian-ask-cursor" });
    implementRow.createSpan({ text: "1. ", cls: "claudian-ask-item-num" });
    implementRow.createSpan({ text: "Implement", cls: "claudian-ask-item-label" });
    implementRow.addEventListener("click", () => {
      this.focusedIndex = 0;
      this.updateFocus();
      this.handleResolve({ type: "implement" });
    });
    this.items.push(implementRow);
    const reviseRow = actionsEl.createDiv({ cls: "claudian-ask-item claudian-ask-custom-item" });
    reviseRow.createSpan({ text: "\xA0", cls: "claudian-ask-cursor" });
    reviseRow.createSpan({ text: "2. ", cls: "claudian-ask-item-num" });
    this.feedbackInput = reviseRow.createEl("input", {
      type: "text",
      cls: "claudian-ask-custom-text",
      placeholder: "Enter feedback to revise plan..."
    });
    this.feedbackInput.addEventListener("focus", () => {
      this.isInputFocused = true;
    });
    this.feedbackInput.addEventListener("blur", () => {
      this.isInputFocused = false;
    });
    reviseRow.addEventListener("click", () => {
      this.focusedIndex = 1;
      this.updateFocus();
    });
    this.items.push(reviseRow);
    const cancelRow = actionsEl.createDiv({ cls: "claudian-ask-item" });
    cancelRow.createSpan({ text: "\xA0", cls: "claudian-ask-cursor" });
    cancelRow.createSpan({ text: "3. ", cls: "claudian-ask-item-num" });
    cancelRow.createSpan({ text: "Cancel", cls: "claudian-ask-item-label" });
    cancelRow.addEventListener("click", () => {
      this.focusedIndex = 2;
      this.updateFocus();
      this.handleResolve({ type: "cancel" });
    });
    this.items.push(cancelRow);
    this.rootEl.createDiv({ text: HINTS_TEXT3, cls: "claudian-ask-hints" });
    this.rootEl.setAttribute("tabindex", "0");
    this.rootEl.addEventListener("keydown", this.boundKeyDown);
    requestAnimationFrame(() => {
      this.rootEl.focus();
      this.rootEl.scrollIntoView({ block: "nearest", behavior: "smooth" });
    });
  }
  destroy() {
    this.handleResolve(null);
  }
  handleKeyDown(e2) {
    if (this.isInputFocused) {
      if (e2.key === "Escape") {
        e2.preventDefault();
        e2.stopPropagation();
        this.isInputFocused = false;
        this.feedbackInput.blur();
        this.rootEl.focus();
        return;
      }
      if (e2.key === "Enter" && this.feedbackInput.value.trim()) {
        e2.preventDefault();
        e2.stopPropagation();
        this.handleResolve({ type: "revise", text: this.feedbackInput.value.trim() });
        return;
      }
      return;
    }
    switch (e2.key) {
      case "ArrowDown":
        e2.preventDefault();
        e2.stopPropagation();
        this.focusedIndex = Math.min(this.focusedIndex + 1, this.items.length - 1);
        this.updateFocus();
        break;
      case "ArrowUp":
        e2.preventDefault();
        e2.stopPropagation();
        this.focusedIndex = Math.max(this.focusedIndex - 1, 0);
        this.updateFocus();
        break;
      case "Enter":
        e2.preventDefault();
        e2.stopPropagation();
        if (this.focusedIndex === 0) {
          this.handleResolve({ type: "implement" });
        } else if (this.focusedIndex === 1) {
          this.feedbackInput.focus();
        } else if (this.focusedIndex === 2) {
          this.handleResolve({ type: "cancel" });
        }
        break;
      case "Escape":
        e2.preventDefault();
        e2.stopPropagation();
        this.handleResolve(null);
        break;
    }
  }
  updateFocus() {
    for (let i2 = 0; i2 < this.items.length; i2++) {
      const item = this.items[i2];
      const cursor = item.querySelector(".claudian-ask-cursor");
      if (i2 === this.focusedIndex) {
        item.addClass("is-focused");
        if (cursor) cursor.textContent = "\u203A";
        item.scrollIntoView({ block: "nearest" });
        if (item.hasClass("claudian-ask-custom-item")) {
          const input = item.querySelector(".claudian-ask-custom-text");
          if (input) {
            input.focus();
            this.isInputFocused = true;
          }
        }
      } else {
        item.removeClass("is-focused");
        if (cursor) cursor.textContent = "\xA0";
        if (item.hasClass("claudian-ask-custom-item") && this.isInputFocused) {
          const input = item.querySelector(".claudian-ask-custom-text");
          if (input) {
            input.blur();
            this.isInputFocused = false;
          }
        }
      }
    }
  }
  handleResolve(decision) {
    var _a3, _b2;
    if (!this.resolved) {
      this.resolved = true;
      (_a3 = this.rootEl) == null ? void 0 : _a3.removeEventListener("keydown", this.boundKeyDown);
      (_b2 = this.rootEl) == null ? void 0 : _b2.remove();
      this.resolveCallback(decision);
    }
  }
};

// src/features/chat/rendering/ToolCallRenderer.ts
var import_obsidian25 = require("obsidian");

// src/core/tools/toolIcons.ts
var TOOL_ICONS = {
  [TOOL_READ]: "file-text",
  [TOOL_WRITE]: "file-plus",
  [TOOL_EDIT]: "file-pen",
  [TOOL_NOTEBOOK_EDIT]: "file-pen",
  [TOOL_BASH]: "terminal",
  [TOOL_BASH_OUTPUT]: "terminal",
  [TOOL_KILL_SHELL]: "terminal",
  [TOOL_GLOB]: "folder-search",
  [TOOL_GREP]: "search",
  [TOOL_LS]: "list",
  [TOOL_TODO_WRITE]: "list-checks",
  [TOOL_TASK]: "bot",
  [TOOL_SUBAGENT_LEGACY]: "bot",
  [TOOL_LIST_MCP_RESOURCES]: "list",
  [TOOL_READ_MCP_RESOURCE]: "file-text",
  [TOOL_MCP]: "wrench",
  [TOOL_WEB_SEARCH]: "globe",
  [TOOL_WEB_FETCH]: "download",
  [TOOL_AGENT_OUTPUT]: "bot",
  [TOOL_ASK_USER_QUESTION]: "help-circle",
  [TOOL_SKILL]: "zap",
  [TOOL_TOOL_SEARCH]: "search-check",
  [TOOL_ENTER_PLAN_MODE]: "map",
  [TOOL_EXIT_PLAN_MODE]: "check-circle",
  // Runtime-managed tools
  [TOOL_APPLY_PATCH]: "file-pen",
  [TOOL_WRITE_STDIN]: "terminal",
  [TOOL_SPAWN_AGENT]: "bot",
  [TOOL_SEND_INPUT]: "bot",
  [TOOL_WAIT]: "clock",
  [TOOL_WAIT_AGENT]: "clock",
  [TOOL_RESUME_AGENT]: "bot",
  [TOOL_CLOSE_AGENT]: "bot"
};
var MCP_ICON_MARKER = "__mcp_icon__";
function getToolIcon(toolName) {
  if (toolName.startsWith("mcp__")) {
    return MCP_ICON_MARKER;
  }
  return TOOL_ICONS[toolName] || "wrench";
}

// src/features/chat/rendering/DiffRenderer.ts
function splitIntoHunks(diffLines, contextLines = 3) {
  if (diffLines.length === 0) return [];
  const changedIndices = [];
  for (let i2 = 0; i2 < diffLines.length; i2++) {
    if (diffLines[i2].type !== "equal") {
      changedIndices.push(i2);
    }
  }
  if (changedIndices.length === 0) return [];
  const ranges = [];
  for (const idx of changedIndices) {
    const start = Math.max(0, idx - contextLines);
    const end = Math.min(diffLines.length - 1, idx + contextLines);
    if (ranges.length > 0 && start <= ranges[ranges.length - 1].end + 1) {
      ranges[ranges.length - 1].end = end;
    } else {
      ranges.push({ start, end });
    }
  }
  const hunks = [];
  for (const range of ranges) {
    const lines = diffLines.slice(range.start, range.end + 1);
    let oldStart = 1;
    let newStart = 1;
    for (let i2 = 0; i2 < range.start; i2++) {
      const line = diffLines[i2];
      if (line.type === "equal" || line.type === "delete") oldStart++;
      if (line.type === "equal" || line.type === "insert") newStart++;
    }
    hunks.push({ lines, oldStart, newStart });
  }
  return hunks;
}
var NEW_FILE_DISPLAY_CAP = 20;
function renderDiffContent(containerEl, diffLines, contextLines = 3) {
  containerEl.empty();
  const allInserts = diffLines.length > 0 && diffLines.every((l2) => l2.type === "insert");
  if (allInserts && diffLines.length > NEW_FILE_DISPLAY_CAP) {
    const hunkEl = containerEl.createDiv({ cls: "claudian-diff-hunk" });
    for (const line of diffLines.slice(0, NEW_FILE_DISPLAY_CAP)) {
      const lineEl = hunkEl.createDiv({ cls: "claudian-diff-line claudian-diff-insert" });
      const prefixEl = lineEl.createSpan({ cls: "claudian-diff-prefix" });
      prefixEl.setText("+");
      const contentEl = lineEl.createSpan({ cls: "claudian-diff-text" });
      contentEl.setText(line.text || " ");
    }
    const remaining = diffLines.length - NEW_FILE_DISPLAY_CAP;
    const separator = containerEl.createDiv({ cls: "claudian-diff-separator" });
    separator.setText(`... ${remaining} more lines`);
    return;
  }
  const hunks = splitIntoHunks(diffLines, contextLines);
  if (hunks.length === 0) {
    const noChanges = containerEl.createDiv({ cls: "claudian-diff-no-changes" });
    noChanges.setText("No changes");
    return;
  }
  hunks.forEach((hunk, hunkIndex) => {
    if (hunkIndex > 0) {
      const separator = containerEl.createDiv({ cls: "claudian-diff-separator" });
      separator.setText("...");
    }
    const hunkEl = containerEl.createDiv({ cls: "claudian-diff-hunk" });
    for (const line of hunk.lines) {
      const lineEl = hunkEl.createDiv({ cls: `claudian-diff-line claudian-diff-${line.type}` });
      const prefix = line.type === "insert" ? "+" : line.type === "delete" ? "-" : " ";
      const prefixEl = lineEl.createSpan({ cls: "claudian-diff-prefix" });
      prefixEl.setText(prefix);
      const contentEl = lineEl.createSpan({ cls: "claudian-diff-text" });
      contentEl.setText(line.text || " ");
    }
  });
}

// src/features/chat/rendering/todoUtils.ts
var import_obsidian24 = require("obsidian");
function getTodoStatusIcon(status) {
  return status === "completed" ? "check" : "dot";
}
function getTodoDisplayText(todo) {
  return todo.status === "in_progress" ? todo.activeForm : todo.content;
}
function renderTodoItems(container, todos) {
  container.empty();
  for (const todo of todos) {
    const item = container.createDiv({ cls: `claudian-todo-item claudian-todo-${todo.status}` });
    const icon = item.createSpan({ cls: "claudian-todo-status-icon" });
    icon.setAttribute("aria-hidden", "true");
    (0, import_obsidian24.setIcon)(icon, getTodoStatusIcon(todo.status));
    const text = item.createSpan({ cls: "claudian-todo-text" });
    text.setText(getTodoDisplayText(todo));
  }
}

// src/features/chat/rendering/ToolCallRenderer.ts
function setToolIcon(el, name) {
  const icon = getToolIcon(name);
  if (icon === MCP_ICON_MARKER) {
    el.innerHTML = MCP_ICON_SVG;
  } else {
    (0, import_obsidian25.setIcon)(el, icon);
  }
}
function getToolName(name, input) {
  switch (name) {
    case TOOL_TODO_WRITE: {
      const todos = input.todos;
      if (todos && Array.isArray(todos) && todos.length > 0) {
        const completed = todos.filter((t2) => t2.status === "completed").length;
        return `Tasks ${completed}/${todos.length}`;
      }
      return "Tasks";
    }
    case TOOL_ENTER_PLAN_MODE:
      return "Entering plan mode";
    case TOOL_EXIT_PLAN_MODE:
      return "Plan complete";
    default:
      return name;
  }
}
function getToolSummary(name, input) {
  switch (name) {
    case TOOL_READ:
    case TOOL_WRITE:
    case TOOL_EDIT: {
      const filePath = input.file_path || "";
      return fileNameOnly(filePath);
    }
    case TOOL_BASH: {
      const cmd = input.command || "";
      return truncateText(cmd, 60);
    }
    case TOOL_GLOB:
    case TOOL_GREP:
      return input.pattern || "";
    case TOOL_WEB_SEARCH:
      return getWebSearchSummary(input, 60);
    case TOOL_WEB_FETCH:
      return truncateText(input.url || "", 60);
    case TOOL_LS:
      return fileNameOnly(input.path || ".");
    case TOOL_SKILL:
      return input.skill || "";
    case TOOL_TOOL_SEARCH:
      return truncateText(parseToolSearchQuery(input.query), 60);
    case TOOL_TODO_WRITE:
      return "";
    case TOOL_APPLY_PATCH:
      return getApplyPatchSummary(input);
    case TOOL_WRITE_STDIN:
      return getWriteStdinSummary(input);
    default:
      if (isAgentLifecycleTool(name)) {
        return getAgentLifecycleSummary(name, input);
      }
      return "";
  }
}
function getToolLabel(name, input) {
  switch (name) {
    case TOOL_READ:
      return `Read: ${shortenPath(input.file_path) || "file"}`;
    case TOOL_WRITE:
      return `Write: ${shortenPath(input.file_path) || "file"}`;
    case TOOL_EDIT:
      return `Edit: ${shortenPath(input.file_path) || "file"}`;
    case TOOL_BASH: {
      const cmd = input.command || "command";
      return `Bash: ${cmd.length > 40 ? cmd.substring(0, 40) + "..." : cmd}`;
    }
    case TOOL_GLOB:
      return `Glob: ${input.pattern || "files"}`;
    case TOOL_GREP:
      return `Grep: ${input.pattern || "pattern"}`;
    case TOOL_WEB_SEARCH: {
      return getWebSearchLabel(input, 40);
    }
    case TOOL_WEB_FETCH: {
      const url2 = input.url || "url";
      return `WebFetch: ${url2.length > 40 ? url2.substring(0, 40) + "..." : url2}`;
    }
    case TOOL_LS:
      return `LS: ${shortenPath(input.path) || "."}`;
    case TOOL_TODO_WRITE: {
      const todos = input.todos;
      if (todos && Array.isArray(todos)) {
        const completed = todos.filter((t2) => t2.status === "completed").length;
        return `Tasks (${completed}/${todos.length})`;
      }
      return "Tasks";
    }
    case TOOL_SKILL: {
      const skillName = input.skill || "skill";
      return `Skill: ${skillName}`;
    }
    case TOOL_TOOL_SEARCH: {
      const tools = parseToolSearchQuery(input.query);
      return `ToolSearch: ${tools || "tools"}`;
    }
    case TOOL_ENTER_PLAN_MODE:
      return "Entering plan mode";
    case TOOL_EXIT_PLAN_MODE:
      return "Plan complete";
    case TOOL_APPLY_PATCH: {
      const summary = getApplyPatchSummary(input);
      return summary ? `apply_patch: ${summary}` : "apply_patch";
    }
    case TOOL_WRITE_STDIN: {
      const summary = getWriteStdinSummary(input);
      return summary ? `write_stdin: ${summary}` : "write_stdin";
    }
    default:
      if (isAgentLifecycleTool(name)) {
        const summary = getAgentLifecycleSummary(name, input);
        return summary ? `${name}: ${summary}` : name;
      }
      return name;
  }
}
function fileNameOnly(filePath) {
  var _a3;
  if (!filePath) return "";
  const normalized = filePath.replace(/\\/g, "/");
  return (_a3 = normalized.split("/").pop()) != null ? _a3 : normalized;
}
function getApplyPatchSummary(input) {
  const patchText = typeof input.patch === "string" ? input.patch : "";
  const patchFiles = [...patchText.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)].map((m2) => {
    var _a3, _b2;
    return (_b2 = (_a3 = m2[1]) == null ? void 0 : _a3.trim()) != null ? _b2 : "";
  });
  const changes = input.changes;
  const changeFiles = Array.isArray(changes) ? changes.map((c) => c.path).filter((p) => !!p) : [];
  const files = [.../* @__PURE__ */ new Set([...patchFiles, ...changeFiles])];
  if (files.length === 0) return patchText ? "patch" : "";
  if (files.length === 1) return fileNameOnly(files[0]);
  return `${files.length} files`;
}
function getWriteStdinSummary(input) {
  var _a3;
  const sessionId = (_a3 = input.session_id) != null ? _a3 : input.sessionId;
  const chars = typeof input.chars === "string" ? input.chars.replace(/\n/g, "\\n") : "";
  if (chars) {
    const preview = chars.length > 24 ? `${chars.slice(0, 24)}...` : chars;
    return sessionId ? `#${String(sessionId)} ${preview}` : preview;
  }
  return sessionId ? `#${String(sessionId)}` : "";
}
function getAgentLifecycleSummary(name, input) {
  switch (name) {
    case "spawn_agent": {
      const msg = typeof input.message === "string" ? input.message : "";
      return msg.length > 50 ? `${msg.slice(0, 50)}...` : msg;
    }
    case "send_input": {
      const msg = typeof input.message === "string" ? input.message : "";
      return msg.length > 40 ? `${msg.slice(0, 40)}...` : msg;
    }
    case "wait": {
      const ids = Array.isArray(input.ids) ? input.ids.length : 0;
      const timeoutMs = typeof input.timeout_ms === "number" ? input.timeout_ms : void 0;
      const parts = [];
      if (ids > 0) parts.push(`${ids} agent${ids === 1 ? "" : "s"}`);
      if (timeoutMs !== void 0) parts.push(`${Math.round(timeoutMs / 1e3)}s`);
      return parts.join(", ");
    }
    case "resume_agent":
    case "close_agent":
      return "";
    default:
      return "";
  }
}
function shortenPath(filePath) {
  if (!filePath) return "";
  const normalized = filePath.replace(/\\/g, "/");
  const parts = normalized.split("/");
  if (parts.length <= 3) return normalized;
  return ".../" + parts.slice(-2).join("/");
}
function truncateText(text, maxLength) {
  if (text.length <= maxLength) return text;
  return text.substring(0, maxLength) + "...";
}
function parseToolSearchQuery(query) {
  if (!query) return "";
  const selectPrefix = "select:";
  const body = query.startsWith(selectPrefix) ? query.slice(selectPrefix.length) : query;
  return body.split(",").map((s4) => s4.trim()).filter(Boolean).join(", ");
}
function normalizeWebSearchDisplayData(input) {
  var _a3;
  const queries = Array.isArray(input.queries) ? input.queries.filter((entry) => typeof entry === "string" && entry.trim().length > 0).map((entry) => entry.trim()) : [];
  const query = typeof input.query === "string" && input.query.trim() ? input.query.trim() : (_a3 = queries[0]) != null ? _a3 : "";
  const url2 = typeof input.url === "string" && input.url.trim() ? input.url.trim() : "";
  const pattern = typeof input.pattern === "string" && input.pattern.trim() ? input.pattern.trim() : "";
  const explicitActionType = typeof input.actionType === "string" && input.actionType.trim() ? input.actionType.trim() : "";
  const actionType = explicitActionType || (url2 && pattern ? "find_in_page" : url2 ? "open_page" : query || queries.length > 0 ? "search" : "");
  return { actionType, query, queries, url: url2, pattern };
}
function getWebSearchSummary(input, maxLength) {
  const data = normalizeWebSearchDisplayData(input);
  switch (data.actionType) {
    case "open_page":
      return truncateText(`Open ${data.url || "page"}`, maxLength);
    case "find_in_page": {
      const target = data.pattern ? `Find "${data.pattern}"` : "Find in page";
      const suffix = data.url ? ` in ${data.url}` : "";
      return truncateText(target + suffix, maxLength);
    }
    case "search":
      return truncateText(data.query || data.queries[0] || "", maxLength);
    default:
      return truncateText(data.query || data.url || data.pattern || "", maxLength);
  }
}
function getWebSearchLabel(input, maxLength) {
  const summary = getWebSearchSummary(input, maxLength);
  return `WebSearch: ${summary || "search"}`;
}
function appendToolLink(parent, title, url2) {
  const linkEl = parent.createEl("a", { cls: "claudian-tool-link" });
  linkEl.setAttribute("href", url2);
  linkEl.setAttribute("target", "_blank");
  linkEl.setAttribute("rel", "noopener noreferrer");
  const iconEl = linkEl.createSpan({ cls: "claudian-tool-link-icon" });
  (0, import_obsidian25.setIcon)(iconEl, "external-link");
  linkEl.createSpan({ cls: "claudian-tool-link-title", text: title });
}
function isPlaceholderWebSearchResult(result) {
  if (!result) return true;
  const normalized = result.trim().toLowerCase();
  return normalized === "" || normalized === "search complete";
}
function parseWebSearchResult(result) {
  const linksMatch = result.match(/Links:\s*(\[[\s\S]*?\])(?:\n|$)/);
  if (!linksMatch) return null;
  try {
    const parsed = JSON.parse(linksMatch[1]);
    if (!Array.isArray(parsed) || parsed.length === 0) return null;
    const linksEndIndex = result.indexOf(linksMatch[0]) + linksMatch[0].length;
    const summary = result.slice(linksEndIndex).trim();
    return { links: parsed.filter((l2) => l2.title && l2.url), summary };
  } catch (e2) {
    return null;
  }
}
function renderWebSearchActionExpanded(container, input) {
  const data = normalizeWebSearchDisplayData(input);
  const hasStructuredData = Boolean(data.actionType || data.query || data.queries.length || data.url || data.pattern);
  if (!hasStructuredData) {
    return false;
  }
  const linesEl = container.createDiv({ cls: "claudian-tool-lines" });
  switch (data.actionType) {
    case "open_page":
      linesEl.createDiv({ cls: "claudian-tool-line", text: "Open page" });
      if (data.url) {
        appendToolLink(linesEl, data.url, data.url);
      } else {
        linesEl.createDiv({ cls: "claudian-tool-line", text: "URL unavailable" });
      }
      return true;
    case "find_in_page":
      linesEl.createDiv({ cls: "claudian-tool-line", text: "Find in page" });
      if (data.url) {
        appendToolLink(linesEl, data.url, data.url);
      } else {
        linesEl.createDiv({ cls: "claudian-tool-line", text: "URL unavailable" });
      }
      if (data.pattern) {
        linesEl.createDiv({ cls: "claudian-tool-line", text: `Pattern: ${data.pattern}` });
      }
      return true;
    case "search":
    default: {
      const primaryQuery = data.query || data.queries[0];
      linesEl.createDiv({
        cls: "claudian-tool-line",
        text: primaryQuery ? `Query: ${primaryQuery}` : "Search web"
      });
      const alternateQueries = data.queries.filter((query) => query !== primaryQuery);
      for (const query of alternateQueries.slice(0, 4)) {
        linesEl.createDiv({ cls: "claudian-tool-line", text: `Alt query: ${query}` });
      }
      if (alternateQueries.length > 4) {
        linesEl.createDiv({
          cls: "claudian-tool-truncated",
          text: `... ${alternateQueries.length - 4} more queries`
        });
      }
      return true;
    }
  }
}
function renderWebSearchExpanded(container, input, result) {
  const parsed = result ? parseWebSearchResult(result) : null;
  if (parsed && parsed.links.length > 0) {
    const linksEl = container.createDiv({ cls: "claudian-tool-lines" });
    for (const link of parsed.links) {
      appendToolLink(linksEl, link.title, link.url);
    }
    if (parsed.summary) {
      const summaryEl = container.createDiv({ cls: "claudian-tool-web-summary" });
      summaryEl.setText(parsed.summary.length > 800 ? parsed.summary.slice(0, 800) + "..." : parsed.summary);
    }
    return;
  }
  const data = normalizeWebSearchDisplayData(input);
  const shouldRenderAction = Boolean(data.actionType || data.query || data.queries.length || data.url || data.pattern) && (!result || isPlaceholderWebSearchResult(result) || data.actionType === "open_page" || data.actionType === "find_in_page");
  if (shouldRenderAction && renderWebSearchActionExpanded(container, input)) {
    if (result && !isPlaceholderWebSearchResult(result)) {
      renderLinesExpanded(container, result, 12);
    }
    return;
  }
  if (result) {
    renderLinesExpanded(container, result, 20);
    return;
  }
  if (renderWebSearchActionExpanded(container, input)) {
    return;
  }
  container.createDiv({ cls: "claudian-tool-empty", text: "No result" });
}
function renderFileSearchExpanded(container, result) {
  const lines = result.split(/\r?\n/).filter((line) => line.trim());
  if (lines.length === 0) {
    container.createDiv({ cls: "claudian-tool-empty", text: "No matches found" });
    return;
  }
  renderLinesExpanded(container, result, 15, true);
}
function renderLinesExpanded(container, result, maxLines, hoverable = false) {
  const lines = result.split(/\r?\n/);
  const truncated = lines.length > maxLines;
  const displayLines = truncated ? lines.slice(0, maxLines) : lines;
  const linesEl = container.createDiv({ cls: "claudian-tool-lines" });
  for (const line of displayLines) {
    const stripped = line.replace(/^\s*\d+→/, "");
    const lineEl = linesEl.createDiv({ cls: "claudian-tool-line" });
    if (hoverable) lineEl.addClass("hoverable");
    lineEl.setText(stripped || " ");
  }
  if (truncated) {
    linesEl.createDiv({
      cls: "claudian-tool-truncated",
      text: `... ${lines.length - maxLines} more lines`
    });
  }
}
function renderToolSearchExpanded(container, result) {
  let toolNames = [];
  try {
    const parsed = JSON.parse(result);
    if (Array.isArray(parsed)) {
      toolNames = parsed.filter((item) => item.type === "tool_reference" && item.tool_name).map((item) => item.tool_name);
    }
  } catch (e2) {
  }
  if (toolNames.length === 0) {
    renderLinesExpanded(container, result, 20);
    return;
  }
  for (const name of toolNames) {
    const lineEl = container.createDiv({ cls: "claudian-tool-search-item" });
    const iconEl = lineEl.createSpan({ cls: "claudian-tool-search-icon" });
    setToolIcon(iconEl, name);
    lineEl.createSpan({ text: name });
  }
}
function renderWebFetchExpanded(container, result) {
  const maxChars = 500;
  const linesEl = container.createDiv({ cls: "claudian-tool-lines" });
  const lineEl = linesEl.createDiv({ cls: "claudian-tool-line" });
  lineEl.style.whiteSpace = "pre-wrap";
  lineEl.style.wordBreak = "break-word";
  if (result.length > maxChars) {
    lineEl.setText(result.slice(0, maxChars));
    linesEl.createDiv({
      cls: "claudian-tool-truncated",
      text: `... ${result.length - maxChars} more characters`
    });
  } else {
    lineEl.setText(result);
  }
}
function renderApplyPatchExpanded(container, input, result) {
  var _a3;
  const patchText = typeof input.patch === "string" ? input.patch : "";
  const parsedDiffs = patchText ? parseApplyPatchDiffs(patchText) : [];
  if (result && /verification failed|^[Ee]rror:/.test(result.trim())) {
    renderLinesExpanded(container, result, 20);
  }
  if (parsedDiffs.length > 0) {
    for (const fileDiff of parsedDiffs) {
      const sectionEl = container.createDiv({ cls: "claudian-tool-patch-section" });
      const statsSuffix = fileDiff.stats.added || fileDiff.stats.removed ? ` (+${fileDiff.stats.added} -${fileDiff.stats.removed})` : "";
      const pathText = fileDiff.movedTo ? `${fileDiff.filePath} -> ${fileDiff.movedTo}` : fileDiff.filePath;
      sectionEl.createDiv({
        cls: "claudian-tool-patch-header",
        text: `${fileDiff.operation}: ${pathText}${statsSuffix}`
      });
      if (fileDiff.operation === "delete" && fileDiff.diffLines.length === 0) {
        sectionEl.createDiv({ cls: "claudian-tool-empty", text: "File deleted" });
        continue;
      }
      if (fileDiff.diffLines.length === 0) {
        sectionEl.createDiv({ cls: "claudian-tool-empty", text: "No textual diff available" });
        continue;
      }
      const diffRow = sectionEl.createDiv({ cls: "claudian-write-edit-diff-row" });
      const diffEl = diffRow.createDiv({ cls: "claudian-write-edit-diff" });
      renderDiffContent(diffEl, fileDiff.diffLines);
    }
    return;
  }
  const changes = Array.isArray(input.changes) ? input.changes : [];
  if (changes.length > 0) {
    const linesEl = container.createDiv({ cls: "claudian-tool-lines" });
    for (const change of changes) {
      if (!change || typeof change !== "object") continue;
      const path24 = typeof change.path === "string" ? change.path : "";
      const kind = typeof change.kind === "string" ? change.kind : "change";
      if (!path24) continue;
      linesEl.createDiv({ cls: "claudian-tool-line", text: `${kind}: ${path24}` });
    }
    return;
  }
  if (patchText) {
    renderLinesExpanded(container, patchText, 80);
    return;
  }
  if (result) {
    const fileMatches = [...result.matchAll(/(?:update|add|delete|create|modify|Applied:\s*)(?:\w+:\s*)?([^\n,]+)/gi)];
    if (fileMatches.length > 0) {
      const linesEl = container.createDiv({ cls: "claudian-tool-lines" });
      for (const match of fileMatches) {
        const filePath = (_a3 = match[1]) == null ? void 0 : _a3.trim();
        if (filePath) {
          const lineEl = linesEl.createDiv({ cls: "claudian-tool-line" });
          lineEl.setText(filePath);
        }
      }
      return;
    }
    renderLinesExpanded(container, result, 20);
    return;
  }
  container.createDiv({ cls: "claudian-tool-empty", text: "No result" });
}
function renderAgentLifecycleExpanded(container, result) {
  const trimmed = result.trim();
  if (trimmed.startsWith("{")) {
    try {
      const parsed = JSON.parse(trimmed);
      const linesEl = container.createDiv({ cls: "claudian-tool-lines" });
      for (const [key, value] of Object.entries(parsed)) {
        const lineEl = linesEl.createDiv({ cls: "claudian-tool-line" });
        const displayValue = typeof value === "object" ? JSON.stringify(value) : String(value);
        lineEl.setText(`${key}: ${displayValue}`);
      }
      return;
    } catch (e2) {
    }
  }
  renderLinesExpanded(container, result, 20);
}
function renderExpandedContent(container, toolName, result, input = {}) {
  if (!result && toolName !== TOOL_WEB_SEARCH && toolName !== TOOL_BASH) {
    container.createDiv({ cls: "claudian-tool-empty", text: "No result" });
    return;
  }
  const resolvedResult = result != null ? result : "";
  if (isAgentLifecycleTool(toolName)) {
    renderAgentLifecycleExpanded(container, resolvedResult);
    return;
  }
  switch (toolName) {
    case TOOL_BASH:
      renderBashContent(container, input, resolvedResult);
      break;
    case TOOL_WRITE_STDIN:
      renderLinesExpanded(container, resolvedResult, 20);
      break;
    case TOOL_READ:
      renderLinesExpanded(container, resolvedResult, 15);
      break;
    case TOOL_GLOB:
    case TOOL_GREP:
    case TOOL_LS:
      renderFileSearchExpanded(container, resolvedResult);
      break;
    case TOOL_WEB_SEARCH:
      renderWebSearchExpanded(container, input, result);
      break;
    case TOOL_WEB_FETCH:
      renderWebFetchExpanded(container, resolvedResult);
      break;
    case TOOL_TOOL_SEARCH:
      renderToolSearchExpanded(container, resolvedResult);
      break;
    case TOOL_APPLY_PATCH:
      renderApplyPatchExpanded(container, input, result);
      break;
    default:
      renderLinesExpanded(container, resolvedResult, 20);
      break;
  }
}
function getTodos(input) {
  const todos = input.todos;
  if (!todos || !Array.isArray(todos)) return void 0;
  return todos;
}
function getCurrentTask(input) {
  const todos = getTodos(input);
  if (!todos) return void 0;
  return todos.find((t2) => t2.status === "in_progress");
}
function areAllTodosCompleted(input) {
  const todos = getTodos(input);
  if (!todos || todos.length === 0) return false;
  return todos.every((t2) => t2.status === "completed");
}
function resetStatusElement(statusEl, statusClass, ariaLabel) {
  statusEl.className = "claudian-tool-status";
  statusEl.empty();
  statusEl.addClass(statusClass);
  statusEl.setAttribute("aria-label", ariaLabel);
}
var STATUS_ICONS = {
  completed: "check",
  error: "x",
  blocked: "shield-off"
};
function setTodoWriteStatus(statusEl, input) {
  const isComplete = areAllTodosCompleted(input);
  const status = isComplete ? "completed" : "running";
  const ariaLabel = isComplete ? "Status: completed" : "Status: in progress";
  resetStatusElement(statusEl, `status-${status}`, ariaLabel);
  if (isComplete) (0, import_obsidian25.setIcon)(statusEl, "check");
}
function setToolStatus(statusEl, status) {
  resetStatusElement(statusEl, `status-${status}`, `Status: ${status}`);
  const icon = STATUS_ICONS[status];
  if (icon) (0, import_obsidian25.setIcon)(statusEl, icon);
}
function renderTodoWriteResult(container, input) {
  container.empty();
  container.addClass("claudian-todo-panel-content");
  container.addClass("claudian-todo-list-container");
  const todos = input.todos;
  if (!todos || !Array.isArray(todos)) {
    const item = container.createSpan({ cls: "claudian-tool-result-item" });
    item.setText("Tasks updated");
    return;
  }
  renderTodoItems(container, todos);
}
function isBlockedToolResult(content, isError) {
  const lower = extractToolResultContent(content, { fallbackIndent: 2 }).toLowerCase();
  if (lower.includes("outside the vault")) return true;
  if (lower.includes("access denied")) return true;
  if (lower.includes("user denied")) return true;
  if (lower.includes("approval")) return true;
  if (isError && lower.includes("deny")) return true;
  return false;
}
function createToolElementStructure(parentEl, toolCall) {
  const toolEl = parentEl.createDiv({ cls: "claudian-tool-call" });
  if (toolCall.name === TOOL_BASH) {
    toolEl.addClass("claudian-tool-call-bash");
  }
  const header = toolEl.createDiv({ cls: "claudian-tool-header" });
  header.setAttribute("tabindex", "0");
  header.setAttribute("role", "button");
  const iconEl = header.createSpan({ cls: "claudian-tool-icon" });
  iconEl.setAttribute("aria-hidden", "true");
  setToolIcon(iconEl, toolCall.name);
  const nameEl = header.createSpan({ cls: "claudian-tool-name" });
  nameEl.setText(getToolName(toolCall.name, toolCall.input));
  const summaryEl = header.createSpan({ cls: "claudian-tool-summary" });
  summaryEl.setText(getToolSummary(toolCall.name, toolCall.input));
  const currentTaskEl = toolCall.name === TOOL_TODO_WRITE ? createCurrentTaskPreview(header, toolCall.input) : null;
  const statusEl = header.createSpan({ cls: "claudian-tool-status" });
  const content = toolEl.createDiv({ cls: "claudian-tool-content" });
  return { toolEl, header, iconEl, nameEl, summaryEl, statusEl, content, currentTaskEl };
}
function formatAnswer(raw) {
  if (Array.isArray(raw)) return raw.join(", ");
  if (typeof raw === "string") return raw;
  return "";
}
function resolveAskUserAnswers(toolCall) {
  if (toolCall.resolvedAnswers) return toolCall.resolvedAnswers;
  const parsed = extractResolvedAnswersFromResultText(toolCall.result);
  if (parsed) {
    toolCall.resolvedAnswers = parsed;
    return parsed;
  }
  return void 0;
}
function renderAskUserQuestionResult(container, toolCall) {
  var _a3;
  container.empty();
  const questions = toolCall.input.questions;
  const answers = resolveAskUserAnswers(toolCall);
  if (!questions || !Array.isArray(questions) || !answers) return false;
  const reviewEl = container.createDiv({ cls: "claudian-ask-review" });
  for (let i2 = 0; i2 < questions.length; i2++) {
    const q10 = questions[i2];
    const answer = formatAnswer(
      (_a3 = q10.id ? answers[q10.id] : void 0) != null ? _a3 : answers[q10.question]
    );
    const pairEl = reviewEl.createDiv({ cls: "claudian-ask-review-pair" });
    pairEl.createDiv({ text: `${i2 + 1}.`, cls: "claudian-ask-review-num" });
    const bodyEl = pairEl.createDiv({ cls: "claudian-ask-review-body" });
    bodyEl.createDiv({ text: q10.question, cls: "claudian-ask-review-q-text" });
    bodyEl.createDiv({
      text: answer || "Not answered",
      cls: answer ? "claudian-ask-review-a-text" : "claudian-ask-review-empty"
    });
  }
  return true;
}
function renderAskUserQuestionFallback(container, toolCall, initialText) {
  container.empty();
  const questions = Array.isArray(toolCall.input.questions) ? toolCall.input.questions : [];
  if (questions.length === 0) {
    contentFallback(container, initialText || toolCall.result || "Waiting for answer...");
    return;
  }
  if (initialText || toolCall.result) {
    container.createDiv({
      cls: "claudian-ask-review-prompt",
      text: initialText || toolCall.result || "Waiting for answer..."
    });
  }
  for (let questionIndex = 0; questionIndex < questions.length; questionIndex++) {
    const question = questions[questionIndex];
    const reviewEl = container.createDiv({ cls: "claudian-ask-review" });
    const pairEl = reviewEl.createDiv({ cls: "claudian-ask-review-pair" });
    pairEl.createDiv({ text: `${questionIndex + 1}.`, cls: "claudian-ask-review-num" });
    const bodyEl = pairEl.createDiv({ cls: "claudian-ask-review-body" });
    bodyEl.createDiv({ text: question.question, cls: "claudian-ask-review-q-text" });
    if (!Array.isArray(question.options) || question.options.length === 0) {
      bodyEl.createDiv({ cls: "claudian-ask-review-empty", text: "No options recorded" });
      continue;
    }
    const listEl = bodyEl.createDiv({ cls: "claudian-ask-list" });
    question.options.forEach((option, optionIndex) => {
      renderAskUserQuestionOption(listEl, option, optionIndex, question.multiSelect === true);
    });
  }
}
function renderAskUserQuestionOption(parentEl, option, optionIndex, isMultiSelect) {
  const itemEl = parentEl.createDiv({ cls: "claudian-ask-item is-disabled" });
  if (isMultiSelect) {
    itemEl.createDiv({ cls: "claudian-ask-check", text: "[ ] " });
  } else {
    itemEl.createDiv({ cls: "claudian-ask-item-num", text: `${optionIndex + 1}. ` });
  }
  const contentEl = itemEl.createDiv({ cls: "claudian-ask-item-content" });
  const labelRowEl = contentEl.createDiv({ cls: "claudian-ask-label-row" });
  labelRowEl.createDiv({ cls: "claudian-ask-item-label", text: option.label });
  if (option.description) {
    contentEl.createDiv({ cls: "claudian-ask-item-desc", text: option.description });
  }
}
function contentFallback(container, text) {
  const resultRow = container.createDiv({ cls: "claudian-tool-result-row" });
  const resultText = resultRow.createSpan({ cls: "claudian-tool-result-text" });
  resultText.setText(text);
}
function renderBashContent(container, input, result, initialText) {
  const command = input.command || "";
  if (command) {
    const cmdEl = container.createDiv({ cls: "claudian-tool-bash-command" });
    cmdEl.setText(`$ ${command}`);
  }
  if (initialText) {
    contentFallback(container, initialText);
  } else if (result) {
    renderLinesExpanded(container, result, 20);
  } else {
    container.createDiv({ cls: "claudian-tool-empty", text: "No result" });
  }
}
function createCurrentTaskPreview(header, input) {
  const currentTaskEl = header.createSpan({ cls: "claudian-tool-current" });
  const currentTask = getCurrentTask(input);
  if (currentTask) {
    currentTaskEl.setText(currentTask.activeForm);
  }
  return currentTaskEl;
}
function createTodoToggleHandler(currentTaskEl, statusEl, onExpandChange) {
  return (expanded) => {
    if (onExpandChange) onExpandChange(expanded);
    if (currentTaskEl) {
      currentTaskEl.style.display = expanded ? "none" : "";
    }
    if (statusEl) {
      statusEl.style.display = expanded ? "none" : "";
    }
  };
}
function renderToolContent(content, toolCall, initialText) {
  var _a3;
  if (toolCall.name === TOOL_TODO_WRITE) {
    content.addClass("claudian-tool-content-todo");
    renderTodoWriteResult(content, toolCall.input);
  } else if (toolCall.name === TOOL_ASK_USER_QUESTION) {
    content.addClass("claudian-tool-content-ask");
    if (initialText) {
      renderAskUserQuestionFallback(content, toolCall, "Waiting for answer...");
    } else if (!renderAskUserQuestionResult(content, toolCall)) {
      renderAskUserQuestionFallback(content, toolCall);
    }
  } else if (toolCall.name === TOOL_BASH) {
    renderBashContent(content, toolCall.input, (_a3 = toolCall.result) != null ? _a3 : "", initialText);
  } else if (initialText) {
    contentFallback(content, initialText);
  } else {
    renderExpandedContent(content, toolCall.name, toolCall.result, toolCall.input);
  }
}
function renderToolCall(parentEl, toolCall, toolCallElements) {
  const { toolEl, header, statusEl, content, currentTaskEl } = createToolElementStructure(parentEl, toolCall);
  toolEl.dataset.toolId = toolCall.id;
  toolCallElements.set(toolCall.id, toolEl);
  statusEl.addClass(`status-${toolCall.status}`);
  statusEl.setAttribute("aria-label", `Status: ${toolCall.status}`);
  renderToolContent(content, toolCall, "Running...");
  const state = { isExpanded: false };
  toolCall.isExpanded = false;
  const todoStatusEl = toolCall.name === TOOL_TODO_WRITE ? statusEl : null;
  setupCollapsible(toolEl, header, content, state, {
    initiallyExpanded: false,
    onToggle: createTodoToggleHandler(currentTaskEl, todoStatusEl, (expanded) => {
      toolCall.isExpanded = expanded;
    }),
    baseAriaLabel: getToolLabel(toolCall.name, toolCall.input)
  });
  return toolEl;
}
function updateToolCallResult(toolId, toolCall, toolCallElements) {
  const toolEl = toolCallElements.get(toolId);
  if (!toolEl) return;
  if (toolCall.name === TOOL_TODO_WRITE) {
    const statusEl2 = toolEl.querySelector(".claudian-tool-status");
    if (statusEl2) {
      setTodoWriteStatus(statusEl2, toolCall.input);
    }
    const content2 = toolEl.querySelector(".claudian-tool-content");
    if (content2) {
      renderTodoWriteResult(content2, toolCall.input);
    }
    const nameEl = toolEl.querySelector(".claudian-tool-name");
    if (nameEl) {
      nameEl.setText(getToolName(toolCall.name, toolCall.input));
    }
    const currentTaskEl = toolEl.querySelector(".claudian-tool-current");
    if (currentTaskEl) {
      const currentTask = getCurrentTask(toolCall.input);
      currentTaskEl.setText(currentTask ? currentTask.activeForm : "");
    }
    return;
  }
  const statusEl = toolEl.querySelector(".claudian-tool-status");
  if (statusEl) {
    setToolStatus(statusEl, toolCall.status);
  }
  if (toolCall.name === TOOL_ASK_USER_QUESTION) {
    const content2 = toolEl.querySelector(".claudian-tool-content");
    if (content2) {
      content2.addClass("claudian-tool-content-ask");
      if (!renderAskUserQuestionResult(content2, toolCall)) {
        renderAskUserQuestionFallback(content2, toolCall);
      }
    }
    return;
  }
  const content = toolEl.querySelector(".claudian-tool-content");
  if (content) {
    content.empty();
    renderExpandedContent(content, toolCall.name, toolCall.result, toolCall.input);
  }
}
function renderStoredToolCall(parentEl, toolCall) {
  const { toolEl, header, statusEl, content, currentTaskEl } = createToolElementStructure(parentEl, toolCall);
  if (toolCall.name === TOOL_TODO_WRITE) {
    setTodoWriteStatus(statusEl, toolCall.input);
  } else {
    setToolStatus(statusEl, toolCall.status);
  }
  renderToolContent(content, toolCall);
  const state = { isExpanded: false };
  const todoStatusEl = toolCall.name === TOOL_TODO_WRITE ? statusEl : null;
  setupCollapsible(toolEl, header, content, state, {
    initiallyExpanded: false,
    onToggle: createTodoToggleHandler(currentTaskEl, todoStatusEl),
    baseAriaLabel: getToolLabel(toolCall.name, toolCall.input)
  });
  return toolEl;
}

// src/features/chat/controllers/InputController.ts
var APPROVAL_OPTION_MAP = {
  "Deny": "deny",
  "Allow once": "allow",
  "Always allow": "allow-always"
};
var DEFAULT_APPROVAL_DECISION_OPTIONS = Object.entries(APPROVAL_OPTION_MAP).map(([label, decision]) => ({
  label,
  value: label,
  decision
}));
var InputController = class {
  constructor(deps) {
    this.pendingApprovalInline = null;
    this.pendingAskInline = null;
    this.pendingExitPlanModeInline = null;
    this.pendingPlanApproval = null;
    this.pendingPlanApprovalInvalidated = false;
    this.activeResumeDropdown = null;
    this.inputContainerHideDepth = 0;
    this.steerInFlight = false;
    this.pendingSteerMessage = null;
    this.activeStreamingAssistantMessage = null;
    this.pendingProviderUserMessages = [];
    this.sawInitialProviderUserMessage = false;
    this.awaitingProviderAssistantStart = false;
    this.deps = deps;
  }
  getAgentService() {
    var _a3, _b2, _c;
    return (_c = (_b2 = (_a3 = this.deps).getAgentService) == null ? void 0 : _b2.call(_a3)) != null ? _c : null;
  }
  getAuxiliaryModel() {
    var _a3, _b2, _c, _d2, _e, _f;
    return (_f = (_e = (_b2 = (_a3 = this.deps).getAuxiliaryModel) == null ? void 0 : _b2.call(_a3)) != null ? _e : (_d2 = (_c = this.getAgentService()) == null ? void 0 : _c.getAuxiliaryModel) == null ? void 0 : _d2.call(_c)) != null ? _f : null;
  }
  syncInstructionRefineModelOverride(instructionRefineService) {
    var _a3, _b2;
    (_b2 = instructionRefineService.setModelOverride) == null ? void 0 : _b2.call(instructionRefineService, (_a3 = this.getAuxiliaryModel()) != null ? _a3 : void 0);
  }
  getActiveProviderId() {
    var _a3, _b2, _c, _d2, _e, _f;
    const agentService = this.getAgentService();
    const conversationId = this.deps.state.currentConversationId;
    if (!conversationId) {
      return (_d2 = (_c = (_b2 = (_a3 = this.deps).getTabProviderId) == null ? void 0 : _b2.call(_a3)) != null ? _c : agentService == null ? void 0 : agentService.providerId) != null ? _d2 : DEFAULT_CHAT_PROVIDER_ID;
    }
    if (agentService == null ? void 0 : agentService.providerId) {
      return agentService.providerId;
    }
    return (_f = (_e = this.deps.plugin.getConversationSync(conversationId)) == null ? void 0 : _e.providerId) != null ? _f : DEFAULT_CHAT_PROVIDER_ID;
  }
  getActiveCapabilities() {
    const providerId = this.getActiveProviderId();
    const agentService = this.getAgentService();
    if ((agentService == null ? void 0 : agentService.providerId) === providerId) {
      return agentService.getCapabilities();
    }
    return ProviderRegistry.getCapabilities(providerId);
  }
  isResumeSessionAtStillNeeded(resumeUuid, previousMessages) {
    for (let i2 = previousMessages.length - 1; i2 >= 0; i2--) {
      if (previousMessages[i2].role === "assistant" && previousMessages[i2].assistantMessageId === resumeUuid) {
        return i2 === previousMessages.length - 1;
      }
    }
    return false;
  }
  // ============================================
  // Message Sending
  // ============================================
  async sendMessage(options) {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l;
    const {
      plugin,
      state,
      renderer,
      streamController,
      selectionController,
      browserSelectionController,
      canvasSelectionController,
      conversationController
    } = this.deps;
    if (state.isCreatingConversation || state.isSwitchingConversation) return;
    const inputEl = this.deps.getInputEl();
    const imageContextManager = this.deps.getImageContextManager();
    const fileContextManager = this.deps.getFileContextManager();
    const contentOverride = options == null ? void 0 : options.content;
    const shouldUseInput = contentOverride === void 0;
    const content = (contentOverride != null ? contentOverride : inputEl.value).trim();
    const hasImages = (_a3 = imageContextManager == null ? void 0 : imageContextManager.hasImages()) != null ? _a3 : false;
    if (!content && !hasImages) return;
    const builtInCmd = detectBuiltInCommand(content);
    if (builtInCmd) {
      if (shouldUseInput) {
        inputEl.value = "";
        this.deps.resetInputHeight();
      }
      await this.executeBuiltInCommand(builtInCmd.command, builtInCmd.args);
      return;
    }
    if (state.isStreaming) {
      const images2 = hasImages ? [...(imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || []] : void 0;
      const editorContext = selectionController.getContext();
      const browserContext = (_b2 = browserSelectionController == null ? void 0 : browserSelectionController.getContext()) != null ? _b2 : null;
      const canvasContext = canvasSelectionController.getContext();
      state.queuedMessage = this.mergeQueuedMessages(state.queuedMessage, {
        content,
        images: images2,
        editorContext,
        browserContext,
        canvasContext
      });
      if (shouldUseInput) {
        inputEl.value = "";
        this.deps.resetInputHeight();
      }
      imageContextManager == null ? void 0 : imageContextManager.clearImages();
      this.updateQueueIndicator();
      return;
    }
    if (shouldUseInput) {
      inputEl.value = "";
      this.deps.resetInputHeight();
    }
    state.isStreaming = true;
    state.cancelRequested = false;
    state.ignoreUsageUpdates = false;
    this.deps.getSubagentManager().resetSpawnedCount();
    state.autoScrollEnabled = (_c = plugin.settings.enableAutoScroll) != null ? _c : true;
    const streamGeneration = state.bumpStreamGeneration();
    const welcomeEl = this.deps.getWelcomeEl();
    if (welcomeEl) {
      welcomeEl.style.display = "none";
    }
    fileContextManager == null ? void 0 : fileContextManager.startSession();
    const images = (imageContextManager == null ? void 0 : imageContextManager.getAttachedImages()) || [];
    const imagesForMessage = images.length > 0 ? [...images] : void 0;
    const isCompact = /^\/compact(\s|$)/i.test(content);
    if (shouldUseInput) {
      imageContextManager == null ? void 0 : imageContextManager.clearImages();
    }
    const { displayContent, turnRequest } = this.buildTurnSubmission({
      content,
      images: imagesForMessage,
      editorContextOverride: options == null ? void 0 : options.editorContextOverride,
      browserContextOverride: options == null ? void 0 : options.browserContextOverride,
      canvasContextOverride: options == null ? void 0 : options.canvasContextOverride
    });
    fileContextManager == null ? void 0 : fileContextManager.markCurrentNoteSent();
    const userMsg = {
      id: this.deps.generateId(),
      role: "user",
      content: displayContent,
      displayContent,
      // Original user input (for UI display)
      timestamp: Date.now(),
      images: imagesForMessage
    };
    state.addMessage(userMsg);
    state.hasPendingConversationSave = true;
    renderer.addMessage(userMsg);
    await this.triggerTitleGeneration();
    const assistantMsg = {
      id: this.deps.generateId(),
      role: "assistant",
      content: "",
      timestamp: Date.now(),
      toolCalls: [],
      contentBlocks: []
    };
    state.addMessage(assistantMsg);
    this.activeStreamingAssistantMessage = assistantMsg;
    this.activateStreamingAssistantMessage(assistantMsg);
    this.pendingProviderUserMessages = [{
      displayContent,
      images: imagesForMessage
    }];
    this.sawInitialProviderUserMessage = false;
    this.awaitingProviderAssistantStart = true;
    streamController.showThinkingIndicator(
      isCompact ? "Compacting..." : void 0,
      isCompact ? "claudian-thinking--compact" : void 0
    );
    state.responseStartTime = performance.now();
    let wasInterrupted = false;
    let wasInvalidated = false;
    let didEnqueueToSdk = false;
    let planCompleted = false;
    if (this.deps.ensureServiceInitialized) {
      const ready = await this.deps.ensureServiceInitialized();
      if (!ready) {
        new import_obsidian26.Notice("Failed to initialize agent service. Please try again.");
        streamController.hideThinkingIndicator();
        state.isStreaming = false;
        this.activeStreamingAssistantMessage = null;
        this.resetProviderMessageBoundaryState();
        return;
      }
    }
    const agentService = this.getAgentService();
    if (!agentService) {
      new import_obsidian26.Notice("Agent service not available. Please reload the plugin.");
      this.activeStreamingAssistantMessage = null;
      this.resetProviderMessageBoundaryState();
      return;
    }
    const conversationIdForSend = state.currentConversationId;
    if (conversationIdForSend) {
      const conv = plugin.getConversationSync(conversationIdForSend);
      if (conv == null ? void 0 : conv.resumeAtMessageId) {
        if (this.isResumeSessionAtStillNeeded(conv.resumeAtMessageId, state.messages.slice(0, -2))) {
          agentService.setResumeCheckpoint(conv.resumeAtMessageId);
        } else {
          try {
            await plugin.updateConversation(conversationIdForSend, { resumeAtMessageId: void 0 });
          } catch (e2) {
          }
        }
      }
    }
    try {
      const preparedTurn = agentService.prepareTurn(turnRequest);
      userMsg.content = preparedTurn.persistedContent;
      userMsg.currentNote = preparedTurn.isCompact ? void 0 : preparedTurn.request.currentNotePath;
      const previousMessages = state.messages.slice(0, -2);
      for await (const chunk of agentService.query(preparedTurn, previousMessages)) {
        if (state.streamGeneration !== streamGeneration) {
          wasInvalidated = true;
          break;
        }
        if (state.cancelRequested) {
          wasInterrupted = true;
          break;
        }
        if (await this.handleProviderMessageBoundaryChunk(chunk)) {
          continue;
        }
        await streamController.handleStreamChunk(
          chunk,
          (_d2 = this.activeStreamingAssistantMessage) != null ? _d2 : assistantMsg
        );
      }
    } catch (error48) {
      const errorMsg = error48 instanceof Error ? error48.message : "Unknown error";
      await streamController.appendText(`

**Error:** ${errorMsg}`);
    } finally {
      const finalAssistantMsg = (_e = this.activeStreamingAssistantMessage) != null ? _e : assistantMsg;
      const turnMetadata = agentService.consumeTurnMetadata();
      userMsg.userMessageId = (_f = turnMetadata.userMessageId) != null ? _f : userMsg.userMessageId;
      finalAssistantMsg.assistantMessageId = (_g = turnMetadata.assistantMessageId) != null ? _g : finalAssistantMsg.assistantMessageId;
      didEnqueueToSdk = didEnqueueToSdk || turnMetadata.wasSent === true;
      planCompleted = planCompleted || turnMetadata.planCompleted === true;
      state.clearFlavorTimerInterval();
      if (!wasInvalidated && state.streamGeneration === streamGeneration) {
        const didCancelThisTurn = wasInterrupted || state.cancelRequested;
        if (didCancelThisTurn && !state.pendingNewSessionPlan) {
          await streamController.appendText('\n\n<span class="claudian-interrupted">Interrupted</span> <span class="claudian-interrupted-hint">\xB7 What should Claudian do instead?</span>');
        }
        streamController.hideThinkingIndicator();
        state.isStreaming = false;
        state.cancelRequested = false;
        this.restorePendingSteerMessageToQueue();
        const hasCompactBoundary = (_h = finalAssistantMsg.contentBlocks) == null ? void 0 : _h.some((b10) => b10.type === "context_compacted");
        if (!didCancelThisTurn && !hasCompactBoundary) {
          const durationSeconds = state.responseStartTime ? Math.floor((performance.now() - state.responseStartTime) / 1e3) : 0;
          if (durationSeconds > 0) {
            const flavorWord = COMPLETION_FLAVOR_WORDS[Math.floor(Math.random() * COMPLETION_FLAVOR_WORDS.length)];
            finalAssistantMsg.durationSeconds = durationSeconds;
            finalAssistantMsg.durationFlavorWord = flavorWord;
            if (state.currentContentEl) {
              const footerEl = state.currentContentEl.createDiv({ cls: "claudian-response-footer" });
              footerEl.createSpan({
                text: `* ${flavorWord} for ${formatDurationMmSs(durationSeconds)}`,
                cls: "claudian-baked-duration"
              });
            }
          }
        }
        state.currentContentEl = null;
        await streamController.finalizeCurrentThinkingBlock(finalAssistantMsg);
        await streamController.finalizeCurrentTextBlock(finalAssistantMsg);
        this.deps.getSubagentManager().resetStreamingState();
        if (state.currentTodos && state.currentTodos.every((t2) => t2.status === "completed")) {
          state.currentTodos = null;
        }
        this.syncScrollToBottomAfterRenderUpdates();
        if (state.pendingNewSessionPlan && finalAssistantMsg.toolCalls) {
          for (const tc of finalAssistantMsg.toolCalls) {
            if (tc.name === TOOL_EXIT_PLAN_MODE && !tc.result) {
              tc.status = "completed";
              tc.result = "User approved the plan and started a new session.";
              updateToolCallResult(tc.id, tc, state.toolCallElements);
            }
          }
        }
        let planAutoSendContent = null;
        let planApprovalInvalidated = false;
        let shouldProcessQueuedMessage = true;
        if (planCompleted && !didCancelThisTurn) {
          const { decision, invalidated } = await this.showPlanApproval();
          if (state.streamGeneration !== streamGeneration || invalidated) {
            planApprovalInvalidated = true;
          } else if ((decision == null ? void 0 : decision.type) === "implement") {
            (_j2 = (_i = this.deps).restorePrePlanPermissionModeIfNeeded) == null ? void 0 : _j2.call(_i);
            planAutoSendContent = "Implement the plan.";
          } else if ((decision == null ? void 0 : decision.type) === "revise") {
            this.deps.getInputEl().value = decision.text;
            shouldProcessQueuedMessage = false;
          } else {
            (_l = (_k = this.deps).restorePrePlanPermissionModeIfNeeded) == null ? void 0 : _l.call(_k);
          }
        }
        if (!planApprovalInvalidated) {
          const saveExtras = didEnqueueToSdk ? { resumeAtMessageId: void 0 } : void 0;
          await conversationController.save(true, saveExtras);
          const userMsgIndex = state.messages.indexOf(userMsg);
          renderer.refreshActionButtons(userMsg, state.messages, userMsgIndex >= 0 ? userMsgIndex : void 0);
          if (planAutoSendContent) {
            this.deps.getInputEl().value = planAutoSendContent;
            this.sendMessage().catch(() => {
            });
          } else {
            const planContent = state.pendingNewSessionPlan;
            if (planContent) {
              state.pendingNewSessionPlan = null;
              await conversationController.createNew();
              this.deps.getInputEl().value = planContent;
              this.sendMessage().catch(() => {
              });
            } else if (shouldProcessQueuedMessage) {
              this.processQueuedMessage();
            }
          }
        }
      }
      if (wasInvalidated) {
        this.clearPendingSteerState();
        this.updateQueueIndicator();
      }
      this.activeStreamingAssistantMessage = null;
      this.resetProviderMessageBoundaryState();
    }
  }
  // ============================================
  // Queue Management
  // ============================================
  updateQueueIndicator() {
    var _a3;
    const { state } = this.deps;
    const indicatorEl = state.queueIndicatorEl;
    if (!indicatorEl) return;
    indicatorEl.empty();
    const visibleQueuedMessage = (_a3 = state.queuedMessage) != null ? _a3 : this.pendingSteerMessage;
    if (visibleQueuedMessage) {
      const isPendingSteerOnly = !state.queuedMessage && !!this.pendingSteerMessage;
      indicatorEl.createSpan({
        cls: "claudian-queue-indicator-text",
        text: `${isPendingSteerOnly ? "\u2319 Steering: " : "\u2319 Queued: "}${this.getQueuedMessageDisplay(visibleQueuedMessage)}`
      });
      if (state.queuedMessage && this.canSteerQueuedMessage()) {
        const steerButton = indicatorEl.createEl("button", {
          cls: "claudian-queue-indicator-action",
          text: this.steerInFlight ? "Steering..." : "Steer Now"
        });
        steerButton.setAttribute("type", "button");
        if (this.steerInFlight) {
          steerButton.setAttribute("disabled", "true");
        } else {
          steerButton.addEventListener("click", (event) => {
            event.stopPropagation();
            void this.steerQueuedMessage();
          });
        }
      }
      indicatorEl.style.display = "flex";
      return;
    }
    indicatorEl.style.display = "none";
  }
  clearQueuedMessage() {
    const { state } = this.deps;
    state.queuedMessage = null;
    this.updateQueueIndicator();
  }
  restoreMessageToInput(message) {
    var _a3;
    if (!message) return;
    const { content, images } = message;
    const inputEl = this.deps.getInputEl();
    inputEl.value = content;
    if (images && images.length > 0) {
      (_a3 = this.deps.getImageContextManager()) == null ? void 0 : _a3.setImages(images);
    }
  }
  restorePendingMessagesToInput() {
    const { state } = this.deps;
    const combinedMessage = this.mergePendingMessages(
      this.pendingSteerMessage,
      state.queuedMessage
    );
    this.restoreMessageToInput(combinedMessage);
    state.queuedMessage = null;
    this.clearPendingSteerState();
    this.updateQueueIndicator();
  }
  processQueuedMessage() {
    var _a3;
    const { state } = this.deps;
    if (!state.queuedMessage) return;
    const { content, images, editorContext, browserContext, canvasContext } = state.queuedMessage;
    state.queuedMessage = null;
    this.updateQueueIndicator();
    const inputEl = this.deps.getInputEl();
    inputEl.value = content;
    if (images && images.length > 0) {
      (_a3 = this.deps.getImageContextManager()) == null ? void 0 : _a3.setImages(images);
    }
    setTimeout(
      () => this.sendMessage({
        editorContextOverride: editorContext,
        browserContextOverride: browserContext != null ? browserContext : null,
        canvasContextOverride: canvasContext
      }),
      0
    );
  }
  buildTurnSubmission(options) {
    var _a3, _b2;
    const {
      selectionController,
      browserSelectionController,
      canvasSelectionController
    } = this.deps;
    const fileContextManager = this.deps.getFileContextManager();
    const mcpServerSelector = this.deps.getMcpServerSelector();
    const externalContextSelector = this.deps.getExternalContextSelector();
    const currentNotePath = (fileContextManager == null ? void 0 : fileContextManager.getCurrentNotePath()) || null;
    const shouldSendCurrentNote = (_a3 = fileContextManager == null ? void 0 : fileContextManager.shouldSendCurrentNote(currentNotePath)) != null ? _a3 : false;
    const editorContext = options.editorContextOverride !== void 0 ? options.editorContextOverride : selectionController.getContext();
    const browserContext = options.browserContextOverride !== void 0 ? options.browserContextOverride : (_b2 = browserSelectionController == null ? void 0 : browserSelectionController.getContext()) != null ? _b2 : null;
    const canvasContext = options.canvasContextOverride !== void 0 ? options.canvasContextOverride : canvasSelectionController.getContext();
    const externalContextPaths = externalContextSelector == null ? void 0 : externalContextSelector.getExternalContexts();
    const isCompact = /^\/compact(\s|$)/i.test(options.content);
    const transformedText = !isCompact && fileContextManager ? fileContextManager.transformContextMentions(options.content) : options.content;
    const enabledMcpServers = mcpServerSelector == null ? void 0 : mcpServerSelector.getEnabledServers();
    return {
      displayContent: options.content,
      turnRequest: {
        text: transformedText,
        images: options.images,
        currentNotePath: shouldSendCurrentNote && currentNotePath ? currentNotePath : void 0,
        editorSelection: editorContext,
        browserSelection: browserContext,
        canvasSelection: canvasContext,
        externalContextPaths: externalContextPaths && externalContextPaths.length > 0 ? externalContextPaths : void 0,
        enabledMcpServers: enabledMcpServers && enabledMcpServers.size > 0 ? enabledMcpServers : void 0
      }
    };
  }
  getQueuedMessageDisplay(message) {
    var _a3, _b2;
    if (!message) {
      return "";
    }
    const rawContent = message.content.trim();
    const preview = rawContent.length > 40 ? rawContent.slice(0, 40) + "..." : rawContent;
    const hasImages = ((_b2 = (_a3 = message.images) == null ? void 0 : _a3.length) != null ? _b2 : 0) > 0;
    if (hasImages) {
      return preview ? `${preview} [images]` : "[images]";
    }
    return preview;
  }
  canSteerQueuedMessage() {
    const agentService = this.getAgentService();
    return this.deps.state.isStreaming && this.getActiveCapabilities().supportsTurnSteer === true && typeof (agentService == null ? void 0 : agentService.steer) === "function";
  }
  cloneQueuedMessage(message) {
    return {
      ...message,
      images: message.images ? [...message.images] : void 0
    };
  }
  mergePendingMessages(first, second) {
    if (first && second) {
      return this.mergeQueuedMessages(first, second);
    }
    if (first) {
      return this.cloneQueuedMessage(first);
    }
    if (second) {
      return this.cloneQueuedMessage(second);
    }
    return null;
  }
  clearPendingSteerState() {
    this.pendingSteerMessage = null;
    this.steerInFlight = false;
  }
  restorePendingSteerMessageToQueue() {
    if (!this.pendingSteerMessage) {
      return;
    }
    const { state } = this.deps;
    const pendingSteerMessage = this.cloneQueuedMessage(this.pendingSteerMessage);
    this.clearPendingSteerState();
    state.queuedMessage = state.queuedMessage ? this.mergeQueuedMessages(pendingSteerMessage, state.queuedMessage) : pendingSteerMessage;
    this.updateQueueIndicator();
  }
  mergeQueuedMessages(existing, incoming) {
    if (!existing) {
      return {
        ...incoming,
        images: incoming.images ? [...incoming.images] : void 0
      };
    }
    const contentParts = [existing.content, incoming.content].filter((part) => part.length > 0);
    return {
      content: contentParts.join("\n\n"),
      images: [...existing.images || [], ...incoming.images || []].filter(Boolean).length > 0 ? [...existing.images || [], ...incoming.images || []] : void 0,
      editorContext: incoming.editorContext,
      browserContext: incoming.browserContext,
      canvasContext: incoming.canvasContext
    };
  }
  async steerQueuedMessage() {
    var _a3, _b2;
    if (this.steerInFlight) {
      return;
    }
    const { state } = this.deps;
    const agentService = this.getAgentService();
    if (!state.queuedMessage || !this.canSteerQueuedMessage() || !(agentService == null ? void 0 : agentService.steer)) {
      return;
    }
    const queuedMessage = this.cloneQueuedMessage(state.queuedMessage);
    state.queuedMessage = null;
    this.pendingSteerMessage = queuedMessage;
    this.steerInFlight = true;
    this.updateQueueIndicator();
    try {
      const { displayContent, turnRequest } = this.buildTurnSubmission({
        content: queuedMessage.content,
        images: queuedMessage.images,
        editorContextOverride: queuedMessage.editorContext,
        browserContextOverride: (_a3 = queuedMessage.browserContext) != null ? _a3 : null,
        canvasContextOverride: queuedMessage.canvasContext
      });
      const preparedTurn = agentService.prepareTurn(turnRequest);
      const accepted = await agentService.steer(preparedTurn);
      if (state.cancelRequested || !this.pendingSteerMessage) {
        return;
      }
      if (!accepted) {
        this.restoreQueuedMessageAfterSteerFailure(queuedMessage);
        return;
      }
      (_b2 = this.deps.getFileContextManager()) == null ? void 0 : _b2.markCurrentNoteSent();
      this.pendingProviderUserMessages.push({
        displayContent,
        persistedContent: preparedTurn.persistedContent,
        currentNote: preparedTurn.isCompact ? void 0 : preparedTurn.request.currentNotePath,
        images: queuedMessage.images
      });
    } catch (e2) {
      this.restoreQueuedMessageAfterSteerFailure(queuedMessage);
      new import_obsidian26.Notice("Failed to steer the queued Codex message. It is still available.");
    }
  }
  restoreQueuedMessageAfterSteerFailure(message) {
    const { state } = this.deps;
    this.clearPendingSteerState();
    if (state.cancelRequested) {
      this.updateQueueIndicator();
      return;
    }
    if (state.isStreaming) {
      state.queuedMessage = state.queuedMessage ? this.mergeQueuedMessages(message, state.queuedMessage) : message;
      this.updateQueueIndicator();
      return;
    }
    this.restoreMessageToInput(message);
    this.updateQueueIndicator();
  }
  activateStreamingAssistantMessage(message) {
    const { state, renderer } = this.deps;
    const msgEl = renderer.addMessage(message);
    const contentEl = msgEl.querySelector(".claudian-message-content");
    if (!contentEl) {
      return;
    }
    if (!state.currentContentEl) {
      state.toolCallElements.clear();
    }
    state.currentContentEl = contentEl;
    state.currentTextEl = null;
    state.currentTextContent = "";
    state.currentThinkingState = null;
  }
  resetProviderMessageBoundaryState() {
    this.pendingProviderUserMessages = [];
    this.sawInitialProviderUserMessage = false;
    this.awaitingProviderAssistantStart = false;
  }
  async handleProviderMessageBoundaryChunk(chunk) {
    switch (chunk.type) {
      case "user_message_start":
        await this.handleProviderUserMessageStart(chunk);
        return true;
      case "assistant_message_start":
        await this.handleProviderAssistantMessageStart();
        return true;
      default:
        return false;
    }
  }
  async handleProviderUserMessageStart(chunk) {
    var _a3, _b2, _c;
    const expected = this.pendingProviderUserMessages.shift();
    if (!this.sawInitialProviderUserMessage) {
      this.sawInitialProviderUserMessage = true;
      return;
    }
    this.clearPendingSteerState();
    this.updateQueueIndicator();
    const previousAssistant = this.activeStreamingAssistantMessage;
    const shouldDiscardPlaceholder = this.shouldDiscardPendingAssistantPlaceholder(previousAssistant);
    if (previousAssistant) {
      if (shouldDiscardPlaceholder) {
        this.discardStreamingAssistantMessage(previousAssistant.id);
      } else {
        await this.deps.streamController.finalizeCurrentThinkingBlock(previousAssistant);
        await this.deps.streamController.finalizeCurrentTextBlock(previousAssistant);
      }
    }
    this.deps.streamController.hideThinkingIndicator();
    const displayContent = (_a3 = expected == null ? void 0 : expected.displayContent) != null ? _a3 : chunk.content;
    const persistedContent = (_b2 = expected == null ? void 0 : expected.persistedContent) != null ? _b2 : displayContent;
    const images = expected == null ? void 0 : expected.images;
    if (displayContent || ((_c = images == null ? void 0 : images.length) != null ? _c : 0) > 0) {
      const userMessage = {
        id: this.deps.generateId(),
        role: "user",
        content: persistedContent,
        displayContent,
        timestamp: Date.now(),
        currentNote: expected == null ? void 0 : expected.currentNote,
        images
      };
      this.deps.state.addMessage(userMessage);
      this.deps.renderer.addMessage(userMessage);
    }
    const assistantMessage = {
      id: this.deps.generateId(),
      role: "assistant",
      content: "",
      timestamp: Date.now(),
      toolCalls: [],
      contentBlocks: []
    };
    this.deps.state.addMessage(assistantMessage);
    this.activeStreamingAssistantMessage = assistantMessage;
    this.activateStreamingAssistantMessage(assistantMessage);
    this.deps.streamController.showThinkingIndicator();
    this.deps.state.responseStartTime = performance.now();
    this.awaitingProviderAssistantStart = true;
  }
  async handleProviderAssistantMessageStart() {
    if (this.awaitingProviderAssistantStart) {
      this.awaitingProviderAssistantStart = false;
      return;
    }
    const previousAssistant = this.activeStreamingAssistantMessage;
    if (previousAssistant) {
      await this.deps.streamController.finalizeCurrentThinkingBlock(previousAssistant);
      await this.deps.streamController.finalizeCurrentTextBlock(previousAssistant);
    }
    const assistantMessage = {
      id: this.deps.generateId(),
      role: "assistant",
      content: "",
      timestamp: Date.now(),
      toolCalls: [],
      contentBlocks: []
    };
    this.deps.state.addMessage(assistantMessage);
    this.activeStreamingAssistantMessage = assistantMessage;
    this.activateStreamingAssistantMessage(assistantMessage);
    this.deps.streamController.showThinkingIndicator();
  }
  shouldDiscardPendingAssistantPlaceholder(message) {
    var _a3, _b2, _c, _d2;
    return this.awaitingProviderAssistantStart && !!message && !message.content.trim() && ((_b2 = (_a3 = message.toolCalls) == null ? void 0 : _a3.length) != null ? _b2 : 0) === 0 && ((_d2 = (_c = message.contentBlocks) == null ? void 0 : _c.length) != null ? _d2 : 0) === 0;
  }
  discardStreamingAssistantMessage(messageId) {
    const { state, renderer } = this.deps;
    state.messages = state.messages.filter((message) => message.id !== messageId);
    renderer.removeMessage(messageId);
    state.currentContentEl = null;
    state.currentTextEl = null;
    state.currentTextContent = "";
    state.currentThinkingState = null;
  }
  // ============================================
  // Title Generation
  // ============================================
  /**
   * Triggers AI title generation after first user message.
   * Handles setting fallback title, firing async generation, and updating UI.
   */
  async triggerTitleGeneration() {
    var _a3, _b2;
    const { plugin, state, conversationController } = this.deps;
    if (state.messages.length !== 1) {
      return;
    }
    if (!state.currentConversationId) {
      const sessionId = (_b2 = (_a3 = this.getAgentService()) == null ? void 0 : _a3.getSessionId()) != null ? _b2 : void 0;
      const conversation = await plugin.createConversation({
        providerId: this.getActiveProviderId(),
        sessionId
      });
      state.currentConversationId = conversation.id;
    }
    const firstUserMsg = state.messages.find((m2) => m2.role === "user");
    if (!firstUserMsg) {
      return;
    }
    const userContent = firstUserMsg.displayContent || firstUserMsg.content;
    const fallbackTitle = conversationController.generateFallbackTitle(userContent);
    await plugin.renameConversation(state.currentConversationId, fallbackTitle);
    if (!plugin.settings.enableAutoTitleGeneration) {
      return;
    }
    const titleService = this.deps.getTitleGenerationService();
    if (!titleService) {
      return;
    }
    await plugin.updateConversation(state.currentConversationId, { titleGenerationStatus: "pending" });
    conversationController.updateHistoryDropdown();
    const convId = state.currentConversationId;
    const expectedTitle = fallbackTitle;
    titleService.generateTitle(
      convId,
      userContent,
      async (conversationId, result) => {
        const currentConv = await plugin.getConversationById(conversationId);
        if (!currentConv) return;
        const userManuallyRenamed = currentConv.title !== expectedTitle;
        if (result.success && !userManuallyRenamed) {
          await plugin.renameConversation(conversationId, result.title);
          await plugin.updateConversation(conversationId, { titleGenerationStatus: "success" });
        } else if (!userManuallyRenamed) {
          await plugin.updateConversation(conversationId, { titleGenerationStatus: "failed" });
        } else {
          await plugin.updateConversation(conversationId, { titleGenerationStatus: void 0 });
        }
        conversationController.updateHistoryDropdown();
      }
    ).catch(() => {
    });
  }
  // ============================================
  // Streaming Control
  // ============================================
  cancelStreaming() {
    var _a3;
    const { state, streamController } = this.deps;
    if (!state.isStreaming) return;
    state.cancelRequested = true;
    this.restorePendingMessagesToInput();
    (_a3 = this.getAgentService()) == null ? void 0 : _a3.cancel();
    streamController.hideThinkingIndicator();
  }
  syncScrollToBottomAfterRenderUpdates() {
    var _a3;
    const { plugin, state } = this.deps;
    if (!((_a3 = plugin.settings.enableAutoScroll) != null ? _a3 : true)) return;
    if (!state.autoScrollEnabled) return;
    requestAnimationFrame(() => {
      var _a4;
      if (!((_a4 = this.deps.plugin.settings.enableAutoScroll) != null ? _a4 : true)) return;
      if (!this.deps.state.autoScrollEnabled) return;
      const messagesEl = this.deps.getMessagesEl();
      messagesEl.scrollTop = messagesEl.scrollHeight;
    });
  }
  // ============================================
  // Instruction Mode
  // ============================================
  async handleInstructionSubmit(rawInstruction) {
    const { plugin } = this.deps;
    const instructionRefineService = this.deps.getInstructionRefineService();
    const instructionModeManager = this.deps.getInstructionModeManager();
    if (!instructionRefineService) return;
    const existingPrompt = plugin.settings.systemPrompt;
    let modal = null;
    let wasCancelled = false;
    try {
      modal = new InstructionModal(
        plugin.app,
        rawInstruction,
        {
          onAccept: async (finalInstruction) => {
            const currentPrompt = plugin.settings.systemPrompt;
            plugin.settings.systemPrompt = appendMarkdownSnippet(currentPrompt, finalInstruction);
            await plugin.saveSettings();
            new import_obsidian26.Notice("Instruction added to custom system prompt");
            instructionModeManager == null ? void 0 : instructionModeManager.clear();
          },
          onReject: () => {
            wasCancelled = true;
            instructionRefineService.cancel();
            instructionModeManager == null ? void 0 : instructionModeManager.clear();
          },
          onClarificationSubmit: async (response) => {
            this.syncInstructionRefineModelOverride(instructionRefineService);
            const result2 = await instructionRefineService.continueConversation(response);
            if (wasCancelled) {
              return;
            }
            if (!result2.success) {
              if (result2.error === "Cancelled") {
                return;
              }
              new import_obsidian26.Notice(result2.error || "Failed to process response");
              modal == null ? void 0 : modal.showError(result2.error || "Failed to process response");
              return;
            }
            if (result2.clarification) {
              modal == null ? void 0 : modal.showClarification(result2.clarification);
            } else if (result2.refinedInstruction) {
              modal == null ? void 0 : modal.showConfirmation(result2.refinedInstruction);
            }
          }
        }
      );
      modal.open();
      this.syncInstructionRefineModelOverride(instructionRefineService);
      instructionRefineService.resetConversation();
      const result = await instructionRefineService.refineInstruction(
        rawInstruction,
        existingPrompt
      );
      if (wasCancelled) {
        return;
      }
      if (!result.success) {
        if (result.error === "Cancelled") {
          instructionModeManager == null ? void 0 : instructionModeManager.clear();
          return;
        }
        new import_obsidian26.Notice(result.error || "Failed to refine instruction");
        modal.showError(result.error || "Failed to refine instruction");
        instructionModeManager == null ? void 0 : instructionModeManager.clear();
        return;
      }
      if (result.clarification) {
        modal.showClarification(result.clarification);
      } else if (result.refinedInstruction) {
        modal.showConfirmation(result.refinedInstruction);
      } else {
        new import_obsidian26.Notice("No instruction received");
        modal.showError("No instruction received");
        instructionModeManager == null ? void 0 : instructionModeManager.clear();
      }
    } catch (error48) {
      const errorMsg = error48 instanceof Error ? error48.message : "Unknown error";
      new import_obsidian26.Notice(`Error: ${errorMsg}`);
      modal == null ? void 0 : modal.showError(errorMsg);
      instructionModeManager == null ? void 0 : instructionModeManager.clear();
    }
  }
  // ============================================
  // Approval Dialogs
  // ============================================
  async handleApprovalRequest(toolName, _input, description, approvalOptions) {
    var _a3;
    const inputContainerEl = this.deps.getInputContainerEl();
    const parentEl = inputContainerEl.parentElement;
    if (!parentEl) {
      throw new Error("Input container is detached from DOM");
    }
    const headerEl = parentEl.createDiv({ cls: "claudian-ask-approval-info" });
    headerEl.remove();
    const toolEl = headerEl.createDiv({ cls: "claudian-ask-approval-tool" });
    const iconEl = toolEl.createSpan({ cls: "claudian-ask-approval-icon" });
    iconEl.setAttribute("aria-hidden", "true");
    setToolIcon(iconEl, toolName);
    toolEl.createSpan({ text: toolName, cls: "claudian-ask-approval-tool-name" });
    if (approvalOptions == null ? void 0 : approvalOptions.decisionReason) {
      headerEl.createDiv({ text: approvalOptions.decisionReason, cls: "claudian-ask-approval-reason" });
    }
    if (approvalOptions == null ? void 0 : approvalOptions.blockedPath) {
      headerEl.createDiv({ text: approvalOptions.blockedPath, cls: "claudian-ask-approval-blocked-path" });
    }
    if (approvalOptions == null ? void 0 : approvalOptions.agentID) {
      headerEl.createDiv({ text: `Agent: ${approvalOptions.agentID}`, cls: "claudian-ask-approval-agent" });
    }
    headerEl.createDiv({ text: description, cls: "claudian-ask-approval-desc" });
    const decisionOptions = (_a3 = approvalOptions == null ? void 0 : approvalOptions.decisionOptions) != null ? _a3 : DEFAULT_APPROVAL_DECISION_OPTIONS;
    const optionDecisionMap = /* @__PURE__ */ new Map();
    const questionOptions = decisionOptions.map((option, index) => {
      var _a4;
      const value = option.value || `approval-option-${index}`;
      if (option.decision) {
        optionDecisionMap.set(value, option.decision);
      }
      return {
        label: option.label,
        description: (_a4 = option.description) != null ? _a4 : "",
        value
      };
    });
    const input = {
      questions: [{
        question: "Allow this action?",
        options: questionOptions,
        isOther: false,
        isSecret: false
      }]
    };
    const result = await this.showInlineQuestion(
      parentEl,
      inputContainerEl,
      input,
      (inline) => {
        this.pendingApprovalInline = inline;
      },
      void 0,
      { title: "Permission required", headerEl, showCustomInput: false, immediateSelect: true }
    );
    if (!result) return "cancel";
    const selected = Object.values(result)[0];
    const selectedValue = Array.isArray(selected) ? selected[0] : selected;
    if (typeof selectedValue !== "string") {
      new import_obsidian26.Notice(`Unexpected approval selection: "${String(selectedValue)}"`);
      return "cancel";
    }
    const decision = optionDecisionMap.get(selectedValue);
    if (decision) {
      return decision;
    }
    return {
      type: "select-option",
      value: selectedValue
    };
  }
  async handleAskUserQuestion(input, signal) {
    const inputContainerEl = this.deps.getInputContainerEl();
    const parentEl = inputContainerEl.parentElement;
    if (!parentEl) {
      throw new Error("Input container is detached from DOM");
    }
    return this.showInlineQuestion(
      parentEl,
      inputContainerEl,
      input,
      (inline) => {
        this.pendingAskInline = inline;
      },
      signal
    );
  }
  showInlineQuestion(parentEl, inputContainerEl, input, setPending, signal, config2) {
    this.deps.streamController.hideThinkingIndicator();
    this.hideInputContainer(inputContainerEl);
    return new Promise((resolve8, reject) => {
      const inline = new InlineAskUserQuestion(
        parentEl,
        input,
        (result) => {
          setPending(null);
          this.restoreInputContainer(inputContainerEl);
          resolve8(result);
        },
        signal,
        config2
      );
      setPending(inline);
      try {
        inline.render();
      } catch (err) {
        setPending(null);
        this.restoreInputContainer(inputContainerEl);
        reject(err);
      }
    });
  }
  async handleExitPlanMode(input, signal) {
    const { state, streamController } = this.deps;
    const inputContainerEl = this.deps.getInputContainerEl();
    const parentEl = inputContainerEl.parentElement;
    if (!parentEl) {
      throw new Error("Input container is detached from DOM");
    }
    streamController.hideThinkingIndicator();
    this.hideInputContainer(inputContainerEl);
    const enrichedInput = state.planFilePath ? { ...input, planFilePath: state.planFilePath } : input;
    const renderContent = (el, markdown) => this.deps.renderer.renderContent(el, markdown);
    const planPathPrefix = this.getActiveCapabilities().planPathPrefix;
    return new Promise((resolve8, reject) => {
      const inline = new InlineExitPlanMode(
        parentEl,
        enrichedInput,
        (decision) => {
          this.pendingExitPlanModeInline = null;
          this.restoreInputContainer(inputContainerEl);
          resolve8(decision);
        },
        signal,
        renderContent,
        planPathPrefix
      );
      this.pendingExitPlanModeInline = inline;
      try {
        inline.render();
      } catch (err) {
        this.pendingExitPlanModeInline = null;
        this.restoreInputContainer(inputContainerEl);
        reject(err);
      }
    });
  }
  dismissPendingApprovalPrompt() {
    if (this.pendingApprovalInline) {
      this.pendingApprovalInline.destroy();
      this.pendingApprovalInline = null;
    }
  }
  dismissPendingApproval() {
    this.dismissPendingApprovalPrompt();
    if (this.pendingAskInline) {
      this.pendingAskInline.destroy();
      this.pendingAskInline = null;
    }
    if (this.pendingExitPlanModeInline) {
      this.pendingExitPlanModeInline.destroy();
      this.pendingExitPlanModeInline = null;
    }
    this.dismissPendingPlanApproval(true);
    this.resetInputContainerVisibility();
  }
  showPlanApproval() {
    const inputContainerEl = this.deps.getInputContainerEl();
    const parentEl = inputContainerEl.parentElement;
    if (!parentEl) {
      return Promise.resolve({ decision: null, invalidated: false });
    }
    this.hideInputContainer(inputContainerEl);
    this.pendingPlanApprovalInvalidated = false;
    return new Promise((resolve8, reject) => {
      const inline = new InlinePlanApproval(
        parentEl,
        (decision) => {
          const invalidated = this.pendingPlanApprovalInvalidated;
          this.pendingPlanApprovalInvalidated = false;
          this.pendingPlanApproval = null;
          this.restoreInputContainer(inputContainerEl);
          resolve8({ decision, invalidated });
        }
      );
      this.pendingPlanApproval = inline;
      try {
        inline.render();
      } catch (err) {
        this.pendingPlanApproval = null;
        this.pendingPlanApprovalInvalidated = false;
        this.restoreInputContainer(inputContainerEl);
        reject(err);
      }
    });
  }
  dismissPendingPlanApproval(invalidated) {
    if (!this.pendingPlanApproval) {
      return;
    }
    if (invalidated) {
      this.pendingPlanApprovalInvalidated = true;
    }
    this.pendingPlanApproval.destroy();
    this.pendingPlanApproval = null;
  }
  hideInputContainer(inputContainerEl) {
    this.inputContainerHideDepth++;
    inputContainerEl.style.display = "none";
  }
  restoreInputContainer(inputContainerEl) {
    if (this.inputContainerHideDepth <= 0) return;
    this.inputContainerHideDepth--;
    if (this.inputContainerHideDepth === 0) {
      inputContainerEl.style.display = "";
    }
  }
  resetInputContainerVisibility() {
    if (this.inputContainerHideDepth > 0) {
      this.inputContainerHideDepth = 0;
      this.deps.getInputContainerEl().style.display = "";
    }
  }
  // ============================================
  // Built-in Commands
  // ============================================
  async executeBuiltInCommand(command, args) {
    const { conversationController } = this.deps;
    const capabilities = this.getActiveCapabilities();
    if (!isBuiltInCommandSupported(command, capabilities)) {
      new import_obsidian26.Notice(`/${command.name} is not supported by this provider.`);
      return;
    }
    switch (command.action) {
      case "clear":
        await conversationController.createNew();
        break;
      case "add-dir": {
        const externalContextSelector = this.deps.getExternalContextSelector();
        if (!externalContextSelector) {
          new import_obsidian26.Notice("External context selector not available.");
          return;
        }
        const result = externalContextSelector.addExternalContext(args);
        if (result.success) {
          new import_obsidian26.Notice(`Added external context: ${result.normalizedPath}`);
        } else {
          new import_obsidian26.Notice(result.error);
        }
        break;
      }
      case "resume":
        this.showResumeDropdown();
        break;
      case "fork": {
        if (!this.getActiveCapabilities().supportsFork) {
          new import_obsidian26.Notice("Fork is not supported by this provider.");
          return;
        }
        if (!this.deps.onForkAll) {
          new import_obsidian26.Notice("Fork not available.");
          return;
        }
        await this.deps.onForkAll();
        break;
      }
      default:
        new import_obsidian26.Notice(`Unknown command: ${command.action}`);
    }
  }
  // ============================================
  // Resume Session Dropdown
  // ============================================
  handleResumeKeydown(e2) {
    var _a3;
    if (!((_a3 = this.activeResumeDropdown) == null ? void 0 : _a3.isVisible())) return false;
    return this.activeResumeDropdown.handleKeydown(e2);
  }
  isResumeDropdownVisible() {
    var _a3, _b2;
    return (_b2 = (_a3 = this.activeResumeDropdown) == null ? void 0 : _a3.isVisible()) != null ? _b2 : false;
  }
  destroyResumeDropdown() {
    if (this.activeResumeDropdown) {
      this.activeResumeDropdown.destroy();
      this.activeResumeDropdown = null;
    }
  }
  showResumeDropdown() {
    var _a3;
    const { plugin, state, conversationController } = this.deps;
    this.destroyResumeDropdown();
    const conversations = plugin.getConversationList();
    if (conversations.length === 0) {
      new import_obsidian26.Notice("No conversations to resume");
      return;
    }
    const openConversation = (_a3 = this.deps.openConversation) != null ? _a3 : ((id) => conversationController.switchTo(id));
    this.activeResumeDropdown = new ResumeSessionDropdown(
      this.deps.getInputContainerEl(),
      this.deps.getInputEl(),
      conversations,
      state.currentConversationId,
      {
        onSelect: (id) => {
          this.destroyResumeDropdown();
          openConversation(id).catch((err) => {
            const msg = err instanceof Error ? err.message : String(err);
            new import_obsidian26.Notice(`Failed to open conversation: ${msg}`);
          });
        },
        onDismiss: () => {
          this.destroyResumeDropdown();
        }
      }
    );
  }
};

// src/features/chat/controllers/NavigationController.ts
var SCROLL_SPEED = 8;
var NavigationController = class {
  constructor(deps) {
    this.scrollDirection = null;
    this.animationFrameId = null;
    this.initialized = false;
    this.disposed = false;
    this.scrollLoop = () => {
      if (this.scrollDirection === null || this.disposed) return;
      const messagesEl = this.deps.getMessagesEl();
      if (!messagesEl) {
        this.stopScrolling();
        return;
      }
      const scrollAmount = this.scrollDirection === "up" ? -SCROLL_SPEED : SCROLL_SPEED;
      messagesEl.scrollTop += scrollAmount;
      this.animationFrameId = requestAnimationFrame(this.scrollLoop);
    };
    this.deps = deps;
    this.boundMessagesKeydown = this.handleMessagesKeydown.bind(this);
    this.boundKeyup = this.handleKeyup.bind(this);
    this.boundInputKeydown = this.handleInputKeydown.bind(this);
  }
  initialize() {
    if (this.initialized || this.disposed) return;
    const messagesEl = this.deps.getMessagesEl();
    const inputEl = this.deps.getInputEl();
    if (!messagesEl || !inputEl) return;
    messagesEl.setAttribute("tabindex", "0");
    messagesEl.addClass("claudian-messages-focusable");
    messagesEl.addEventListener("keydown", this.boundMessagesKeydown);
    document.addEventListener("keyup", this.boundKeyup);
    inputEl.addEventListener("keydown", this.boundInputKeydown, { capture: true });
    this.initialized = true;
  }
  /** Cleans up event listeners and animation frames. */
  dispose() {
    if (this.disposed) return;
    this.disposed = true;
    this.stopScrolling();
    document.removeEventListener("keyup", this.boundKeyup);
    const messagesEl = this.deps.getMessagesEl();
    messagesEl == null ? void 0 : messagesEl.removeEventListener("keydown", this.boundMessagesKeydown);
    messagesEl == null ? void 0 : messagesEl.removeClass("claudian-messages-focusable");
    const inputEl = this.deps.getInputEl();
    inputEl == null ? void 0 : inputEl.removeEventListener("keydown", this.boundInputKeydown, { capture: true });
  }
  // ============================================
  // Messages Panel Keyboard Handling
  // ============================================
  handleMessagesKeydown(e2) {
    if (e2.ctrlKey || e2.metaKey || e2.altKey || e2.shiftKey) return;
    const settings11 = this.deps.getSettings();
    const key = e2.key.toLowerCase();
    if (key === settings11.scrollUpKey.toLowerCase()) {
      e2.preventDefault();
      this.startScrolling("up");
      return;
    }
    if (key === settings11.scrollDownKey.toLowerCase()) {
      e2.preventDefault();
      this.startScrolling("down");
      return;
    }
    if (key === settings11.focusInputKey.toLowerCase()) {
      e2.preventDefault();
      this.deps.getInputEl().focus();
      return;
    }
  }
  handleKeyup(e2) {
    const settings11 = this.deps.getSettings();
    const key = e2.key.toLowerCase();
    if (key === settings11.scrollUpKey.toLowerCase() || key === settings11.scrollDownKey.toLowerCase()) {
      this.stopScrolling();
    }
  }
  // ============================================
  // Input Keyboard Handling (Escape)
  // ============================================
  handleInputKeydown(e2) {
    var _a3, _b2;
    if (e2.key !== "Escape") return;
    if (e2.isComposing) return;
    if (this.deps.isStreaming()) {
      return;
    }
    if ((_b2 = (_a3 = this.deps).shouldSkipEscapeHandling) == null ? void 0 : _b2.call(_a3)) {
      return;
    }
    e2.preventDefault();
    e2.stopPropagation();
    this.deps.getInputEl().blur();
    this.deps.getMessagesEl().focus();
  }
  // ============================================
  // Continuous Scrolling with requestAnimationFrame
  // ============================================
  startScrolling(direction) {
    if (this.scrollDirection === direction) {
      return;
    }
    this.scrollDirection = direction;
    this.scrollLoop();
  }
  stopScrolling() {
    this.scrollDirection = null;
    if (this.animationFrameId !== null) {
      cancelAnimationFrame(this.animationFrameId);
      this.animationFrameId = null;
    }
  }
  // ============================================
  // Public API
  // ============================================
  /** Focuses the messages panel. */
  focusMessages() {
    this.deps.getMessagesEl().focus();
  }
  /** Focuses the input. */
  focusInput() {
    this.deps.getInputEl().focus();
  }
};

// src/features/chat/controllers/SelectionController.ts
var import_obsidian27 = require("obsidian");

// src/shared/components/SelectionHighlight.ts
var import_state = require("@codemirror/state");
var import_view = require("@codemirror/view");
function createSelectionHighlighter() {
  const showHighlight = import_state.StateEffect.define();
  const hideHighlight = import_state.StateEffect.define();
  const selectionHighlightField = import_state.StateField.define({
    create: () => import_view.Decoration.none,
    update: (deco, tr) => {
      for (const e2 of tr.effects) {
        if (e2.is(showHighlight)) {
          const builder = new import_state.RangeSetBuilder();
          builder.add(e2.value.from, e2.value.to, import_view.Decoration.mark({
            class: "claudian-selection-highlight"
          }));
          return builder.finish();
        } else if (e2.is(hideHighlight)) {
          return import_view.Decoration.none;
        }
      }
      return deco.map(tr.changes);
    },
    provide: (f2) => import_view.EditorView.decorations.from(f2)
  });
  const installedEditors2 = /* @__PURE__ */ new WeakSet();
  function ensureHighlightField(editorView) {
    if (!installedEditors2.has(editorView)) {
      editorView.dispatch({
        effects: import_state.StateEffect.appendConfig.of(selectionHighlightField)
      });
      installedEditors2.add(editorView);
    }
  }
  function show(editorView, from, to) {
    ensureHighlightField(editorView);
    editorView.dispatch({
      effects: showHighlight.of({ from, to })
    });
  }
  function hide(editorView) {
    if (installedEditors2.has(editorView)) {
      editorView.dispatch({
        effects: hideHighlight.of(null)
      });
    }
  }
  return { show, hide };
}
var defaultHighlighter = createSelectionHighlighter();
function showSelectionHighlight(editorView, from, to) {
  defaultHighlighter.show(editorView, from, to);
}
function hideSelectionHighlight(editorView) {
  defaultHighlighter.hide(editorView);
}

// src/features/chat/controllers/SelectionController.ts
var SELECTION_POLL_INTERVAL = 250;
var INPUT_HANDOFF_GRACE_MS = 1500;
var HIGHLIGHT_KEY = "claudian-selection";
var SelectionController = class {
  constructor(app, indicatorEl, inputEl, contextRowEl, onVisibilityChange, focusScopeEl) {
    this.storedSelection = null;
    this.inputHandoffGraceUntil = null;
    this.pollInterval = null;
    this.focusScopePointerDownHandler = () => {
      if (!this.storedSelection) return;
      this.inputHandoffGraceUntil = Date.now() + INPUT_HANDOFF_GRACE_MS;
    };
    this.app = app;
    this.indicatorEl = indicatorEl;
    this.inputEl = inputEl;
    this.focusScopeEl = focusScopeEl != null ? focusScopeEl : inputEl;
    this.contextRowEl = contextRowEl;
    this.onVisibilityChange = onVisibilityChange != null ? onVisibilityChange : null;
  }
  start() {
    if (this.pollInterval) return;
    this.inputEl.addEventListener("pointerdown", this.focusScopePointerDownHandler);
    if (this.focusScopeEl !== this.inputEl) {
      this.focusScopeEl.addEventListener("pointerdown", this.focusScopePointerDownHandler);
    }
    this.pollInterval = setInterval(() => this.poll(), SELECTION_POLL_INTERVAL);
  }
  stop() {
    if (this.pollInterval) {
      clearInterval(this.pollInterval);
      this.pollInterval = null;
    }
    this.inputEl.removeEventListener("pointerdown", this.focusScopePointerDownHandler);
    if (this.focusScopeEl !== this.inputEl) {
      this.focusScopeEl.removeEventListener("pointerdown", this.focusScopePointerDownHandler);
    }
    this.clear();
  }
  dispose() {
    this.stop();
  }
  // ============================================
  // Selection Polling
  // ============================================
  poll() {
    var _a3;
    const view = this.app.workspace.getActiveViewOfType(import_obsidian27.MarkdownView);
    if (!view) {
      this.clearWhenMarkdownContextIsUnavailable();
      return;
    }
    if (view.getMode() === "preview") {
      this.pollReadingMode(view);
      return;
    }
    const editor = view.editor;
    const editorView = getEditorView(editor);
    if (!editorView) {
      this.clearWhenMarkdownContextIsUnavailable();
      return;
    }
    const selectedText = editor.getSelection();
    if (selectedText.trim()) {
      this.inputHandoffGraceUntil = null;
      const fromPos = editor.getCursor("from");
      const toPos = editor.getCursor("to");
      const from = editor.posToOffset(fromPos);
      const to = editor.posToOffset(toPos);
      const startLine = fromPos.line + 1;
      const notePath = ((_a3 = view.file) == null ? void 0 : _a3.path) || "unknown";
      const lineCount = selectedText.split(/\r?\n/).length;
      const s4 = this.storedSelection;
      const sameRange = s4 && s4.editorView === editorView && s4.from === from && s4.to === to && s4.notePath === notePath;
      const unchanged = sameRange && s4.selectedText === selectedText && s4.lineCount === lineCount && s4.startLine === startLine;
      if (!unchanged) {
        if (s4 && !sameRange) {
          this.clearHighlight();
        }
        this.storedSelection = { notePath, selectedText, lineCount, startLine, from, to, editorView };
        this.updateIndicator();
      }
    } else {
      this.handleDeselection();
    }
  }
  pollReadingMode(view) {
    var _a3, _b2;
    const containerEl = view.containerEl;
    if (!containerEl) {
      this.clearWhenMarkdownContextIsUnavailable();
      return;
    }
    const selection = document.getSelection();
    const selectedText = (_a3 = selection == null ? void 0 : selection.toString()) != null ? _a3 : "";
    if (selectedText.trim()) {
      const anchorNode = selection == null ? void 0 : selection.anchorNode;
      const focusNode = selection == null ? void 0 : selection.focusNode;
      if ((!anchorNode || !containerEl.contains(anchorNode)) && (!focusNode || !containerEl.contains(focusNode))) {
        this.handleDeselection();
        return;
      }
      this.inputHandoffGraceUntil = null;
      const notePath = ((_b2 = view.file) == null ? void 0 : _b2.path) || "unknown";
      const lineCount = selectedText.split(/\r?\n/).length;
      const domRanges = this.cloneDOMRanges(selection);
      const unchanged = this.storedSelection && this.storedSelection.editorView === void 0 && this.storedSelection.notePath === notePath && this.storedSelection.selectedText === selectedText && this.storedSelection.lineCount === lineCount && this.rangeListsMatch(this.storedSelection.domRanges, domRanges);
      if (!unchanged) {
        this.clearHighlight();
        this.storedSelection = { notePath, selectedText, lineCount, domRanges };
        this.updateIndicator();
      }
    } else {
      this.handleDeselection();
    }
  }
  get cssHighlights() {
    return typeof CSS !== "undefined" && CSS.highlights ? CSS.highlights : null;
  }
  rangesMatch(a2, b10) {
    return a2.startContainer === b10.startContainer && a2.startOffset === b10.startOffset && a2.endContainer === b10.endContainer && a2.endOffset === b10.endOffset;
  }
  rangeListsMatch(left, right) {
    return left !== void 0 && left.length === right.length && left.every((range, index) => this.rangesMatch(range, right[index]));
  }
  selectionMatchesRanges(selection, ranges) {
    if (!selection || selection.rangeCount !== ranges.length) return false;
    for (let i2 = 0; i2 < ranges.length; i2++) {
      if (!this.rangesMatch(selection.getRangeAt(i2), ranges[i2])) {
        return false;
      }
    }
    return true;
  }
  cloneDOMRanges(selection) {
    if (!selection) return [];
    const ranges = [];
    for (let i2 = 0; i2 < selection.rangeCount; i2++) {
      ranges.push(selection.getRangeAt(i2).cloneRange());
    }
    return ranges;
  }
  isFocusWithinChatSidebar() {
    const activeElement = document.activeElement;
    return activeElement !== null && (activeElement === this.focusScopeEl || this.focusScopeEl.contains(activeElement));
  }
  isNativeEditorSelectionVisible(sel) {
    if (!sel.editorView || sel.from === void 0 || sel.to === void 0) {
      return false;
    }
    const activeElement = document.activeElement;
    if (activeElement === null || !sel.editorView.dom.contains(activeElement)) {
      return false;
    }
    const cmSel = sel.editorView.state.selection.main;
    return cmSel.from === sel.from && cmSel.to === sel.to;
  }
  isNativePreviewSelectionVisible(ranges) {
    if (this.isFocusWithinChatSidebar()) {
      return false;
    }
    return this.selectionMatchesRanges(document.getSelection(), ranges);
  }
  clearWhenMarkdownContextIsUnavailable() {
    if (!this.storedSelection) return;
    if (this.isFocusWithinChatSidebar()) {
      this.inputHandoffGraceUntil = null;
      return;
    }
    if (this.inputHandoffGraceUntil !== null && Date.now() <= this.inputHandoffGraceUntil) {
      return;
    }
    this.inputHandoffGraceUntil = null;
    this.clearHighlight();
    this.storedSelection = null;
    this.updateIndicator();
  }
  handleDeselection() {
    if (!this.storedSelection) return;
    if (this.isFocusWithinChatSidebar()) {
      this.inputHandoffGraceUntil = null;
      return;
    }
    if (this.inputHandoffGraceUntil !== null && Date.now() <= this.inputHandoffGraceUntil) {
      return;
    }
    this.inputHandoffGraceUntil = null;
    this.clearHighlight();
    this.storedSelection = null;
    this.updateIndicator();
  }
  // ============================================
  // Highlight Management
  // ============================================
  showHighlight() {
    var _a3, _b2, _c;
    const sel = this.storedSelection;
    if (!sel) return;
    if (sel.editorView && sel.from !== void 0 && sel.to !== void 0) {
      if (this.isNativeEditorSelectionVisible(sel)) {
        hideSelectionHighlight(sel.editorView);
        return;
      }
      showSelectionHighlight(sel.editorView, sel.from, sel.to);
      return;
    }
    if ((_a3 = sel.domRanges) == null ? void 0 : _a3.length) {
      if (this.isNativePreviewSelectionVisible(sel.domRanges)) {
        (_b2 = this.cssHighlights) == null ? void 0 : _b2.delete(HIGHLIGHT_KEY);
        return;
      }
      const validRanges = sel.domRanges.filter((r2) => r2.startContainer.isConnected);
      if (validRanges.length) {
        (_c = this.cssHighlights) == null ? void 0 : _c.set(HIGHLIGHT_KEY, new Highlight(...validRanges));
      }
    }
  }
  clearHighlight() {
    var _a3, _b2;
    if ((_a3 = this.storedSelection) == null ? void 0 : _a3.editorView) {
      hideSelectionHighlight(this.storedSelection.editorView);
    }
    (_b2 = this.cssHighlights) == null ? void 0 : _b2.delete(HIGHLIGHT_KEY);
  }
  // ============================================
  // Indicator
  // ============================================
  updateIndicator() {
    if (!this.indicatorEl) return;
    if (this.storedSelection) {
      const lineText = this.storedSelection.lineCount === 1 ? "line" : "lines";
      this.indicatorEl.textContent = `${this.storedSelection.lineCount} ${lineText} selected`;
      this.indicatorEl.style.display = "block";
    } else {
      this.indicatorEl.style.display = "none";
    }
    this.updateContextRowVisibility();
  }
  updateContextRowVisibility() {
    var _a3;
    if (!this.contextRowEl) return;
    updateContextRowHasContent(this.contextRowEl);
    (_a3 = this.onVisibilityChange) == null ? void 0 : _a3.call(this);
  }
  // ============================================
  // Context Access
  // ============================================
  getContext() {
    if (!this.storedSelection) return null;
    return {
      notePath: this.storedSelection.notePath,
      mode: "selection",
      selectedText: this.storedSelection.selectedText,
      lineCount: this.storedSelection.lineCount,
      ...this.storedSelection.startLine !== void 0 && { startLine: this.storedSelection.startLine }
    };
  }
  hasSelection() {
    return this.storedSelection !== null;
  }
  // ============================================
  // Clear
  // ============================================
  clear() {
    this.inputHandoffGraceUntil = null;
    this.clearHighlight();
    this.storedSelection = null;
    this.updateIndicator();
  }
};

// src/features/chat/controllers/StreamController.ts
var import_obsidian30 = require("obsidian");

// src/core/tools/todo.ts
function isValidTodoItem(item) {
  if (typeof item !== "object" || item === null) return false;
  const record2 = item;
  return typeof record2.content === "string" && record2.content.length > 0 && typeof record2.activeForm === "string" && record2.activeForm.length > 0 && typeof record2.status === "string" && ["pending", "in_progress", "completed"].includes(record2.status);
}
function parseTodoInput(input) {
  if (!input.todos || !Array.isArray(input.todos)) {
    return null;
  }
  const validTodos = [];
  for (const item of input.todos) {
    if (isValidTodoItem(item)) {
      validTodos.push(item);
    }
  }
  return validTodos.length > 0 ? validTodos : null;
}

// src/utils/animationFrame.ts
function scheduleAnimationFrame(callback) {
  if (typeof globalThis.requestAnimationFrame === "function") {
    return {
      kind: "raf",
      id: globalThis.requestAnimationFrame(() => callback())
    };
  }
  return {
    kind: "timeout",
    id: globalThis.setTimeout(callback, 16)
  };
}
function cancelScheduledAnimationFrame(frame) {
  if (frame.kind === "raf" && typeof globalThis.cancelAnimationFrame === "function") {
    globalThis.cancelAnimationFrame(frame.id);
    return;
  }
  globalThis.clearTimeout(frame.id);
}

// src/features/chat/controllers/StreamController.ts
init_path();

// src/features/chat/rendering/subagentLifecycleResolution.ts
function resolveSubagentLifecycleAdapter(activeProviderId, toolName) {
  const activeAdapter = ProviderRegistry.getSubagentLifecycleAdapter(activeProviderId);
  if (!toolName) {
    return activeAdapter;
  }
  return activeAdapter && adapterOwnsTool(activeAdapter, toolName) ? activeAdapter : null;
}
function adapterOwnsTool(adapter, toolName) {
  return adapter.isSpawnTool(toolName) || adapter.isHiddenTool(toolName) || adapter.isWaitTool(toolName) || adapter.isCloseTool(toolName);
}

// src/features/chat/rendering/SubagentRenderer.ts
var import_obsidian28 = require("obsidian");
var SUBAGENT_TOOL_STATUS_ICONS = {
  completed: "check",
  error: "x",
  blocked: "shield-off"
};
function extractTaskDescription(input) {
  return input.description || "Subagent task";
}
function extractTaskPrompt(input) {
  return input.prompt || "";
}
function truncateDescription(description, maxLength = 40) {
  if (description.length <= maxLength) return description;
  return description.substring(0, maxLength) + "...";
}
function createSection(parentEl, title, bodyClass) {
  const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-section" });
  const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-section-header" });
  headerEl.setAttribute("tabindex", "0");
  headerEl.setAttribute("role", "button");
  const titleEl = headerEl.createDiv({ cls: "claudian-subagent-section-title" });
  titleEl.setText(title);
  const bodyEl = wrapperEl.createDiv({ cls: "claudian-subagent-section-body" });
  if (bodyClass) bodyEl.addClass(bodyClass);
  const state = { isExpanded: false };
  setupCollapsible(wrapperEl, headerEl, bodyEl, state, {
    baseAriaLabel: title
  });
  return { wrapperEl, bodyEl };
}
function setPromptText(promptBodyEl, prompt) {
  promptBodyEl.empty();
  const textEl = promptBodyEl.createDiv({ cls: "claudian-subagent-prompt-text" });
  textEl.setText(prompt || "No prompt provided");
}
function updateSyncHeaderAria(state) {
  state.headerEl.setAttribute(
    "aria-label",
    `Subagent task: ${truncateDescription(state.info.description)} - Status: ${state.info.status} - click to expand`
  );
  state.statusEl.setAttribute("aria-label", `Status: ${state.info.status}`);
}
function renderSubagentToolContent(contentEl, toolCall) {
  contentEl.empty();
  if (!toolCall.result && toolCall.status === "running") {
    const emptyEl = contentEl.createDiv({ cls: "claudian-subagent-tool-empty" });
    emptyEl.setText("Running...");
    return;
  }
  renderExpandedContent(contentEl, toolCall.name, toolCall.result, toolCall.input);
}
function setSubagentToolStatus(view, status) {
  view.statusEl.className = "claudian-subagent-tool-status";
  view.statusEl.addClass(`status-${status}`);
  view.statusEl.empty();
  view.statusEl.setAttribute("aria-label", `Status: ${status}`);
  const statusIcon = SUBAGENT_TOOL_STATUS_ICONS[status];
  if (statusIcon) {
    (0, import_obsidian28.setIcon)(view.statusEl, statusIcon);
  }
}
function updateSubagentToolView(view, toolCall) {
  view.wrapperEl.className = `claudian-subagent-tool-item claudian-subagent-tool-${toolCall.status}`;
  view.nameEl.setText(getToolName(toolCall.name, toolCall.input));
  view.summaryEl.setText(getToolSummary(toolCall.name, toolCall.input));
  setSubagentToolStatus(view, toolCall.status);
  renderSubagentToolContent(view.contentEl, toolCall);
}
function createSubagentToolView(parentEl, toolCall) {
  var _a3, _b2;
  const wrapperEl = parentEl.createDiv({
    cls: `claudian-subagent-tool-item claudian-subagent-tool-${toolCall.status}`
  });
  wrapperEl.dataset.toolId = toolCall.id;
  const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-tool-header" });
  headerEl.setAttribute("tabindex", "0");
  headerEl.setAttribute("role", "button");
  const iconEl = headerEl.createDiv({ cls: "claudian-subagent-tool-icon" });
  iconEl.setAttribute("aria-hidden", "true");
  setToolIcon(iconEl, toolCall.name);
  const nameEl = headerEl.createDiv({ cls: "claudian-subagent-tool-name" });
  const summaryEl = headerEl.createDiv({ cls: "claudian-subagent-tool-summary" });
  const statusEl = headerEl.createDiv({ cls: "claudian-subagent-tool-status" });
  const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-tool-content" });
  const collapseState = { isExpanded: (_a3 = toolCall.isExpanded) != null ? _a3 : false };
  setupCollapsible(wrapperEl, headerEl, contentEl, collapseState, {
    initiallyExpanded: (_b2 = toolCall.isExpanded) != null ? _b2 : false,
    onToggle: (expanded) => {
      toolCall.isExpanded = expanded;
    },
    baseAriaLabel: getToolLabel(toolCall.name, toolCall.input)
  });
  const view = {
    wrapperEl,
    nameEl,
    summaryEl,
    statusEl,
    contentEl
  };
  updateSubagentToolView(view, toolCall);
  return view;
}
function ensureResultSection(state) {
  if (state.resultSectionEl && state.resultBodyEl) {
    return { wrapperEl: state.resultSectionEl, bodyEl: state.resultBodyEl };
  }
  const section = createSection(state.contentEl, "Result", "claudian-subagent-result-body");
  section.wrapperEl.addClass("claudian-subagent-section-result");
  state.resultSectionEl = section.wrapperEl;
  state.resultBodyEl = section.bodyEl;
  return section;
}
function setResultText(state, text) {
  const section = ensureResultSection(state);
  section.bodyEl.empty();
  const resultEl = section.bodyEl.createDiv({ cls: "claudian-subagent-result-output" });
  resultEl.setText(text);
}
function hydrateSyncSubagentStateFromStored(state, subagent) {
  state.info.description = subagent.description;
  state.info.prompt = subagent.prompt;
  state.info.mode = subagent.mode;
  state.info.status = subagent.status;
  state.info.result = subagent.result;
  state.labelEl.setText(truncateDescription(subagent.description));
  setPromptText(state.promptBodyEl, subagent.prompt || "");
  for (const originalToolCall of subagent.toolCalls) {
    const toolCall = {
      ...originalToolCall,
      input: { ...originalToolCall.input }
    };
    addSubagentToolCall(state, toolCall);
    if (toolCall.status !== "running" || toolCall.result) {
      updateSubagentToolResult(state, toolCall.id, toolCall);
    }
  }
  if (subagent.status === "completed" || subagent.status === "error") {
    const fallback = subagent.status === "error" ? "ERROR" : "DONE";
    finalizeSubagentBlock(state, subagent.result || fallback, subagent.status === "error");
  } else {
    state.statusEl.className = "claudian-subagent-status status-running";
    state.statusEl.empty();
    updateSyncHeaderAria(state);
  }
}
function createSubagentBlock(parentEl, taskToolId, taskInput) {
  const description = extractTaskDescription(taskInput);
  const prompt = extractTaskPrompt(taskInput);
  const info = {
    id: taskToolId,
    description,
    prompt,
    status: "running",
    toolCalls: [],
    isExpanded: false
  };
  const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" });
  wrapperEl.dataset.subagentId = taskToolId;
  const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" });
  headerEl.setAttribute("tabindex", "0");
  headerEl.setAttribute("role", "button");
  const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" });
  iconEl.setAttribute("aria-hidden", "true");
  (0, import_obsidian28.setIcon)(iconEl, getToolIcon(TOOL_TASK));
  const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" });
  labelEl.setText(truncateDescription(description));
  const statusEl = headerEl.createDiv({ cls: "claudian-subagent-status status-running" });
  statusEl.setAttribute("aria-label", "Status: running");
  const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" });
  const promptSection = createSection(contentEl, "Prompt", "claudian-subagent-prompt-body");
  promptSection.wrapperEl.addClass("claudian-subagent-section-prompt");
  setPromptText(promptSection.bodyEl, prompt);
  const toolsContainerEl = contentEl.createDiv({ cls: "claudian-subagent-tools" });
  setupCollapsible(wrapperEl, headerEl, contentEl, info);
  const state = {
    wrapperEl,
    contentEl,
    headerEl,
    labelEl,
    statusEl,
    promptSectionEl: promptSection.wrapperEl,
    promptBodyEl: promptSection.bodyEl,
    toolsContainerEl,
    resultSectionEl: null,
    resultBodyEl: null,
    toolElements: /* @__PURE__ */ new Map(),
    info
  };
  updateSyncHeaderAria(state);
  return state;
}
function addSubagentToolCall(state, toolCall) {
  var _a3, _b2;
  const existingIndex = state.info.toolCalls.findIndex((tc) => tc.id === toolCall.id);
  if (existingIndex >= 0) {
    const existingToolCall = state.info.toolCalls[existingIndex];
    const mergedToolCall = {
      ...existingToolCall,
      ...toolCall,
      input: {
        ...existingToolCall.input,
        ...toolCall.input
      },
      result: (_a3 = toolCall.result) != null ? _a3 : existingToolCall.result,
      isExpanded: (_b2 = toolCall.isExpanded) != null ? _b2 : existingToolCall.isExpanded
    };
    state.info.toolCalls[existingIndex] = mergedToolCall;
    const existingView = state.toolElements.get(toolCall.id);
    if (existingView) {
      updateSubagentToolView(existingView, mergedToolCall);
    }
    updateSyncHeaderAria(state);
    return;
  }
  state.info.toolCalls.push(toolCall);
  const toolView = createSubagentToolView(state.toolsContainerEl, toolCall);
  state.toolElements.set(toolCall.id, toolView);
  updateSyncHeaderAria(state);
}
function updateSubagentToolResult(state, toolId, toolCall) {
  const idx = state.info.toolCalls.findIndex((tc) => tc.id === toolId);
  if (idx !== -1) {
    state.info.toolCalls[idx] = toolCall;
  }
  const toolView = state.toolElements.get(toolId);
  if (!toolView) {
    return;
  }
  updateSubagentToolView(toolView, toolCall);
}
function finalizeSubagentBlock(state, result, isError) {
  state.info.status = isError ? "error" : "completed";
  state.info.result = result;
  state.labelEl.setText(truncateDescription(state.info.description));
  state.statusEl.className = "claudian-subagent-status";
  state.statusEl.addClass(`status-${state.info.status}`);
  state.statusEl.empty();
  if (state.info.status === "completed") {
    (0, import_obsidian28.setIcon)(state.statusEl, "check");
    state.wrapperEl.removeClass("error");
    state.wrapperEl.addClass("done");
  } else {
    (0, import_obsidian28.setIcon)(state.statusEl, "x");
    state.wrapperEl.removeClass("done");
    state.wrapperEl.addClass("error");
  }
  const finalText = (result == null ? void 0 : result.trim()) ? result : isError ? "ERROR" : "DONE";
  setResultText(state, finalText);
  updateSyncHeaderAria(state);
}
function renderStoredSubagent(parentEl, subagent) {
  const state = createSubagentBlock(parentEl, subagent.id, {
    description: subagent.description,
    prompt: subagent.prompt
  });
  hydrateSyncSubagentStateFromStored(state, subagent);
  return state.wrapperEl;
}
function setAsyncWrapperStatus(wrapperEl, status) {
  const classes = ["pending", "running", "awaiting", "completed", "error", "orphaned", "async"];
  classes.forEach((cls) => wrapperEl.removeClass(cls));
  wrapperEl.addClass("async");
  wrapperEl.addClass(status);
}
function getAsyncDisplayStatus(asyncStatus) {
  switch (asyncStatus) {
    case "completed":
      return "completed";
    case "error":
      return "error";
    case "orphaned":
      return "orphaned";
    default:
      return "running";
  }
}
function getAsyncStatusText(asyncStatus) {
  switch (asyncStatus) {
    case "pending":
      return "Initializing";
    case "completed":
      return "";
    // Just show tick icon, no text
    case "error":
      return "Error";
    case "orphaned":
      return "Orphaned";
    default:
      return "Running in background";
  }
}
function getAsyncStatusAriaLabel(asyncStatus) {
  switch (asyncStatus) {
    case "pending":
      return "Initializing";
    case "completed":
      return "Completed";
    case "error":
      return "Error";
    case "orphaned":
      return "Orphaned";
    default:
      return "Running in background";
  }
}
function updateAsyncLabel(state) {
  state.labelEl.setText(truncateDescription(state.info.description));
  const statusLabel = getAsyncStatusAriaLabel(state.info.asyncStatus);
  state.headerEl.setAttribute(
    "aria-label",
    `Background task: ${truncateDescription(state.info.description)} - ${statusLabel} - click to expand`
  );
}
function renderAsyncContentLikeSync(contentEl, subagent, displayStatus) {
  var _a3;
  contentEl.empty();
  const promptSection = createSection(contentEl, "Prompt", "claudian-subagent-prompt-body");
  promptSection.wrapperEl.addClass("claudian-subagent-section-prompt");
  setPromptText(promptSection.bodyEl, subagent.prompt || "");
  const toolsContainerEl = contentEl.createDiv({ cls: "claudian-subagent-tools" });
  for (const originalToolCall of subagent.toolCalls) {
    const toolCall = {
      ...originalToolCall,
      input: { ...originalToolCall.input }
    };
    createSubagentToolView(toolsContainerEl, toolCall);
  }
  if (displayStatus === "running") {
    return;
  }
  const resultSection = createSection(contentEl, "Result", "claudian-subagent-result-body");
  resultSection.wrapperEl.addClass("claudian-subagent-section-result");
  const resultEl = resultSection.bodyEl.createDiv({ cls: "claudian-subagent-result-output" });
  if (displayStatus === "orphaned") {
    resultEl.setText(subagent.result || "Conversation ended before task completed");
    return;
  }
  const fallback = displayStatus === "error" ? "ERROR" : "DONE";
  const finalText = ((_a3 = subagent.result) == null ? void 0 : _a3.trim()) ? subagent.result : fallback;
  resultEl.setText(finalText);
}
function createAsyncSubagentBlock(parentEl, taskToolId, taskInput) {
  const description = taskInput.description || "Background task";
  const prompt = taskInput.prompt || "";
  const info = {
    id: taskToolId,
    description,
    prompt,
    mode: "async",
    status: "running",
    toolCalls: [],
    isExpanded: false,
    asyncStatus: "pending"
  };
  const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" });
  setAsyncWrapperStatus(wrapperEl, "pending");
  wrapperEl.dataset.asyncSubagentId = taskToolId;
  const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" });
  headerEl.setAttribute("tabindex", "0");
  headerEl.setAttribute("role", "button");
  headerEl.setAttribute("aria-expanded", "false");
  headerEl.setAttribute("aria-label", `Background task: ${description} - Initializing - click to expand`);
  const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" });
  iconEl.setAttribute("aria-hidden", "true");
  (0, import_obsidian28.setIcon)(iconEl, getToolIcon(TOOL_TASK));
  const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" });
  labelEl.setText(truncateDescription(description));
  const statusTextEl = headerEl.createDiv({ cls: "claudian-subagent-status-text" });
  statusTextEl.setText("Initializing");
  const statusEl = headerEl.createDiv({ cls: "claudian-subagent-status status-running" });
  statusEl.setAttribute("aria-label", "Status: running");
  const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" });
  renderAsyncContentLikeSync(contentEl, info, "running");
  setupCollapsible(wrapperEl, headerEl, contentEl, info);
  return {
    wrapperEl,
    contentEl,
    headerEl,
    labelEl,
    statusTextEl,
    statusEl,
    info
  };
}
function updateAsyncSubagentRunning(state, agentId) {
  state.info.asyncStatus = "running";
  state.info.agentId = agentId;
  setAsyncWrapperStatus(state.wrapperEl, "running");
  updateAsyncLabel(state);
  state.statusTextEl.setText("Running in background");
  renderAsyncContentLikeSync(state.contentEl, state.info, "running");
}
function finalizeAsyncSubagent(state, result, isError) {
  state.info.asyncStatus = isError ? "error" : "completed";
  state.info.status = isError ? "error" : "completed";
  state.info.result = result;
  setAsyncWrapperStatus(state.wrapperEl, isError ? "error" : "completed");
  updateAsyncLabel(state);
  state.statusTextEl.setText(isError ? "Error" : "");
  state.statusEl.className = "claudian-subagent-status";
  state.statusEl.addClass(`status-${isError ? "error" : "completed"}`);
  state.statusEl.empty();
  if (isError) {
    (0, import_obsidian28.setIcon)(state.statusEl, "x");
  } else {
    (0, import_obsidian28.setIcon)(state.statusEl, "check");
  }
  if (isError) {
    state.wrapperEl.addClass("error");
  } else {
    state.wrapperEl.addClass("done");
  }
  renderAsyncContentLikeSync(state.contentEl, state.info, isError ? "error" : "completed");
}
function markAsyncSubagentOrphaned(state) {
  state.info.asyncStatus = "orphaned";
  state.info.status = "error";
  state.info.result = "Conversation ended before task completed";
  setAsyncWrapperStatus(state.wrapperEl, "orphaned");
  updateAsyncLabel(state);
  state.statusTextEl.setText("Orphaned");
  state.statusEl.className = "claudian-subagent-status status-error";
  state.statusEl.empty();
  (0, import_obsidian28.setIcon)(state.statusEl, "alert-circle");
  state.wrapperEl.addClass("error");
  state.wrapperEl.addClass("orphaned");
  renderAsyncContentLikeSync(state.contentEl, state.info, "orphaned");
}
function renderStoredAsyncSubagent(parentEl, subagent) {
  const wrapperEl = parentEl.createDiv({ cls: "claudian-subagent-list" });
  const displayStatus = getAsyncDisplayStatus(subagent.asyncStatus);
  setAsyncWrapperStatus(wrapperEl, displayStatus);
  if (displayStatus === "completed") {
    wrapperEl.addClass("done");
  } else if (displayStatus === "error" || displayStatus === "orphaned") {
    wrapperEl.addClass("error");
  }
  wrapperEl.dataset.asyncSubagentId = subagent.id;
  const statusText = getAsyncStatusText(subagent.asyncStatus);
  const statusAriaLabel = getAsyncStatusAriaLabel(subagent.asyncStatus);
  const headerEl = wrapperEl.createDiv({ cls: "claudian-subagent-header" });
  headerEl.setAttribute("tabindex", "0");
  headerEl.setAttribute("role", "button");
  headerEl.setAttribute("aria-expanded", "false");
  headerEl.setAttribute(
    "aria-label",
    `Background task: ${subagent.description} - ${statusAriaLabel} - click to expand`
  );
  const iconEl = headerEl.createDiv({ cls: "claudian-subagent-icon" });
  iconEl.setAttribute("aria-hidden", "true");
  (0, import_obsidian28.setIcon)(iconEl, getToolIcon(TOOL_TASK));
  const labelEl = headerEl.createDiv({ cls: "claudian-subagent-label" });
  labelEl.setText(truncateDescription(subagent.description));
  const statusTextEl = headerEl.createDiv({ cls: "claudian-subagent-status-text" });
  statusTextEl.setText(statusText);
  let statusIconClass;
  switch (displayStatus) {
    case "error":
    case "orphaned":
      statusIconClass = "status-error";
      break;
    case "completed":
      statusIconClass = "status-completed";
      break;
    default:
      statusIconClass = "status-running";
  }
  const statusEl = headerEl.createDiv({ cls: `claudian-subagent-status ${statusIconClass}` });
  statusEl.setAttribute("aria-label", `Status: ${statusAriaLabel}`);
  switch (displayStatus) {
    case "completed":
      (0, import_obsidian28.setIcon)(statusEl, "check");
      break;
    case "error":
      (0, import_obsidian28.setIcon)(statusEl, "x");
      break;
    case "orphaned":
      (0, import_obsidian28.setIcon)(statusEl, "alert-circle");
      break;
  }
  const contentEl = wrapperEl.createDiv({ cls: "claudian-subagent-content" });
  renderAsyncContentLikeSync(contentEl, subagent, displayStatus);
  const state = { isExpanded: false };
  setupCollapsible(wrapperEl, headerEl, contentEl, state);
  return wrapperEl;
}

// src/features/chat/rendering/WriteEditRenderer.ts
var import_obsidian29 = require("obsidian");
function shortenPath2(filePath, maxLength = 40) {
  if (!filePath) return "file";
  const normalized = filePath.replace(/\\/g, "/");
  if (normalized.length <= maxLength) return normalized;
  const parts = normalized.split("/");
  if (parts.length <= 2) {
    return "..." + normalized.slice(-maxLength + 3);
  }
  const filename = parts[parts.length - 1];
  const firstDir = parts[0];
  const available = maxLength - firstDir.length - filename.length - 5;
  if (available < 0) {
    return "..." + filename.slice(-maxLength + 3);
  }
  return `${firstDir}/.../${filename}`;
}
function renderDiffStats(statsEl, stats) {
  if (stats.added > 0) {
    const addedEl = statsEl.createSpan({ cls: "added" });
    addedEl.setText(`+${stats.added}`);
  }
  if (stats.removed > 0) {
    if (stats.added > 0) {
      statsEl.createSpan({ text: " " });
    }
    const removedEl = statsEl.createSpan({ cls: "removed" });
    removedEl.setText(`-${stats.removed}`);
  }
}
function createWriteEditBlock(parentEl, toolCall) {
  const filePath = toolCall.input.file_path || "file";
  const toolName = toolCall.name;
  const wrapperEl = parentEl.createDiv({ cls: "claudian-write-edit-block" });
  wrapperEl.dataset.toolId = toolCall.id;
  const headerEl = wrapperEl.createDiv({ cls: "claudian-write-edit-header" });
  headerEl.setAttribute("tabindex", "0");
  headerEl.setAttribute("role", "button");
  headerEl.setAttribute("aria-label", `${toolName}: ${shortenPath2(filePath)} - click to expand`);
  const iconEl = headerEl.createDiv({ cls: "claudian-write-edit-icon" });
  iconEl.setAttribute("aria-hidden", "true");
  (0, import_obsidian29.setIcon)(iconEl, getToolIcon(toolName));
  const nameEl = headerEl.createDiv({ cls: "claudian-write-edit-name" });
  nameEl.setText(toolName);
  const summaryEl = headerEl.createDiv({ cls: "claudian-write-edit-summary" });
  summaryEl.setText(fileNameOnly(filePath) || "file");
  const statsEl = headerEl.createDiv({ cls: "claudian-write-edit-stats" });
  const statusEl = headerEl.createDiv({ cls: "claudian-write-edit-status status-running" });
  statusEl.setAttribute("aria-label", "Status: running");
  const contentEl = wrapperEl.createDiv({ cls: "claudian-write-edit-content" });
  const loadingRow = contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
  const loadingEl = loadingRow.createDiv({ cls: "claudian-write-edit-loading" });
  loadingEl.setText("Writing...");
  const state = {
    wrapperEl,
    contentEl,
    headerEl,
    nameEl,
    summaryEl,
    statsEl,
    statusEl,
    toolCall,
    isExpanded: false
  };
  setupCollapsible(wrapperEl, headerEl, contentEl, state);
  return state;
}
function updateWriteEditWithDiff(state, diffData) {
  state.statsEl.empty();
  state.contentEl.empty();
  const { diffLines, stats } = diffData;
  state.diffLines = diffLines;
  renderDiffStats(state.statsEl, stats);
  const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
  const diffEl = row.createDiv({ cls: "claudian-write-edit-diff" });
  renderDiffContent(diffEl, diffLines);
}
function finalizeWriteEditBlock(state, isError) {
  state.statusEl.className = "claudian-write-edit-status";
  state.statusEl.empty();
  if (isError) {
    state.statusEl.addClass("status-error");
    (0, import_obsidian29.setIcon)(state.statusEl, "x");
    state.statusEl.setAttribute("aria-label", "Status: error");
    if (!state.diffLines) {
      state.contentEl.empty();
      const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
      const errorEl = row.createDiv({ cls: "claudian-write-edit-error" });
      errorEl.setText(state.toolCall.result || "Error");
    }
  } else if (!state.diffLines) {
    state.contentEl.empty();
    const row = state.contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
    const doneEl = row.createDiv({ cls: "claudian-write-edit-done-text" });
    doneEl.setText("DONE");
  }
  if (isError) {
    state.wrapperEl.addClass("error");
  } else {
    state.wrapperEl.addClass("done");
  }
}
function renderStoredWriteEdit(parentEl, toolCall) {
  const filePath = toolCall.input.file_path || "file";
  const toolName = toolCall.name;
  const isError = toolCall.status === "error" || toolCall.status === "blocked";
  const wrapperEl = parentEl.createDiv({ cls: "claudian-write-edit-block" });
  if (isError) {
    wrapperEl.addClass("error");
  } else if (toolCall.status === "completed") {
    wrapperEl.addClass("done");
  }
  wrapperEl.dataset.toolId = toolCall.id;
  const headerEl = wrapperEl.createDiv({ cls: "claudian-write-edit-header" });
  headerEl.setAttribute("tabindex", "0");
  headerEl.setAttribute("role", "button");
  const iconEl = headerEl.createDiv({ cls: "claudian-write-edit-icon" });
  iconEl.setAttribute("aria-hidden", "true");
  (0, import_obsidian29.setIcon)(iconEl, getToolIcon(toolName));
  const nameEl = headerEl.createDiv({ cls: "claudian-write-edit-name" });
  nameEl.setText(toolName);
  const summaryEl = headerEl.createDiv({ cls: "claudian-write-edit-summary" });
  summaryEl.setText(fileNameOnly(filePath) || "file");
  const statsEl = headerEl.createDiv({ cls: "claudian-write-edit-stats" });
  if (toolCall.diffData) {
    renderDiffStats(statsEl, toolCall.diffData.stats);
  }
  const statusEl = headerEl.createDiv({ cls: "claudian-write-edit-status" });
  if (isError) {
    statusEl.addClass("status-error");
    (0, import_obsidian29.setIcon)(statusEl, "x");
  }
  const contentEl = wrapperEl.createDiv({ cls: "claudian-write-edit-content" });
  const row = contentEl.createDiv({ cls: "claudian-write-edit-diff-row" });
  if (toolCall.diffData && toolCall.diffData.diffLines.length > 0) {
    const diffEl = row.createDiv({ cls: "claudian-write-edit-diff" });
    renderDiffContent(diffEl, toolCall.diffData.diffLines);
  } else if (isError && toolCall.result) {
    const errorEl = row.createDiv({ cls: "claudian-write-edit-error" });
    errorEl.setText(toolCall.result);
  } else {
    const doneEl = row.createDiv({ cls: "claudian-write-edit-done-text" });
    doneEl.setText(isError ? "ERROR" : "DONE");
  }
  const state = { isExpanded: false };
  setupCollapsible(wrapperEl, headerEl, contentEl, state);
  return wrapperEl;
}

// src/features/chat/controllers/StreamController.ts
var _StreamController = class _StreamController {
  // agentId → spawn callId
  constructor(deps) {
    this.pendingTextRenderFrame = null;
    this.pendingTextRenderPromise = null;
    this.resolvePendingTextRender = null;
    this.isTextRenderRunning = false;
    this.pendingThinkingRenderFrame = null;
    this.pendingThinkingRenderPromise = null;
    this.resolvePendingThinkingRender = null;
    this.isThinkingRenderRunning = false;
    this.pendingToolOutputFrames = /* @__PURE__ */ new Map();
    this.pendingScrollFrame = null;
    // Provider lifecycle agent tracking (spawn → wait/close lifecycle)
    this.lifecycleSubagentStates = /* @__PURE__ */ new Map();
    // spawn callId → SubagentState
    this.lifecycleAgentIdToSpawnId = /* @__PURE__ */ new Map();
    this.deps = deps;
  }
  getActiveProviderId() {
    var _a3, _b2, _c, _d2;
    return (_d2 = (_c = (_b2 = (_a3 = this.deps).getAgentService) == null ? void 0 : _b2.call(_a3)) == null ? void 0 : _c.providerId) != null ? _d2 : DEFAULT_CHAT_PROVIDER_ID;
  }
  getSubagentLifecycleAdapter(toolName) {
    return resolveSubagentLifecycleAdapter(this.getActiveProviderId(), toolName);
  }
  normalizeToolResultContent(content) {
    return extractToolResultContent(content, { fallbackIndent: 2 });
  }
  // ============================================
  // Stream Chunk Handling
  // ============================================
  async handleStreamChunk(chunk, msg) {
    var _a3, _b2, _c, _d2, _e;
    const { state } = this.deps;
    switch (chunk.type) {
      case "thinking":
        this.flushPendingTools();
        if (state.currentTextEl) {
          await this.finalizeCurrentTextBlock(msg);
        }
        await this.appendThinking(chunk.content);
        break;
      case "text":
        this.flushPendingTools();
        if (state.currentThinkingState) {
          await this.finalizeCurrentThinkingBlock(msg);
        }
        msg.content += chunk.content;
        await this.appendText(chunk.content);
        break;
      case "tool_use": {
        if (state.currentThinkingState) {
          await this.finalizeCurrentThinkingBlock(msg);
        }
        await this.finalizeCurrentTextBlock(msg);
        if (isSubagentToolName(chunk.name)) {
          this.flushPendingTools();
          this.handleTaskToolUseViaManager(chunk, msg);
          break;
        }
        if (chunk.name === TOOL_AGENT_OUTPUT) {
          this.handleAgentOutputToolUse(chunk, msg);
          break;
        }
        const subagentLifecycleAdapter = this.getSubagentLifecycleAdapter(chunk.name);
        if (subagentLifecycleAdapter == null ? void 0 : subagentLifecycleAdapter.isSpawnTool(chunk.name)) {
          this.handleProviderSubagentSpawn(chunk, msg, subagentLifecycleAdapter);
          break;
        }
        if (subagentLifecycleAdapter == null ? void 0 : subagentLifecycleAdapter.isHiddenTool(chunk.name)) {
          this.handleProviderHiddenSubagentTool(chunk, msg);
          break;
        }
        this.handleRegularToolUse(chunk, msg);
        break;
      }
      case "tool_result": {
        await this.handleToolResult(chunk, msg);
        break;
      }
      case "subagent_tool_use":
      case "subagent_tool_result":
        await this.handleSubagentChunk(chunk, msg);
        break;
      case "tool_output":
        this.handleToolOutput(chunk, msg);
        break;
      case "notice":
        this.flushPendingTools();
        await this.appendText(`

\u26A0\uFE0F **${chunk.level === "warning" ? "Blocked" : "Notice"}:** ${chunk.content}`);
        break;
      case "error":
        this.flushPendingTools();
        await this.appendText(`

\u274C **Error:** ${chunk.content}`);
        break;
      case "done":
        this.flushPendingTools();
        break;
      case "context_compacted": {
        this.flushPendingTools();
        if (state.currentThinkingState) {
          await this.finalizeCurrentThinkingBlock(msg);
        }
        await this.finalizeCurrentTextBlock(msg);
        msg.contentBlocks = msg.contentBlocks || [];
        msg.contentBlocks.push({ type: "context_compacted" });
        this.renderCompactBoundary();
        break;
      }
      case "usage": {
        const currentSessionId = (_d2 = (_c = (_b2 = (_a3 = this.deps).getAgentService) == null ? void 0 : _b2.call(_a3)) == null ? void 0 : _c.getSessionId()) != null ? _d2 : null;
        const chunkSessionId = (_e = chunk.sessionId) != null ? _e : null;
        if (chunkSessionId && currentSessionId && chunkSessionId !== currentSessionId || chunkSessionId && !currentSessionId) {
          break;
        }
        if (this.deps.subagentManager.subagentsSpawnedThisStream > 0) {
          break;
        }
        if (!state.ignoreUsageUpdates) {
          const activeModel = this.getActiveProviderModel();
          state.usage = activeModel && !chunk.usage.model ? { ...chunk.usage, model: activeModel } : chunk.usage;
        }
        break;
      }
      default:
        break;
    }
    this.scrollToBottom();
  }
  // ============================================
  // Tool Use Handling
  // ============================================
  /**
   * Handles regular tool_use chunks by buffering them.
   * Tools are rendered when flushPendingTools is called (on next content type or tool_result).
   */
  handleRegularToolUse(chunk, msg) {
    var _a3, _b2, _c;
    const { state } = this.deps;
    const existingToolCall = (_a3 = msg.toolCalls) == null ? void 0 : _a3.find((tc) => tc.id === chunk.id);
    if (existingToolCall) {
      const newInput = chunk.input || {};
      if (Object.keys(newInput).length > 0) {
        existingToolCall.input = { ...existingToolCall.input, ...newInput };
        if (existingToolCall.name === TOOL_TODO_WRITE) {
          const todos = parseTodoInput(existingToolCall.input);
          if (todos) {
            this.deps.state.currentTodos = todos;
          }
        }
        if (existingToolCall.name === TOOL_WRITE) {
          this.capturePlanFilePath(existingToolCall.input);
        }
        const toolEl = state.toolCallElements.get(chunk.id);
        if (toolEl) {
          const nameEl = (_b2 = toolEl.querySelector(".claudian-tool-name")) != null ? _b2 : toolEl.querySelector(".claudian-write-edit-name");
          if (nameEl) {
            nameEl.setText(getToolName(existingToolCall.name, existingToolCall.input));
          }
          const summaryEl = (_c = toolEl.querySelector(".claudian-tool-summary")) != null ? _c : toolEl.querySelector(".claudian-write-edit-summary");
          if (summaryEl) {
            summaryEl.setText(getToolSummary(existingToolCall.name, existingToolCall.input));
          }
        }
      }
      return;
    }
    const toolCall = {
      id: chunk.id,
      name: chunk.name,
      input: chunk.input,
      status: "running",
      isExpanded: false
    };
    msg.toolCalls = msg.toolCalls || [];
    msg.toolCalls.push(toolCall);
    msg.contentBlocks = msg.contentBlocks || [];
    msg.contentBlocks.push({ type: "tool_use", toolId: chunk.id });
    if (chunk.name === TOOL_TODO_WRITE) {
      const todos = parseTodoInput(chunk.input);
      if (todos) {
        this.deps.state.currentTodos = todos;
      }
    }
    if (chunk.name === TOOL_WRITE) {
      this.capturePlanFilePath(chunk.input);
    }
    if (state.currentContentEl) {
      state.pendingTools.set(chunk.id, {
        toolCall,
        parentEl: state.currentContentEl
      });
      this.showThinkingIndicator();
    }
  }
  getActiveProviderModel() {
    var _a3, _b2, _c;
    const providerId = (_c = (_b2 = (_a3 = this.deps).getAgentService) == null ? void 0 : _b2.call(_a3)) == null ? void 0 : _c.providerId;
    if (!providerId) {
      return void 0;
    }
    const settings11 = ProviderSettingsCoordinator.getProviderSettingsSnapshot(
      this.deps.plugin.settings,
      providerId
    );
    return typeof settings11.model === "string" ? settings11.model : void 0;
  }
  capturePlanFilePath(input) {
    var _a3, _b2, _c;
    const filePath = input.file_path;
    if (!filePath) return;
    const planPathPrefix = (_c = (_b2 = (_a3 = this.deps).getAgentService) == null ? void 0 : _b2.call(_a3)) == null ? void 0 : _c.getCapabilities().planPathPrefix;
    if (planPathPrefix && filePath.replace(/\\/g, "/").includes(planPathPrefix)) {
      this.deps.state.planFilePath = filePath;
    }
  }
  /**
   * Flushes all pending tool calls by rendering them.
   * Called when a different content type arrives or stream ends.
   */
  flushPendingTools() {
    const { state } = this.deps;
    if (state.pendingTools.size === 0) {
      return;
    }
    for (const toolId of state.pendingTools.keys()) {
      this.renderPendingTool(toolId);
    }
    state.pendingTools.clear();
  }
  /**
   * Renders a single pending tool call and moves it from pending to rendered state.
   */
  renderPendingTool(toolId) {
    const { state } = this.deps;
    const pending = state.pendingTools.get(toolId);
    if (!pending) return;
    const { toolCall, parentEl } = pending;
    if (!parentEl) return;
    if (isWriteEditTool(toolCall.name)) {
      const writeEditState = createWriteEditBlock(parentEl, toolCall);
      state.writeEditStates.set(toolId, writeEditState);
      state.toolCallElements.set(toolId, writeEditState.wrapperEl);
    } else {
      renderToolCall(parentEl, toolCall, state.toolCallElements);
    }
    state.pendingTools.delete(toolId);
  }
  handleToolOutput(chunk, msg) {
    var _a3, _b2;
    const { state } = this.deps;
    if (state.pendingTools.has(chunk.id)) {
      this.renderPendingTool(chunk.id);
    }
    const existingToolCall = (_a3 = msg.toolCalls) == null ? void 0 : _a3.find((tc) => tc.id === chunk.id);
    if (!existingToolCall) {
      return;
    }
    existingToolCall.result = ((_b2 = existingToolCall.result) != null ? _b2 : "") + chunk.content;
    this.scheduleToolOutputRender(chunk.id, existingToolCall);
    this.showThinkingIndicator();
  }
  // ============================================
  // Provider lifecycle subagents (spawn → wait/close)
  // ============================================
  handleProviderSubagentSpawn(chunk, msg, adapter) {
    const { state } = this.deps;
    const toolCall = {
      id: chunk.id,
      name: chunk.name,
      input: chunk.input,
      status: "running",
      isExpanded: false
    };
    msg.toolCalls = msg.toolCalls || [];
    msg.toolCalls.push(toolCall);
    msg.contentBlocks = msg.contentBlocks || [];
    msg.contentBlocks.push({ type: "tool_use", toolId: chunk.id });
    if (state.currentContentEl) {
      this.flushPendingTools();
      const subagentInfo = adapter.buildSubagentInfo(toolCall, msg.toolCalls);
      const subagentState = createSubagentBlock(state.currentContentEl, chunk.id, {
        description: subagentInfo.description,
        prompt: subagentInfo.prompt
      });
      this.lifecycleSubagentStates.set(chunk.id, subagentState);
    }
  }
  handleProviderHiddenSubagentTool(chunk, msg) {
    const toolCall = {
      id: chunk.id,
      name: chunk.name,
      input: chunk.input,
      status: "running",
      isExpanded: false
    };
    msg.toolCalls = msg.toolCalls || [];
    msg.toolCalls.push(toolCall);
  }
  /**
   * Handles tool_result for provider lifecycle subagent tools.
   * Returns true if the result was consumed (caller should return early).
   */
  handleProviderSubagentResult(chunk, msg) {
    var _a3, _b2, _c, _d2;
    const existingToolCall = (_a3 = msg.toolCalls) == null ? void 0 : _a3.find((tc) => tc.id === chunk.id);
    if (!existingToolCall) return false;
    const normalizedContent = this.normalizeToolResultContent(chunk.content);
    const adapter = this.getSubagentLifecycleAdapter(existingToolCall.name);
    if (!adapter) return false;
    if (adapter.isSpawnTool(existingToolCall.name)) {
      existingToolCall.status = chunk.isError ? "error" : "completed";
      existingToolCall.result = normalizedContent;
      const spawnResult = adapter.extractSpawnResult(normalizedContent);
      if (spawnResult.agentId) {
        this.lifecycleAgentIdToSpawnId.set(spawnResult.agentId, chunk.id);
      }
      const subagentInfo = adapter.buildSubagentInfo(existingToolCall, (_b2 = msg.toolCalls) != null ? _b2 : []);
      const subagentState = this.lifecycleSubagentStates.get(chunk.id);
      if (subagentState) {
        subagentState.info.description = subagentInfo.description;
        subagentState.info.prompt = subagentInfo.prompt;
        subagentState.labelEl.setText(
          subagentInfo.description.length > 40 ? subagentInfo.description.substring(0, 40) + "..." : subagentInfo.description
        );
      }
      if (chunk.isError) {
        if (subagentState) {
          finalizeSubagentBlock(subagentState, normalizedContent || "Error", true);
        }
      }
      return true;
    }
    if (adapter.isWaitTool(existingToolCall.name)) {
      existingToolCall.status = chunk.isError ? "error" : "completed";
      existingToolCall.result = normalizedContent;
      for (const spawnId of adapter.resolveSpawnToolIds(
        existingToolCall,
        this.lifecycleAgentIdToSpawnId
      )) {
        const spawnToolCall = (_c = msg.toolCalls) == null ? void 0 : _c.find((tc) => tc.id === spawnId);
        const subagentState = this.lifecycleSubagentStates.get(spawnId);
        if (!spawnToolCall || !subagentState) continue;
        const subagentInfo = adapter.buildSubagentInfo(spawnToolCall, (_d2 = msg.toolCalls) != null ? _d2 : []);
        subagentState.info.description = subagentInfo.description;
        subagentState.info.prompt = subagentInfo.prompt;
        if (subagentInfo.status === "completed" || subagentInfo.status === "error") {
          finalizeSubagentBlock(
            subagentState,
            subagentInfo.result || (subagentInfo.status === "error" ? "Error" : "DONE"),
            subagentInfo.status === "error"
          );
        }
      }
      return true;
    }
    if (adapter.isCloseTool(existingToolCall.name)) {
      existingToolCall.status = chunk.isError ? "error" : "completed";
      existingToolCall.result = normalizedContent;
      return true;
    }
    return false;
  }
  async handleToolResult(chunk, msg) {
    var _a3, _b2;
    const { state, subagentManager } = this.deps;
    const normalizedContent = this.normalizeToolResultContent(chunk.content);
    if (subagentManager.hasPendingTask(chunk.id)) {
      this.renderPendingTaskFromTaskResultViaManager(chunk, msg);
    }
    const subagentState = subagentManager.getSyncSubagent(chunk.id);
    if (subagentState) {
      this.finalizeSubagent(chunk, msg);
      return;
    }
    if (this.handleAsyncTaskToolResult(chunk)) {
      this.showThinkingIndicator();
      return;
    }
    if (await this.handleAgentOutputToolResult(chunk)) {
      this.showThinkingIndicator();
      return;
    }
    if (this.handleProviderSubagentResult(chunk, msg)) {
      this.showThinkingIndicator();
      return;
    }
    if (state.pendingTools.has(chunk.id)) {
      this.renderPendingTool(chunk.id);
    }
    const existingToolCall = (_a3 = msg.toolCalls) == null ? void 0 : _a3.find((tc) => tc.id === chunk.id);
    const isBlocked = isBlockedToolResult(normalizedContent, chunk.isError);
    if (existingToolCall) {
      if (chunk.isError) {
        existingToolCall.status = "error";
      } else if (!skipsBlockedDetection(existingToolCall.name) && isBlocked) {
        existingToolCall.status = "blocked";
      } else {
        existingToolCall.status = "completed";
      }
      existingToolCall.result = normalizedContent;
      if (existingToolCall.name === TOOL_ASK_USER_QUESTION) {
        const answers = (_b2 = extractResolvedAnswers(chunk.toolUseResult)) != null ? _b2 : extractResolvedAnswersFromResultText(normalizedContent);
        if (answers) existingToolCall.resolvedAnswers = answers;
      }
      const writeEditState = state.writeEditStates.get(chunk.id);
      if (writeEditState && isWriteEditTool(existingToolCall.name)) {
        if (!chunk.isError && !isBlocked) {
          const diffData = extractDiffData(chunk.toolUseResult, existingToolCall);
          if (diffData) {
            existingToolCall.diffData = diffData;
            updateWriteEditWithDiff(writeEditState, diffData);
          }
        }
        finalizeWriteEditBlock(writeEditState, chunk.isError || isBlocked);
      } else {
        this.cancelPendingToolOutputRender(chunk.id);
        updateToolCallResult(chunk.id, existingToolCall, state.toolCallElements);
      }
      if (!chunk.isError && !isBlocked && isEditTool(existingToolCall.name)) {
        this.notifyVaultFileChange(existingToolCall.input);
      }
      if (!chunk.isError && !isBlocked && existingToolCall.name === TOOL_APPLY_PATCH) {
        this.notifyApplyPatchFileChanges(existingToolCall.input);
      }
    }
    this.showThinkingIndicator();
  }
  // ============================================
  // Text Block Management
  // ============================================
  async appendText(text) {
    const { state } = this.deps;
    if (!state.currentContentEl) return;
    this.hideThinkingIndicator();
    if (!state.currentTextEl) {
      state.currentTextEl = state.currentContentEl.createDiv({ cls: "claudian-text-block" });
      state.currentTextContent = "";
    }
    state.currentTextContent += text;
    void this.scheduleCurrentTextRender();
  }
  async finalizeCurrentTextBlock(msg) {
    const { state, renderer } = this.deps;
    await this.flushPendingTextRender();
    if (msg && state.currentTextContent) {
      msg.contentBlocks = msg.contentBlocks || [];
      msg.contentBlocks.push({ type: "text", content: state.currentTextContent });
      if (state.currentTextEl) {
        renderer.addTextCopyButton(state.currentTextEl, state.currentTextContent);
      }
    }
    state.currentTextEl = null;
    state.currentTextContent = "";
  }
  scheduleCurrentTextRender() {
    if (!this.pendingTextRenderPromise) {
      this.pendingTextRenderPromise = new Promise((resolve8) => {
        this.resolvePendingTextRender = resolve8;
      });
    }
    if (this.pendingTextRenderFrame === null && !this.isTextRenderRunning) {
      this.pendingTextRenderFrame = scheduleAnimationFrame(() => {
        this.pendingTextRenderFrame = null;
        void this.renderPendingText();
      });
    }
    return this.pendingTextRenderPromise;
  }
  async flushPendingTextRender() {
    const pendingRender = this.pendingTextRenderPromise;
    if (!pendingRender) return;
    if (this.pendingTextRenderFrame !== null) {
      cancelScheduledAnimationFrame(this.pendingTextRenderFrame);
      this.pendingTextRenderFrame = null;
      void this.renderPendingText();
    }
    await pendingRender;
  }
  async renderPendingText() {
    if (this.isTextRenderRunning) return;
    this.isTextRenderRunning = true;
    const { state, renderer } = this.deps;
    const textEl = state.currentTextEl;
    const content = state.currentTextContent;
    try {
      if (textEl) {
        await renderer.renderContent(textEl, content);
        this.scrollToBottom();
      }
    } catch (e2) {
    } finally {
      this.isTextRenderRunning = false;
    }
    if (state.currentTextEl === textEl && state.currentTextContent !== content) {
      this.pendingTextRenderFrame = scheduleAnimationFrame(() => {
        this.pendingTextRenderFrame = null;
        void this.renderPendingText();
      });
      return;
    }
    const resolve8 = this.resolvePendingTextRender;
    this.pendingTextRenderPromise = null;
    this.resolvePendingTextRender = null;
    resolve8 == null ? void 0 : resolve8();
  }
  cancelPendingTextRender() {
    if (this.pendingTextRenderFrame !== null) {
      cancelScheduledAnimationFrame(this.pendingTextRenderFrame);
      this.pendingTextRenderFrame = null;
    }
    const resolve8 = this.resolvePendingTextRender;
    this.pendingTextRenderPromise = null;
    this.resolvePendingTextRender = null;
    resolve8 == null ? void 0 : resolve8();
  }
  scheduleToolOutputRender(toolId, toolCall) {
    if (this.pendingToolOutputFrames.has(toolId)) return;
    const frame = scheduleAnimationFrame(() => {
      this.pendingToolOutputFrames.delete(toolId);
      updateToolCallResult(toolId, toolCall, this.deps.state.toolCallElements);
      this.scrollToBottom();
    });
    this.pendingToolOutputFrames.set(toolId, frame);
  }
  cancelPendingToolOutputRender(toolId) {
    const frame = this.pendingToolOutputFrames.get(toolId);
    if (!frame) return;
    cancelScheduledAnimationFrame(frame);
    this.pendingToolOutputFrames.delete(toolId);
  }
  cancelPendingToolOutputRenders() {
    for (const frame of this.pendingToolOutputFrames.values()) {
      cancelScheduledAnimationFrame(frame);
    }
    this.pendingToolOutputFrames.clear();
  }
  // ============================================
  // Thinking Block Management
  // ============================================
  async appendThinking(content) {
    const { state, renderer } = this.deps;
    if (!state.currentContentEl) return;
    this.hideThinkingIndicator();
    if (!state.currentThinkingState) {
      state.currentThinkingState = createThinkingBlock(
        state.currentContentEl,
        (el, md) => renderer.renderContent(el, md)
      );
    }
    state.currentThinkingState.content += content;
    void this.scheduleCurrentThinkingRender();
  }
  async finalizeCurrentThinkingBlock(msg) {
    const { state } = this.deps;
    if (!state.currentThinkingState) return;
    await this.flushPendingThinkingRender();
    const durationSeconds = finalizeThinkingBlock(state.currentThinkingState);
    if (msg && state.currentThinkingState.content) {
      msg.contentBlocks = msg.contentBlocks || [];
      msg.contentBlocks.push({
        type: "thinking",
        content: state.currentThinkingState.content,
        durationSeconds
      });
    }
    state.currentThinkingState = null;
  }
  scheduleCurrentThinkingRender() {
    if (!this.pendingThinkingRenderPromise) {
      this.pendingThinkingRenderPromise = new Promise((resolve8) => {
        this.resolvePendingThinkingRender = resolve8;
      });
    }
    if (this.pendingThinkingRenderFrame === null && !this.isThinkingRenderRunning) {
      this.pendingThinkingRenderFrame = scheduleAnimationFrame(() => {
        this.pendingThinkingRenderFrame = null;
        void this.renderPendingThinking();
      });
    }
    return this.pendingThinkingRenderPromise;
  }
  async flushPendingThinkingRender() {
    const pendingRender = this.pendingThinkingRenderPromise;
    if (!pendingRender) return;
    if (this.pendingThinkingRenderFrame !== null) {
      cancelScheduledAnimationFrame(this.pendingThinkingRenderFrame);
      this.pendingThinkingRenderFrame = null;
      void this.renderPendingThinking();
    }
    await pendingRender;
  }
  async renderPendingThinking() {
    var _a3;
    if (this.isThinkingRenderRunning) return;
    this.isThinkingRenderRunning = true;
    const { state, renderer } = this.deps;
    const thinkingState = state.currentThinkingState;
    const content = (_a3 = thinkingState == null ? void 0 : thinkingState.content) != null ? _a3 : "";
    try {
      if (thinkingState) {
        await renderer.renderContent(thinkingState.contentEl, content);
        this.scrollToBottom();
      }
    } catch (e2) {
    } finally {
      this.isThinkingRenderRunning = false;
    }
    if (state.currentThinkingState === thinkingState && thinkingState && thinkingState.content !== content) {
      this.pendingThinkingRenderFrame = scheduleAnimationFrame(() => {
        this.pendingThinkingRenderFrame = null;
        void this.renderPendingThinking();
      });
      return;
    }
    const resolve8 = this.resolvePendingThinkingRender;
    this.pendingThinkingRenderPromise = null;
    this.resolvePendingThinkingRender = null;
    resolve8 == null ? void 0 : resolve8();
  }
  cancelPendingThinkingRender() {
    if (this.pendingThinkingRenderFrame !== null) {
      cancelScheduledAnimationFrame(this.pendingThinkingRenderFrame);
      this.pendingThinkingRenderFrame = null;
    }
    const resolve8 = this.resolvePendingThinkingRender;
    this.pendingThinkingRenderPromise = null;
    this.resolvePendingThinkingRender = null;
    resolve8 == null ? void 0 : resolve8();
  }
  // ============================================
  // Subagent Tool Handling (via SubagentManager)
  // ============================================
  /** Delegates Agent tool_use to SubagentManager and updates message based on result. */
  handleTaskToolUseViaManager(chunk, msg) {
    const { state, subagentManager } = this.deps;
    this.ensureTaskToolCall(msg, chunk.id, chunk.input);
    const result = subagentManager.handleTaskToolUse(chunk.id, chunk.input, state.currentContentEl);
    switch (result.action) {
      case "created_sync":
        this.recordSubagentInMessage(msg, result.subagentState.info, chunk.id);
        this.showThinkingIndicator();
        break;
      case "created_async":
        this.recordSubagentInMessage(msg, result.info, chunk.id, "async");
        this.showThinkingIndicator();
        break;
      case "buffered":
        this.showThinkingIndicator();
        break;
      case "label_updated":
        break;
    }
  }
  /** Renders a pending Agent tool call via SubagentManager and updates message. */
  renderPendingTaskViaManager(toolId, msg) {
    const result = this.deps.subagentManager.renderPendingTask(toolId, this.deps.state.currentContentEl);
    if (!result) return;
    if (result.mode === "sync") {
      this.recordSubagentInMessage(msg, result.subagentState.info, toolId);
    } else {
      this.recordSubagentInMessage(msg, result.info, toolId, "async");
    }
  }
  /** Resolves a pending Agent tool call when its own tool_result arrives. */
  renderPendingTaskFromTaskResultViaManager(chunk, msg) {
    const result = this.deps.subagentManager.renderPendingTaskFromTaskResult(
      chunk.id,
      chunk.content,
      chunk.isError || false,
      this.deps.state.currentContentEl,
      chunk.toolUseResult
    );
    if (!result) return;
    if (result.mode === "sync") {
      this.recordSubagentInMessage(msg, result.subagentState.info, chunk.id);
    } else {
      this.recordSubagentInMessage(msg, result.info, chunk.id, "async");
    }
  }
  recordSubagentInMessage(msg, info, toolId, mode) {
    const taskToolCall = this.ensureTaskToolCall(msg, toolId);
    this.applySubagentToTaskToolCall(taskToolCall, info);
    msg.contentBlocks = msg.contentBlocks || [];
    const existingBlock = msg.contentBlocks.find(
      (block) => block.type === "subagent" && block.subagentId === toolId
    );
    if (existingBlock && mode && existingBlock.type === "subagent") {
      existingBlock.mode = mode;
    } else if (!existingBlock) {
      msg.contentBlocks.push(
        mode ? { type: "subagent", subagentId: toolId, mode } : { type: "subagent", subagentId: toolId }
      );
    }
  }
  async handleSubagentChunk(chunk, msg) {
    const parentToolUseId = chunk.subagentId;
    const { subagentManager } = this.deps;
    if (subagentManager.hasPendingTask(parentToolUseId)) {
      this.renderPendingTaskViaManager(parentToolUseId, msg);
    }
    const subagentState = subagentManager.getSyncSubagent(parentToolUseId);
    if (!subagentState) {
      return;
    }
    switch (chunk.type) {
      case "subagent_tool_use": {
        const toolCall = {
          id: chunk.id,
          name: chunk.name,
          input: chunk.input,
          status: "running",
          isExpanded: false
        };
        subagentManager.addSyncToolCall(parentToolUseId, toolCall);
        this.showThinkingIndicator();
        break;
      }
      case "subagent_tool_result": {
        const toolCall = subagentState.info.toolCalls.find((tc) => tc.id === chunk.id);
        if (toolCall) {
          const normalizedContent = this.normalizeToolResultContent(chunk.content);
          const isBlocked = isBlockedToolResult(normalizedContent, chunk.isError);
          toolCall.status = isBlocked ? "blocked" : chunk.isError ? "error" : "completed";
          toolCall.result = normalizedContent;
          subagentManager.updateSyncToolResult(parentToolUseId, chunk.id, toolCall);
        }
        break;
      }
      default:
        break;
    }
  }
  /** Finalizes a sync subagent when its Agent tool_result is received. */
  finalizeSubagent(chunk, msg) {
    var _a3;
    const isError = chunk.isError || false;
    const normalizedContent = this.normalizeToolResultContent(chunk.content);
    const finalized = this.deps.subagentManager.finalizeSyncSubagent(
      chunk.id,
      chunk.content,
      isError,
      chunk.toolUseResult
    );
    const extractedResult = (_a3 = finalized == null ? void 0 : finalized.result) != null ? _a3 : normalizedContent;
    const taskToolCall = this.ensureTaskToolCall(msg, chunk.id);
    taskToolCall.status = isError ? "error" : "completed";
    taskToolCall.result = extractedResult;
    if (taskToolCall.subagent) {
      taskToolCall.subagent.status = isError ? "error" : "completed";
      taskToolCall.subagent.result = extractedResult;
    }
    if (finalized) {
      this.applySubagentToTaskToolCall(taskToolCall, finalized);
    }
    this.showThinkingIndicator();
  }
  // ============================================
  // Async Subagent Handling
  // ============================================
  /** Handles TaskOutput tool_use (invisible, links to async subagent). */
  handleAgentOutputToolUse(chunk, _msg) {
    const toolCall = {
      id: chunk.id,
      name: chunk.name,
      input: chunk.input,
      status: "running",
      isExpanded: false
    };
    this.deps.subagentManager.handleAgentOutputToolUse(toolCall);
    this.showThinkingIndicator();
  }
  handleAsyncTaskToolResult(chunk) {
    const { subagentManager } = this.deps;
    if (!subagentManager.isPendingAsyncTask(chunk.id)) {
      return false;
    }
    subagentManager.handleTaskToolResult(chunk.id, chunk.content, chunk.isError, chunk.toolUseResult);
    return true;
  }
  /** Handles TaskOutput result to finalize async subagent. */
  async handleAgentOutputToolResult(chunk) {
    const { subagentManager } = this.deps;
    const isLinked = subagentManager.isLinkedAgentOutputTool(chunk.id);
    const handled = subagentManager.handleAgentOutputToolResult(
      chunk.id,
      chunk.content,
      chunk.isError || false,
      chunk.toolUseResult
    );
    await this.hydrateAsyncSubagentToolCalls(handled);
    return isLinked || handled !== void 0;
  }
  async hydrateAsyncSubagentToolCalls(subagent) {
    var _a3, _b2, _c;
    if (!subagent) return;
    if (subagent.mode !== "async") return;
    if (!subagent.agentId) return;
    const asyncStatus = (_a3 = subagent.asyncStatus) != null ? _a3 : subagent.status;
    if (asyncStatus !== "completed" && asyncStatus !== "error") return;
    const runtime = (_c = (_b2 = this.deps).getAgentService) == null ? void 0 : _c.call(_b2);
    if (!runtime) return;
    const { hasHydrated, finalResultHydrated } = await this.tryHydrateAsyncSubagent(
      subagent,
      runtime,
      true
    );
    if (hasHydrated) {
      this.deps.subagentManager.refreshAsyncSubagent(subagent);
    }
    if (!finalResultHydrated) {
      this.scheduleAsyncSubagentResultRetry(subagent, runtime, 0);
    }
  }
  async tryHydrateAsyncSubagent(subagent, runtime, hydrateToolCalls) {
    var _a3, _b2, _c, _d2, _e;
    let hasHydrated = false;
    let finalResultHydrated = false;
    if (hydrateToolCalls && !((_a3 = subagent.toolCalls) == null ? void 0 : _a3.length)) {
      const recoveredToolCalls = (_c = await ((_b2 = runtime.loadSubagentToolCalls) == null ? void 0 : _b2.call(
        runtime,
        subagent.agentId || ""
      ))) != null ? _c : [];
      if (recoveredToolCalls.length > 0) {
        subagent.toolCalls = recoveredToolCalls.map((toolCall) => ({
          ...toolCall,
          input: { ...toolCall.input }
        }));
        hasHydrated = true;
      }
    }
    const recoveredFinalResult = (_e = await ((_d2 = runtime.loadSubagentFinalResult) == null ? void 0 : _d2.call(
      runtime,
      subagent.agentId || ""
    ))) != null ? _e : null;
    if (recoveredFinalResult && recoveredFinalResult.trim().length > 0) {
      finalResultHydrated = true;
      if (recoveredFinalResult !== subagent.result) {
        subagent.result = recoveredFinalResult;
        hasHydrated = true;
      }
    }
    return { hasHydrated, finalResultHydrated };
  }
  scheduleAsyncSubagentResultRetry(subagent, runtime, attempt) {
    if (!subagent.agentId) return;
    if (attempt >= _StreamController.ASYNC_SUBAGENT_RESULT_RETRY_DELAYS_MS.length) return;
    const delay = _StreamController.ASYNC_SUBAGENT_RESULT_RETRY_DELAYS_MS[attempt];
    setTimeout(() => {
      void this.retryAsyncSubagentResult(subagent, runtime, attempt);
    }, delay);
  }
  async retryAsyncSubagentResult(subagent, runtime, attempt) {
    var _a3;
    if (!subagent.agentId) return;
    const asyncStatus = (_a3 = subagent.asyncStatus) != null ? _a3 : subagent.status;
    if (asyncStatus !== "completed" && asyncStatus !== "error") return;
    const { hasHydrated, finalResultHydrated } = await this.tryHydrateAsyncSubagent(
      subagent,
      runtime,
      false
    );
    if (hasHydrated) {
      this.deps.subagentManager.refreshAsyncSubagent(subagent);
    }
    if (!finalResultHydrated) {
      this.scheduleAsyncSubagentResultRetry(subagent, runtime, attempt + 1);
    }
  }
  /** Callback from SubagentManager when async state changes. Updates messages only (DOM handled by manager). */
  onAsyncSubagentStateChange(subagent) {
    this.updateSubagentInMessages(subagent);
    this.scrollToBottom();
  }
  updateSubagentInMessages(subagent) {
    const { state } = this.deps;
    for (let i2 = state.messages.length - 1; i2 >= 0; i2--) {
      const msg = state.messages[i2];
      if (msg.role !== "assistant") continue;
      if (this.linkTaskToolCallToSubagent(msg, subagent)) {
        return;
      }
    }
  }
  ensureTaskToolCall(msg, toolId, input) {
    msg.toolCalls = msg.toolCalls || [];
    const existing = msg.toolCalls.find(
      (tc) => tc.id === toolId && isSubagentToolName(tc.name)
    );
    if (existing) {
      if (input && Object.keys(input).length > 0) {
        existing.input = { ...existing.input, ...input };
      }
      return existing;
    }
    const taskToolCall = {
      id: toolId,
      name: TOOL_TASK,
      input: input ? { ...input } : {},
      status: "running",
      isExpanded: false
    };
    msg.toolCalls.push(taskToolCall);
    return taskToolCall;
  }
  applySubagentToTaskToolCall(taskToolCall, subagent) {
    taskToolCall.subagent = subagent;
    if (subagent.status === "completed") taskToolCall.status = "completed";
    else if (subagent.status === "error") taskToolCall.status = "error";
    else taskToolCall.status = "running";
    if (subagent.result !== void 0) {
      taskToolCall.result = subagent.result;
    }
  }
  linkTaskToolCallToSubagent(msg, subagent) {
    var _a3;
    const taskToolCall = (_a3 = msg.toolCalls) == null ? void 0 : _a3.find(
      (tc) => tc.id === subagent.id && isSubagentToolName(tc.name)
    );
    if (!taskToolCall) return false;
    this.applySubagentToTaskToolCall(taskToolCall, subagent);
    return true;
  }
  /**
   * Schedules showing the thinking indicator after a delay.
   * If content arrives before the delay, the indicator won't show.
   * This prevents the indicator from appearing during active streaming.
   * Note: Flavor text is hidden when model thinking block is active (thinking takes priority).
   */
  showThinkingIndicator(overrideText, overrideCls) {
    const { state } = this.deps;
    if (!state.currentContentEl) return;
    if (state.thinkingIndicatorTimeout) {
      clearTimeout(state.thinkingIndicatorTimeout);
      state.thinkingIndicatorTimeout = null;
    }
    if (state.currentThinkingState) {
      return;
    }
    if (state.thinkingEl) {
      state.currentContentEl.appendChild(state.thinkingEl);
      this.deps.updateQueueIndicator();
      return;
    }
    state.thinkingIndicatorTimeout = setTimeout(() => {
      state.thinkingIndicatorTimeout = null;
      if (!state.currentContentEl || state.thinkingEl || state.currentThinkingState) return;
      const cls = overrideCls ? `claudian-thinking ${overrideCls}` : "claudian-thinking";
      state.thinkingEl = state.currentContentEl.createDiv({ cls });
      const text = overrideText || FLAVOR_TEXTS[Math.floor(Math.random() * FLAVOR_TEXTS.length)];
      state.thinkingEl.createSpan({ text });
      const timerSpan = state.thinkingEl.createSpan({ cls: "claudian-thinking-hint" });
      const updateTimer = () => {
        if (!state.responseStartTime) return;
        if (!timerSpan.isConnected) {
          if (state.flavorTimerInterval) {
            clearInterval(state.flavorTimerInterval);
            state.flavorTimerInterval = null;
          }
          return;
        }
        const elapsedSeconds = Math.floor((performance.now() - state.responseStartTime) / 1e3);
        timerSpan.setText(` (esc to interrupt \xB7 ${formatDurationMmSs(elapsedSeconds)})`);
      };
      updateTimer();
      if (state.flavorTimerInterval) {
        clearInterval(state.flavorTimerInterval);
      }
      state.flavorTimerInterval = setInterval(updateTimer, 1e3);
    }, _StreamController.THINKING_INDICATOR_DELAY);
  }
  /** Hides the thinking indicator and cancels any pending show timeout. */
  hideThinkingIndicator() {
    const { state } = this.deps;
    if (state.thinkingIndicatorTimeout) {
      clearTimeout(state.thinkingIndicatorTimeout);
      state.thinkingIndicatorTimeout = null;
    }
    state.clearFlavorTimerInterval();
    if (state.thinkingEl) {
      state.thinkingEl.remove();
      state.thinkingEl = null;
    }
  }
  // ============================================
  // Compact Boundary
  // ============================================
  renderCompactBoundary() {
    const { state } = this.deps;
    if (!state.currentContentEl) return;
    this.hideThinkingIndicator();
    const el = state.currentContentEl.createDiv({ cls: "claudian-compact-boundary" });
    el.createSpan({ cls: "claudian-compact-boundary-label", text: "Conversation compacted" });
  }
  // ============================================
  // Utilities
  // ============================================
  /**
   * Nudges Obsidian's vault after a Write/Edit/NotebookEdit so the file tree
   * refreshes. Direct `fs` writes bypass the Vault API, and macOS + iCloud
   * FSWatcher often misses the event.
   */
  notifyVaultFileChange(input) {
    var _a3;
    const rawPath = (_a3 = input.file_path) != null ? _a3 : input.notebook_path;
    const vaultPath = getVaultPath(this.deps.plugin.app);
    const relativePath = normalizePathForVault(rawPath, vaultPath);
    if (!relativePath || relativePath.startsWith("/")) return;
    setTimeout(() => {
      const { vault } = this.deps.plugin.app;
      const file2 = vault.getAbstractFileByPath(relativePath);
      if (file2 instanceof import_obsidian30.TFile) {
        vault.trigger("modify", file2);
      } else {
        const parentDir = relativePath.includes("/") ? relativePath.substring(0, relativePath.lastIndexOf("/")) : "";
        vault.adapter.list(parentDir).catch(() => {
        });
      }
    }, 200);
  }
  /** Refreshes vault for each file path in an apply_patch changes array or patch text. */
  notifyApplyPatchFileChanges(input) {
    var _a3;
    const notified = /* @__PURE__ */ new Set();
    const changes = input.changes;
    if (Array.isArray(changes)) {
      for (const change of changes) {
        if (change && typeof change === "object" && typeof change.path === "string") {
          notified.add(change.path);
          this.notifyVaultFileChange({ file_path: change.path });
        }
      }
    }
    const patchText = typeof input.patch === "string" ? input.patch : "";
    if (patchText) {
      for (const match of patchText.matchAll(/^\*\*\* (?:Add|Update|Delete) File: (.+)$/gm)) {
        const filePath = (_a3 = match[1]) == null ? void 0 : _a3.trim();
        if (filePath && !notified.has(filePath)) {
          this.notifyVaultFileChange({ file_path: filePath });
        }
      }
    }
  }
  /** Scrolls messages to bottom if auto-scroll is enabled. */
  scrollToBottom() {
    if (this.pendingScrollFrame !== null) return;
    this.pendingScrollFrame = scheduleAnimationFrame(() => {
      this.pendingScrollFrame = null;
      this.applyScrollToBottom();
    });
  }
  applyScrollToBottom() {
    var _a3;
    const { state, plugin } = this.deps;
    if (!((_a3 = plugin.settings.enableAutoScroll) != null ? _a3 : true)) return;
    if (!state.autoScrollEnabled) return;
    const messagesEl = this.deps.getMessagesEl();
    messagesEl.scrollTop = messagesEl.scrollHeight;
  }
  cancelPendingScroll() {
    if (this.pendingScrollFrame === null) return;
    cancelScheduledAnimationFrame(this.pendingScrollFrame);
    this.pendingScrollFrame = null;
  }
  resetStreamingState() {
    const { state } = this.deps;
    this.cancelPendingTextRender();
    this.cancelPendingThinkingRender();
    this.cancelPendingToolOutputRenders();
    this.cancelPendingScroll();
    this.hideThinkingIndicator();
    state.currentContentEl = null;
    state.currentTextEl = null;
    state.currentTextContent = "";
    state.currentThinkingState = null;
    this.deps.subagentManager.resetStreamingState();
    state.pendingTools.clear();
    state.responseStartTime = null;
  }
};
_StreamController.ASYNC_SUBAGENT_RESULT_RETRY_DELAYS_MS = [200, 600, 1500];
// ============================================
// Thinking Indicator
// ============================================
/** Debounce delay before showing thinking indicator (ms). */
_StreamController.THINKING_INDICATOR_DELAY = 400;
var StreamController = _StreamController;

// src/features/chat/rendering/MessageRenderer.ts
var import_obsidian31 = require("obsidian");

// src/utils/fileLink.ts
var WIKILINK_PATTERN_SOURCE = "(?<!!)\\[\\[([^\\]|#^]+)(?:#[^\\]|]+)?(?:\\^[^\\]|]+)?(?:\\|[^\\]]+)?\\]\\]";
function createWikilinkPattern() {
  return new RegExp(WIKILINK_PATTERN_SOURCE, "g");
}
function buildWikilinkMatch(fullMatch, linkPath, index) {
  const pipeIndex = fullMatch.lastIndexOf("|");
  const displayText = pipeIndex > 0 ? fullMatch.slice(pipeIndex + 1, -2) : linkPath;
  return {
    index,
    fullMatch,
    linkPath,
    linkTarget: extractLinkTarget(fullMatch),
    displayText
  };
}
function extractLinkTarget(fullMatch) {
  const inner = fullMatch.slice(2, -2);
  const pipeIndex = inner.indexOf("|");
  return pipeIndex >= 0 ? inner.slice(0, pipeIndex) : inner;
}
function findWikilinks(app, text) {
  const pattern = createWikilinkPattern();
  const matches = [];
  let match;
  while ((match = pattern.exec(text)) !== null) {
    const fullMatch = match[0];
    const linkPath = match[1];
    if (!fileExistsInVault(app, linkPath)) continue;
    matches.push(buildWikilinkMatch(fullMatch, linkPath, match.index));
  }
  return matches.sort((a2, b10) => b10.index - a2.index);
}
function fileExistsInVault(app, linkPath) {
  const file2 = app.metadataCache.getFirstLinkpathDest(linkPath, "");
  if (file2) {
    return true;
  }
  const directFile = app.vault.getFileByPath(linkPath);
  if (directFile) {
    return true;
  }
  if (!linkPath.endsWith(".md")) {
    const withExt = app.vault.getFileByPath(linkPath + ".md");
    if (withExt) {
      return true;
    }
  }
  return false;
}
function extractLinkPathFromTarget(linkTarget) {
  const subpathIndex = linkTarget.search(/[#^]/);
  return subpathIndex >= 0 ? linkTarget.slice(0, subpathIndex) : linkTarget;
}
function createWikilink(linkTarget, displayText) {
  const link = document.createElement("a");
  link.className = "claudian-file-link internal-link";
  link.textContent = displayText;
  link.setAttribute("data-href", linkTarget);
  link.setAttribute("href", linkTarget);
  return link;
}
function repairEmptyInternalLink(app, link) {
  if ((link.textContent || "").trim()) return;
  const linkTarget = link.dataset.href || link.getAttribute("data-href") || link.getAttribute("href");
  if (!linkTarget) return;
  const linkPath = extractLinkPathFromTarget(linkTarget);
  if (!linkPath || !fileExistsInVault(app, linkPath)) return;
  link.classList.add("claudian-file-link");
  if (!link.dataset.href) {
    link.setAttribute("data-href", linkTarget);
  }
  link.textContent = linkTarget;
}
function registerFileLinkHandler(app, container, component) {
  component.registerDomEvent(container, "click", (event) => {
    const target = event.target;
    const link = target.closest(".claudian-file-link, .internal-link");
    if (link) {
      event.preventDefault();
      const linkTarget = link.dataset.href || link.getAttribute("href");
      if (linkTarget) {
        void app.workspace.openLinkText(linkTarget, "", "tab");
      }
    }
  });
}
function buildFragmentWithLinks(text, matches) {
  const fragment = document.createDocumentFragment();
  let currentIndex = text.length;
  for (const { index, fullMatch, linkTarget, displayText } of matches) {
    const endIndex = index + fullMatch.length;
    if (endIndex < currentIndex) {
      fragment.insertBefore(
        document.createTextNode(text.slice(endIndex, currentIndex)),
        fragment.firstChild
      );
    }
    fragment.insertBefore(createWikilink(linkTarget, displayText), fragment.firstChild);
    currentIndex = index;
  }
  if (currentIndex > 0) {
    fragment.insertBefore(
      document.createTextNode(text.slice(0, currentIndex)),
      fragment.firstChild
    );
  }
  return fragment;
}
function processTextNode(app, node) {
  var _a3;
  const text = node.textContent;
  if (!text || !text.includes("[[")) return false;
  const matches = findWikilinks(app, text);
  if (matches.length === 0) return false;
  (_a3 = node.parentNode) == null ? void 0 : _a3.replaceChild(buildFragmentWithLinks(text, matches), node);
  return true;
}
function processFileLinks(app, container) {
  if (!app || !container) return;
  container.querySelectorAll("a.internal-link").forEach((linkEl) => {
    repairEmptyInternalLink(app, linkEl);
  });
  container.querySelectorAll("code").forEach((codeEl) => {
    var _a3;
    if (((_a3 = codeEl.parentElement) == null ? void 0 : _a3.tagName) === "PRE") return;
    const text = codeEl.textContent;
    if (!text || !text.includes("[[")) return;
    const matches = findWikilinks(app, text);
    if (matches.length === 0) return;
    codeEl.textContent = "";
    codeEl.appendChild(buildFragmentWithLinks(text, matches));
  });
  const walker = document.createTreeWalker(
    container,
    NodeFilter.SHOW_TEXT,
    {
      acceptNode(node2) {
        const parent = node2.parentElement;
        if (!parent) return NodeFilter.FILTER_REJECT;
        const tagName = parent.tagName.toUpperCase();
        if (tagName === "PRE" || tagName === "CODE" || tagName === "A") {
          return NodeFilter.FILTER_REJECT;
        }
        if (parent.closest("pre, code, a, .claudian-file-link, .internal-link")) {
          return NodeFilter.FILTER_REJECT;
        }
        return NodeFilter.FILTER_ACCEPT;
      }
    }
  );
  const textNodes = [];
  let node;
  while (node = walker.nextNode()) {
    textNodes.push(node);
  }
  for (const textNode of textNodes) {
    processTextNode(app, textNode);
  }
}

// src/utils/inlineEdit.ts
function normalizeInsertionText(text) {
  return text.replace(/^(?:\r?\n)+|(?:\r?\n)+$/g, "");
}
function escapeHtml(text) {
  return text.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}

// src/utils/imageEmbed.ts
var IMAGE_EXTENSIONS = /* @__PURE__ */ new Set([
  "png",
  "jpg",
  "jpeg",
  "gif",
  "webp",
  "svg",
  "bmp",
  "ico"
]);
var IMAGE_EMBED_PATTERN = /!\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g;
function isImagePath(path24) {
  var _a3;
  const ext = (_a3 = path24.split(".").pop()) == null ? void 0 : _a3.toLowerCase();
  return ext ? IMAGE_EXTENSIONS.has(ext) : false;
}
function resolveImageFile(app, imagePath, mediaFolder) {
  let file2 = app.vault.getFileByPath(imagePath);
  if (file2) return file2;
  if (mediaFolder) {
    const withFolder = `${mediaFolder}/${imagePath}`;
    file2 = app.vault.getFileByPath(withFolder);
    if (file2) return file2;
  }
  const resolved = app.metadataCache.getFirstLinkpathDest(imagePath, "");
  if (resolved) return resolved;
  return null;
}
function buildStyleAttribute(altText) {
  if (!altText) return "";
  const dimMatch = altText.match(/^(\d+)(?:x(\d+))?$/);
  if (!dimMatch) return "";
  const width = dimMatch[1];
  const height = dimMatch[2];
  if (height) {
    return ` style="width: ${width}px; height: ${height}px;"`;
  }
  return ` style="width: ${width}px;"`;
}
function createImageHtml(app, file2, altText) {
  const src = app.vault.getResourcePath(file2);
  const alt = escapeHtml(altText || file2.basename);
  const style = buildStyleAttribute(altText);
  return `<span class="claudian-embedded-image"><img src="${escapeHtml(src)}" alt="${alt}" loading="lazy"${style}></span>`;
}
function createFallbackHtml(wikilink) {
  return `<span class="claudian-embedded-image-fallback">${escapeHtml(wikilink)}</span>`;
}
function replaceImageEmbedsWithHtml(markdown, app, mediaFolder = "") {
  if (!(app == null ? void 0 : app.vault) || !(app == null ? void 0 : app.metadataCache)) {
    return markdown;
  }
  IMAGE_EMBED_PATTERN.lastIndex = 0;
  return markdown.replace(
    IMAGE_EMBED_PATTERN,
    (match, imagePath, altText) => {
      try {
        if (!isImagePath(imagePath)) {
          return match;
        }
        const file2 = resolveImageFile(app, imagePath, mediaFolder);
        if (!file2) {
          return createFallbackHtml(match);
        }
        return createImageHtml(app, file2, altText);
      } catch (e2) {
        return createFallbackHtml(match);
      }
    }
  );
}

// src/features/chat/rendering/MessageRenderer.ts
var _MessageRenderer = class _MessageRenderer {
  constructor(plugin, component, messagesEl, rewindCallback, forkCallback, getCapabilities) {
    this.liveMessageEls = /* @__PURE__ */ new Map();
    this.app = plugin.app;
    this.plugin = plugin;
    this.component = component;
    this.messagesEl = messagesEl;
    this.rewindCallback = rewindCallback;
    this.forkCallback = forkCallback;
    this.getCapabilities = getCapabilities != null ? getCapabilities : (() => ({
      providerId: DEFAULT_CHAT_PROVIDER_ID,
      supportsPersistentRuntime: false,
      supportsNativeHistory: false,
      supportsPlanMode: false,
      supportsRewind: false,
      supportsFork: false,
      supportsProviderCommands: false,
      supportsImageAttachments: false,
      supportsInstructionMode: false,
      supportsMcpTools: false,
      supportsTurnSteer: false,
      reasoningControl: "none"
    }));
    registerFileLinkHandler(this.app, this.messagesEl, this.component);
  }
  /** Sets the messages container element. */
  setMessagesEl(el) {
    this.messagesEl = el;
  }
  getSubagentLifecycleAdapter(toolName) {
    return resolveSubagentLifecycleAdapter(this.getCapabilities().providerId, toolName);
  }
  // ============================================
  // Streaming Message Rendering
  // ============================================
  /**
   * Adds a new message to the chat during streaming.
   * Returns the message element for content updates.
   */
  addMessage(msg) {
    var _a3, _b2;
    if (msg.role === "user" && msg.images && msg.images.length > 0) {
      this.renderMessageImages(this.messagesEl, msg.images);
    }
    if (msg.role === "user") {
      const textToShow = (_a3 = msg.displayContent) != null ? _a3 : msg.content;
      if (!textToShow) {
        this.scrollToBottom();
        const lastChild = this.messagesEl.lastElementChild;
        return lastChild != null ? lastChild : this.messagesEl;
      }
    }
    const msgEl = this.messagesEl.createDiv({
      cls: `claudian-message claudian-message-${msg.role}`,
      attr: {
        "data-message-id": msg.id,
        "data-role": msg.role
      }
    });
    const contentEl = msgEl.createDiv({ cls: "claudian-message-content", attr: { dir: "auto" } });
    if (msg.role === "user") {
      const textToShow = (_b2 = msg.displayContent) != null ? _b2 : msg.content;
      if (textToShow) {
        const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
        void this.renderContent(textEl, textToShow);
        this.addUserCopyButton(msgEl, textToShow);
      }
      if (this.rewindCallback || this.forkCallback) {
        this.liveMessageEls.set(msg.id, msgEl);
      }
    }
    this.scrollToBottom();
    return msgEl;
  }
  updateLiveUserMessage(msg) {
    var _a3, _b2;
    if (msg.role !== "user") {
      return;
    }
    const msgEl = (_a3 = this.liveMessageEls.get(msg.id)) != null ? _a3 : this.messagesEl.querySelector(`[data-message-id="${msg.id}"]`);
    if (!msgEl) {
      return;
    }
    const contentEl = msgEl.querySelector(".claudian-message-content");
    if (!contentEl) {
      return;
    }
    contentEl.empty();
    const textToShow = (_b2 = msg.displayContent) != null ? _b2 : msg.content;
    if (textToShow) {
      const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
      void this.renderContent(textEl, textToShow);
    }
    const toolbar = msgEl.querySelector(".claudian-user-msg-actions");
    if (toolbar) {
      toolbar.querySelectorAll(".claudian-user-msg-copy-btn").forEach((el) => el.remove());
    }
    if (textToShow) {
      this.addUserCopyButton(msgEl, textToShow);
    }
  }
  removeMessage(messageId) {
    var _a3;
    const msgEl = (_a3 = this.liveMessageEls.get(messageId)) != null ? _a3 : this.messagesEl.querySelector(`[data-message-id="${messageId}"]`);
    if (!msgEl) {
      return;
    }
    msgEl.remove();
    this.liveMessageEls.delete(messageId);
  }
  // ============================================
  // Stored Message Rendering (Batch/Replay)
  // ============================================
  /**
   * Renders all messages for conversation load/switch.
   * @param messages Array of messages to render
   * @param getGreeting Function to get greeting text
   * @returns The newly created welcome element
   */
  renderMessages(messages, getGreeting) {
    this.messagesEl.empty();
    this.liveMessageEls.clear();
    const newWelcomeEl = this.messagesEl.createDiv({ cls: "claudian-welcome" });
    newWelcomeEl.createDiv({ cls: "claudian-welcome-greeting", text: getGreeting() });
    for (let i2 = 0; i2 < messages.length; i2++) {
      this.renderStoredMessage(messages[i2], messages, i2);
    }
    this.scrollToBottom();
    return newWelcomeEl;
  }
  renderStoredMessage(msg, allMessages, index) {
    var _a3, _b2;
    if (msg.isInterrupt && (msg.role === "user" || !this.hasVisibleContent(msg))) {
      this.renderInterruptMessage();
      return;
    }
    if (msg.isRebuiltContext) {
      return;
    }
    if (msg.role === "user" && msg.images && msg.images.length > 0) {
      this.renderMessageImages(this.messagesEl, msg.images);
    }
    if (msg.role === "user") {
      const textToShow = (_a3 = msg.displayContent) != null ? _a3 : msg.content;
      if (!textToShow) {
        return;
      }
    }
    const msgEl = this.messagesEl.createDiv({
      cls: `claudian-message claudian-message-${msg.role}`,
      attr: {
        "data-message-id": msg.id,
        "data-role": msg.role
      }
    });
    const contentEl = msgEl.createDiv({ cls: "claudian-message-content", attr: { dir: "auto" } });
    if (msg.role === "user") {
      const textToShow = (_b2 = msg.displayContent) != null ? _b2 : msg.content;
      if (textToShow) {
        const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
        void this.renderContent(textEl, textToShow);
        this.addUserCopyButton(msgEl, textToShow);
      }
      if (msg.userMessageId && this.isRewindEligible(allMessages, index)) {
        if (this.rewindCallback) {
          this.addRewindButton(msgEl, msg.id);
        }
        if (this.forkCallback) {
          this.addForkButton(msgEl, msg.id);
        }
      }
    } else if (msg.role === "assistant") {
      this.renderAssistantContent(msg, contentEl);
      if (msg.isInterrupt) {
        this.appendInterruptIndicator(contentEl);
      }
    }
  }
  hasVisibleContent(msg) {
    if (msg.content && msg.content.trim().length > 0) return true;
    if (msg.toolCalls && msg.toolCalls.length > 0) return true;
    if (msg.contentBlocks && msg.contentBlocks.length > 0) return true;
    return false;
  }
  isRewindEligible(allMessages, index) {
    if (!allMessages || index === void 0) return false;
    const ctx = findRewindContext(allMessages, index);
    return !!ctx.prevAssistantUuid && ctx.hasResponse;
  }
  renderInterruptMessage() {
    const msgEl = this.messagesEl.createDiv({ cls: "claudian-message claudian-message-assistant" });
    const contentEl = msgEl.createDiv({ cls: "claudian-message-content", attr: { dir: "auto" } });
    this.appendInterruptIndicator(contentEl);
  }
  appendInterruptIndicator(contentEl) {
    const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
    textEl.innerHTML = '<span class="claudian-interrupted">Interrupted</span> <span class="claudian-interrupted-hint">\xB7 What should Claudian do instead?</span>';
  }
  /**
   * Renders assistant message content (content blocks or fallback).
   */
  renderAssistantContent(msg, contentEl) {
    var _a3, _b2, _c;
    if (msg.contentBlocks && msg.contentBlocks.length > 0) {
      const renderedToolIds = /* @__PURE__ */ new Set();
      for (const block of msg.contentBlocks) {
        if (block.type === "thinking") {
          renderStoredThinkingBlock(
            contentEl,
            block.content,
            block.durationSeconds,
            (el, md) => this.renderContent(el, md)
          );
        } else if (block.type === "text") {
          if (!block.content || !block.content.trim()) {
            continue;
          }
          const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
          void this.renderContent(textEl, block.content);
          this.addTextCopyButton(textEl, block.content);
        } else if (block.type === "tool_use") {
          const toolCall = (_a3 = msg.toolCalls) == null ? void 0 : _a3.find((tc) => tc.id === block.toolId);
          if (toolCall) {
            this.renderToolCall(contentEl, toolCall, msg);
            renderedToolIds.add(toolCall.id);
          }
        } else if (block.type === "context_compacted") {
          const boundaryEl = contentEl.createDiv({ cls: "claudian-compact-boundary" });
          boundaryEl.createSpan({ cls: "claudian-compact-boundary-label", text: "Conversation compacted" });
        } else if (block.type === "subagent") {
          const taskToolCall = (_b2 = msg.toolCalls) == null ? void 0 : _b2.find(
            (tc) => tc.id === block.subagentId && isSubagentToolName(tc.name)
          );
          if (!taskToolCall) continue;
          this.renderTaskSubagent(contentEl, taskToolCall, block.mode);
          renderedToolIds.add(taskToolCall.id);
        }
      }
      if (msg.toolCalls && msg.toolCalls.length > 0) {
        for (const toolCall of msg.toolCalls) {
          if (renderedToolIds.has(toolCall.id)) continue;
          this.renderToolCall(contentEl, toolCall, msg);
          renderedToolIds.add(toolCall.id);
        }
      }
    } else {
      if (msg.content) {
        const textEl = contentEl.createDiv({ cls: "claudian-text-block" });
        void this.renderContent(textEl, msg.content);
        this.addTextCopyButton(textEl, msg.content);
      }
      if (msg.toolCalls) {
        for (const toolCall of msg.toolCalls) {
          this.renderToolCall(contentEl, toolCall, msg);
        }
      }
    }
    const hasCompactBoundary = (_c = msg.contentBlocks) == null ? void 0 : _c.some((b10) => b10.type === "context_compacted");
    if (msg.durationSeconds && msg.durationSeconds > 0 && !hasCompactBoundary) {
      const flavorWord = msg.durationFlavorWord || "Baked";
      const footerEl = contentEl.createDiv({ cls: "claudian-response-footer" });
      footerEl.createSpan({
        text: `* ${flavorWord} for ${formatDurationMmSs(msg.durationSeconds)}`,
        cls: "claudian-baked-duration"
      });
    }
  }
  /**
   * Renders a tool call with special handling for Write/Edit, Agent (subagent),
   * and Codex collab agent lifecycle tools.
   */
  renderToolCall(contentEl, toolCall, msg) {
    const subagentLifecycleAdapter = this.getSubagentLifecycleAdapter(toolCall.name);
    if (toolCall.name === TOOL_AGENT_OUTPUT) return;
    if (subagentLifecycleAdapter == null ? void 0 : subagentLifecycleAdapter.isHiddenTool(toolCall.name)) return;
    if (isWriteEditTool(toolCall.name)) {
      renderStoredWriteEdit(contentEl, toolCall);
    } else if (isSubagentToolName(toolCall.name)) {
      this.renderTaskSubagent(contentEl, toolCall);
    } else if ((subagentLifecycleAdapter == null ? void 0 : subagentLifecycleAdapter.isSpawnTool(toolCall.name)) && msg) {
      this.renderProviderLifecycleSubagent(contentEl, toolCall, msg);
    } else {
      renderStoredToolCall(contentEl, toolCall);
    }
  }
  renderTaskSubagent(contentEl, toolCall, modeHint) {
    const subagentInfo = this.resolveTaskSubagent(toolCall, modeHint);
    if (subagentInfo.mode === "async") {
      renderStoredAsyncSubagent(contentEl, subagentInfo);
      return;
    }
    renderStoredSubagent(contentEl, subagentInfo);
  }
  /**
   * Consolidates provider lifecycle tools (spawn + wait/close)
   * into a single subagent block with prompt and result.
   */
  renderProviderLifecycleSubagent(contentEl, spawnToolCall, msg) {
    var _a3;
    const subagentLifecycleAdapter = this.getSubagentLifecycleAdapter(spawnToolCall.name);
    if (!subagentLifecycleAdapter) {
      renderStoredToolCall(contentEl, spawnToolCall);
      return;
    }
    const subagentInfo = subagentLifecycleAdapter.buildSubagentInfo(
      spawnToolCall,
      (_a3 = msg.toolCalls) != null ? _a3 : []
    );
    renderStoredSubagent(contentEl, subagentInfo);
  }
  resolveTaskSubagent(toolCall, modeHint) {
    var _a3, _b2, _c;
    if (toolCall.subagent) {
      if (!modeHint || toolCall.subagent.mode === modeHint) {
        return toolCall.subagent;
      }
      return {
        ...toolCall.subagent,
        mode: modeHint
      };
    }
    const description = ((_a3 = toolCall.input) == null ? void 0 : _a3.description) || "Subagent task";
    const prompt = ((_b2 = toolCall.input) == null ? void 0 : _b2.prompt) || "";
    const mode = modeHint != null ? modeHint : ((_c = toolCall.input) == null ? void 0 : _c.run_in_background) === true ? "async" : "sync";
    if (mode !== "async") {
      return {
        id: toolCall.id,
        description,
        prompt,
        status: this.mapToolStatusToSubagentStatus(toolCall.status),
        toolCalls: [],
        isExpanded: false,
        result: toolCall.result
      };
    }
    const asyncStatus = this.inferAsyncStatusFromTaskTool(toolCall);
    return {
      id: toolCall.id,
      description,
      prompt,
      mode: "async",
      status: asyncStatus,
      asyncStatus,
      toolCalls: [],
      isExpanded: false,
      result: toolCall.result
    };
  }
  mapToolStatusToSubagentStatus(status) {
    switch (status) {
      case "completed":
        return "completed";
      case "error":
      case "blocked":
        return "error";
      default:
        return "running";
    }
  }
  inferAsyncStatusFromTaskTool(toolCall) {
    if (toolCall.status === "error" || toolCall.status === "blocked") return "error";
    if (toolCall.status === "running") return "running";
    const lowerResult = extractToolResultContent(toolCall.result, { fallbackIndent: 2 }).toLowerCase();
    if (lowerResult.includes("not_ready") || lowerResult.includes("not ready") || lowerResult.includes('"status":"running"') || lowerResult.includes('"status":"pending"') || lowerResult.includes('"retrieval_status":"running"') || lowerResult.includes('"retrieval_status":"not_ready"')) {
      return "running";
    }
    return "completed";
  }
  // ============================================
  // Image Rendering
  // ============================================
  /**
   * Renders image attachments above a message.
   */
  renderMessageImages(containerEl, images) {
    const imagesEl = containerEl.createDiv({ cls: "claudian-message-images" });
    for (const image of images) {
      const imageWrapper = imagesEl.createDiv({ cls: "claudian-message-image" });
      const imgEl = imageWrapper.createEl("img", {
        attr: {
          alt: image.name
        }
      });
      void this.setImageSrc(imgEl, image);
      imgEl.addEventListener("click", () => {
        void this.showFullImage(image);
      });
    }
  }
  /**
   * Shows full-size image in modal overlay.
   */
  showFullImage(image) {
    const dataUri = `data:${image.mediaType};base64,${image.data}`;
    const overlay = document.body.createDiv({ cls: "claudian-image-modal-overlay" });
    const modal = overlay.createDiv({ cls: "claudian-image-modal" });
    modal.createEl("img", {
      attr: {
        src: dataUri,
        alt: image.name
      }
    });
    const closeBtn = modal.createDiv({ cls: "claudian-image-modal-close" });
    closeBtn.setText("\xD7");
    const handleEsc = (e2) => {
      if (e2.key === "Escape") {
        close();
      }
    };
    const close = () => {
      document.removeEventListener("keydown", handleEsc);
      overlay.remove();
    };
    closeBtn.addEventListener("click", close);
    overlay.addEventListener("click", (e2) => {
      if (e2.target === overlay) close();
    });
    document.addEventListener("keydown", handleEsc);
  }
  /**
   * Sets image src from attachment data.
   */
  setImageSrc(imgEl, image) {
    const dataUri = `data:${image.mediaType};base64,${image.data}`;
    imgEl.setAttribute("src", dataUri);
  }
  // ============================================
  // Content Rendering
  // ============================================
  /**
   * Renders markdown content with code block enhancements.
   */
  async renderContent(el, markdown) {
    el.empty();
    try {
      const processedMarkdown = replaceImageEmbedsWithHtml(
        markdown,
        this.app,
        this.plugin.settings.mediaFolder
      );
      await import_obsidian31.MarkdownRenderer.renderMarkdown(
        processedMarkdown,
        el,
        "",
        this.component
      );
      el.querySelectorAll("pre").forEach((pre) => {
        var _a3, _b2;
        if ((_a3 = pre.parentElement) == null ? void 0 : _a3.classList.contains("claudian-code-wrapper")) return;
        const wrapper = createEl("div", { cls: "claudian-code-wrapper" });
        (_b2 = pre.parentElement) == null ? void 0 : _b2.insertBefore(wrapper, pre);
        wrapper.appendChild(pre);
        const code = pre.querySelector('code[class*="language-"]');
        if (code) {
          const match = code.className.match(/language-(\w+)/);
          if (match) {
            wrapper.classList.add("has-language");
            const label = createEl("span", {
              cls: "claudian-code-lang-label",
              text: match[1]
            });
            wrapper.appendChild(label);
            label.addEventListener("click", async () => {
              try {
                await navigator.clipboard.writeText(code.textContent || "");
                label.setText("copied!");
                setTimeout(() => label.setText(match[1]), 1500);
              } catch (e2) {
              }
            });
          }
        }
        const copyBtn = pre.querySelector(".copy-code-button");
        if (copyBtn) {
          wrapper.appendChild(copyBtn);
        }
      });
      if (processedMarkdown.includes("[[")) {
        processFileLinks(this.app, el);
      }
    } catch (e2) {
      el.createDiv({
        cls: "claudian-render-error",
        text: "Failed to render message content."
      });
    }
  }
  /**
   * Adds a copy button to a text block.
   * Button shows clipboard icon on hover, changes to "copied!" on click.
   * @param textEl The rendered text element
   * @param markdown The original markdown content to copy
   */
  addTextCopyButton(textEl, markdown) {
    const copyBtn = textEl.createSpan({ cls: "claudian-text-copy-btn" });
    copyBtn.innerHTML = _MessageRenderer.COPY_ICON;
    let feedbackTimeout = null;
    copyBtn.addEventListener("click", async (e2) => {
      e2.stopPropagation();
      try {
        await navigator.clipboard.writeText(markdown);
      } catch (e4) {
        return;
      }
      if (feedbackTimeout) {
        clearTimeout(feedbackTimeout);
      }
      copyBtn.innerHTML = "";
      copyBtn.setText("copied!");
      copyBtn.classList.add("copied");
      feedbackTimeout = setTimeout(() => {
        copyBtn.innerHTML = _MessageRenderer.COPY_ICON;
        copyBtn.classList.remove("copied");
        feedbackTimeout = null;
      }, 1500);
    });
  }
  refreshActionButtons(msg, allMessages, index) {
    if (!msg.userMessageId) return;
    if (!this.isRewindEligible(allMessages, index)) return;
    const msgEl = this.liveMessageEls.get(msg.id);
    if (!msgEl) return;
    if (this.rewindCallback && !msgEl.querySelector(".claudian-message-rewind-btn")) {
      this.addRewindButton(msgEl, msg.id);
    }
    if (this.forkCallback && !msgEl.querySelector(".claudian-message-fork-btn")) {
      this.addForkButton(msgEl, msg.id);
    }
    this.cleanupLiveMessageEl(msg.id, msgEl);
  }
  cleanupLiveMessageEl(msgId, msgEl) {
    const needsRewind = this.rewindCallback && !msgEl.querySelector(".claudian-message-rewind-btn");
    const needsFork = this.forkCallback && !msgEl.querySelector(".claudian-message-fork-btn");
    if (!needsRewind && !needsFork) {
      this.liveMessageEls.delete(msgId);
    }
  }
  getOrCreateActionsToolbar(msgEl) {
    const existing = msgEl.querySelector(".claudian-user-msg-actions");
    if (existing) return existing;
    return msgEl.createDiv({ cls: "claudian-user-msg-actions" });
  }
  addUserCopyButton(msgEl, content) {
    const toolbar = this.getOrCreateActionsToolbar(msgEl);
    const copyBtn = toolbar.createSpan({ cls: "claudian-user-msg-copy-btn" });
    copyBtn.innerHTML = _MessageRenderer.COPY_ICON;
    copyBtn.setAttribute("aria-label", "Copy message");
    let feedbackTimeout = null;
    copyBtn.addEventListener("click", async (e2) => {
      e2.stopPropagation();
      try {
        await navigator.clipboard.writeText(content);
      } catch (e4) {
        return;
      }
      if (feedbackTimeout) clearTimeout(feedbackTimeout);
      copyBtn.innerHTML = "";
      copyBtn.setText("copied!");
      copyBtn.classList.add("copied");
      feedbackTimeout = setTimeout(() => {
        copyBtn.innerHTML = _MessageRenderer.COPY_ICON;
        copyBtn.classList.remove("copied");
        feedbackTimeout = null;
      }, 1500);
    });
  }
  addRewindButton(msgEl, messageId) {
    if (!this.getCapabilities().supportsRewind) return;
    const toolbar = this.getOrCreateActionsToolbar(msgEl);
    const btn = toolbar.createSpan({ cls: "claudian-message-rewind-btn" });
    if (toolbar.firstChild !== btn) toolbar.insertBefore(btn, toolbar.firstChild);
    btn.innerHTML = _MessageRenderer.REWIND_ICON;
    btn.setAttribute("aria-label", t("chat.rewind.ariaLabel"));
    btn.addEventListener("click", async (e2) => {
      var _a3;
      e2.stopPropagation();
      try {
        await ((_a3 = this.rewindCallback) == null ? void 0 : _a3.call(this, messageId));
      } catch (err) {
        new import_obsidian31.Notice(t("chat.rewind.failed", { error: err instanceof Error ? err.message : "Unknown error" }));
      }
    });
  }
  addForkButton(msgEl, messageId) {
    if (!this.getCapabilities().supportsFork) return;
    const toolbar = this.getOrCreateActionsToolbar(msgEl);
    const btn = toolbar.createSpan({ cls: "claudian-message-fork-btn" });
    if (toolbar.firstChild !== btn) toolbar.insertBefore(btn, toolbar.firstChild);
    btn.innerHTML = _MessageRenderer.FORK_ICON;
    btn.setAttribute("aria-label", t("chat.fork.ariaLabel"));
    btn.addEventListener("click", async (e2) => {
      var _a3;
      e2.stopPropagation();
      try {
        await ((_a3 = this.forkCallback) == null ? void 0 : _a3.call(this, messageId));
      } catch (err) {
        new import_obsidian31.Notice(t("chat.fork.failed", { error: err instanceof Error ? err.message : "Unknown error" }));
      }
    });
  }
  // ============================================
  // Utilities
  // ============================================
  /** Scrolls messages container to bottom. */
  scrollToBottom() {
    this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
  }
  /** Scrolls to bottom if already near bottom (within threshold). */
  scrollToBottomIfNeeded(threshold = 100) {
    const { scrollTop, scrollHeight, clientHeight } = this.messagesEl;
    const isNearBottom = scrollHeight - scrollTop - clientHeight < threshold;
    if (isNearBottom) {
      requestAnimationFrame(() => {
        this.messagesEl.scrollTop = this.messagesEl.scrollHeight;
      });
    }
  }
};
_MessageRenderer.REWIND_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/></svg>`;
_MessageRenderer.FORK_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="18" r="3"/><circle cx="6" cy="6" r="3"/><circle cx="18" cy="6" r="3"/><path d="M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9"/><path d="M12 12v3"/></svg>`;
// ============================================
// Copy Button
// ============================================
/** Clipboard icon SVG for copy button. */
_MessageRenderer.COPY_ICON = `<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path></svg>`;
var MessageRenderer = _MessageRenderer;

// src/features/chat/services/BangBashService.ts
var import_child_process7 = require("child_process");
var TIMEOUT_MS = 3e4;
var MAX_BUFFER = 1024 * 1024;
var BangBashService = class {
  constructor(cwd, enhancedPath) {
    this.cwd = cwd;
    this.enhancedPath = enhancedPath;
  }
  execute(command) {
    return new Promise((resolve8) => {
      (0, import_child_process7.exec)(command, {
        cwd: this.cwd,
        env: { ...process.env, PATH: this.enhancedPath },
        timeout: TIMEOUT_MS,
        maxBuffer: MAX_BUFFER,
        shell: process.platform === "win32" ? "cmd.exe" : "/bin/bash"
      }, (error48, stdout, stderr) => {
        if (error48 && "killed" in error48 && error48.killed) {
          const isMaxBuffer = "code" in error48 && error48.code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
          resolve8({
            command,
            stdout: stdout != null ? stdout : "",
            stderr: stderr != null ? stderr : "",
            exitCode: 124,
            error: isMaxBuffer ? "Output exceeded maximum buffer size (1MB)" : `Command timed out after ${TIMEOUT_MS / 1e3}s`
          });
          return;
        }
        resolve8({
          command,
          stdout: stdout != null ? stdout : "",
          stderr: stderr != null ? stderr : "",
          exitCode: typeof (error48 == null ? void 0 : error48.code) === "number" ? error48.code : error48 ? 1 : 0
        });
      });
    });
  }
};

// src/features/chat/services/SubagentManager.ts
var import_fs6 = require("fs");
var import_os4 = require("os");
var import_path29 = require("path");
var _SubagentManager = class _SubagentManager {
  constructor(onStateChange, taskResultInterpreter = ProviderRegistry.getTaskResultInterpreter()) {
    this.syncSubagents = /* @__PURE__ */ new Map();
    this.pendingTasks = /* @__PURE__ */ new Map();
    this._spawnedThisStream = 0;
    this.activeAsyncSubagents = /* @__PURE__ */ new Map();
    this.pendingAsyncSubagents = /* @__PURE__ */ new Map();
    this.taskIdToAgentId = /* @__PURE__ */ new Map();
    this.outputToolIdToAgentId = /* @__PURE__ */ new Map();
    this.asyncDomStates = /* @__PURE__ */ new Map();
    this.onStateChange = onStateChange;
    this.taskResultInterpreter = taskResultInterpreter;
  }
  setCallback(callback) {
    this.onStateChange = callback;
  }
  setTaskResultInterpreter(interpreter) {
    this.taskResultInterpreter = interpreter;
  }
  // ============================================
  // Unified Subagent Entry Point
  // ============================================
  /**
   * Handles an Agent tool_use chunk with minimal buffering to determine sync vs async.
   * Returns a typed result so StreamController can update messages accordingly.
   */
  handleTaskToolUse(taskToolId, taskInput, currentContentEl) {
    const existingSyncState = this.syncSubagents.get(taskToolId);
    if (existingSyncState) {
      this.updateSubagentLabel(existingSyncState.wrapperEl, existingSyncState.info, taskInput);
      return { action: "label_updated" };
    }
    const existingAsyncState = this.asyncDomStates.get(taskToolId);
    if (existingAsyncState) {
      this.updateSubagentLabel(existingAsyncState.wrapperEl, existingAsyncState.info, taskInput);
      const canonical = this.getByTaskId(taskToolId);
      if (canonical && canonical !== existingAsyncState.info) {
        if (taskInput.description) canonical.description = taskInput.description;
        if (taskInput.prompt) canonical.prompt = taskInput.prompt;
      }
      return { action: "label_updated" };
    }
    const pending = this.pendingTasks.get(taskToolId);
    if (pending) {
      const newInput = taskInput || {};
      if (Object.keys(newInput).length > 0) {
        pending.toolCall.input = { ...pending.toolCall.input, ...newInput };
      }
      if (currentContentEl) {
        pending.parentEl = currentContentEl;
      }
      if (this.resolveTaskMode(pending.toolCall.input)) {
        const result = this.renderPendingTask(taskToolId, currentContentEl);
        if (result) {
          return result.mode === "sync" ? { action: "created_sync", subagentState: result.subagentState } : { action: "created_async", info: result.info, domState: result.domState };
        }
      }
      return { action: "buffered" };
    }
    if (!currentContentEl) {
      const toolCall = {
        id: taskToolId,
        name: TOOL_TASK,
        input: taskInput || {},
        status: "running",
        isExpanded: false
      };
      this.pendingTasks.set(taskToolId, { toolCall, parentEl: null });
      return { action: "buffered" };
    }
    const mode = this.resolveTaskMode(taskInput);
    if (!mode) {
      const toolCall = {
        id: taskToolId,
        name: TOOL_TASK,
        input: taskInput || {},
        status: "running",
        isExpanded: false
      };
      this.pendingTasks.set(taskToolId, { toolCall, parentEl: currentContentEl });
      return { action: "buffered" };
    }
    this._spawnedThisStream++;
    if (mode === "async") {
      return this.createAsyncTask(taskToolId, taskInput, currentContentEl);
    }
    return this.createSyncTask(taskToolId, taskInput, currentContentEl);
  }
  // ============================================
  // Pending Task Resolution
  // ============================================
  hasPendingTask(toolId) {
    return this.pendingTasks.has(toolId);
  }
  /**
   * Renders a buffered pending task. Called when a child chunk or tool_result
   * confirms the task is sync, or when run_in_background becomes known.
   * Uses the optional parentEl override, falling back to the stored parentEl.
   */
  renderPendingTask(toolId, parentElOverride) {
    const pending = this.pendingTasks.get(toolId);
    if (!pending) return null;
    const input = pending.toolCall.input;
    const targetEl = parentElOverride != null ? parentElOverride : pending.parentEl;
    if (!targetEl) return null;
    this.pendingTasks.delete(toolId);
    try {
      if (input.run_in_background === true) {
        const result = this.createAsyncTask(pending.toolCall.id, input, targetEl);
        if (result.action === "created_async") {
          this._spawnedThisStream++;
          return { mode: "async", info: result.info, domState: result.domState };
        }
      } else {
        const result = this.createSyncTask(pending.toolCall.id, input, targetEl);
        if (result.action === "created_sync") {
          this._spawnedThisStream++;
          return { mode: "sync", subagentState: result.subagentState };
        }
      }
    } catch (e2) {
    }
    return null;
  }
  /**
   * Resolves a pending Task when its own tool_result arrives.
   * If mode is still unknown, infer async from task result shape (agent_id/agentId),
   * otherwise fall back to sync so it never remains pending indefinitely.
   */
  renderPendingTaskFromTaskResult(toolId, taskResult, isError, parentElOverride, taskToolUseResult) {
    const pending = this.pendingTasks.get(toolId);
    if (!pending) return null;
    const input = pending.toolCall.input;
    const targetEl = parentElOverride != null ? parentElOverride : pending.parentEl;
    if (!targetEl) return null;
    const explicitMode = this.resolveTaskMode(input);
    const taskResultText = extractToolResultContent(taskResult, { fallbackIndent: 2 });
    const inferredMode = explicitMode != null ? explicitMode : this.inferModeFromTaskResult(taskResultText, isError, taskToolUseResult);
    this.pendingTasks.delete(toolId);
    try {
      if (inferredMode === "async") {
        const result = this.createAsyncTask(pending.toolCall.id, input, targetEl);
        if (result.action === "created_async") {
          this._spawnedThisStream++;
          return { mode: "async", info: result.info, domState: result.domState };
        }
      } else {
        const result = this.createSyncTask(pending.toolCall.id, input, targetEl);
        if (result.action === "created_sync") {
          this._spawnedThisStream++;
          return { mode: "sync", subagentState: result.subagentState };
        }
      }
    } catch (e2) {
    }
    return null;
  }
  // ============================================
  // Sync Subagent Operations
  // ============================================
  getSyncSubagent(toolId) {
    return this.syncSubagents.get(toolId);
  }
  addSyncToolCall(parentToolUseId, toolCall) {
    const subagentState = this.syncSubagents.get(parentToolUseId);
    if (!subagentState) return;
    addSubagentToolCall(subagentState, toolCall);
  }
  updateSyncToolResult(parentToolUseId, toolId, toolCall) {
    const subagentState = this.syncSubagents.get(parentToolUseId);
    if (!subagentState) return;
    updateSubagentToolResult(subagentState, toolId, toolCall);
  }
  finalizeSyncSubagent(toolId, result, isError, toolUseResult) {
    const subagentState = this.syncSubagents.get(toolId);
    if (!subagentState) return null;
    const resultText = extractToolResultContent(result, { fallbackIndent: 2 });
    const extractedResult = this.extractAgentResult(resultText, "", toolUseResult);
    finalizeSubagentBlock(subagentState, extractedResult, isError);
    this.syncSubagents.delete(toolId);
    return subagentState.info;
  }
  // ============================================
  // Async Subagent Lifecycle
  // ============================================
  handleTaskToolResult(taskToolId, result, isError, toolUseResult) {
    var _a3;
    const subagent = this.pendingAsyncSubagents.get(taskToolId);
    if (!subagent) return;
    const resultText = extractToolResultContent(result, { fallbackIndent: 2 });
    if (isError) {
      this.transitionToError(subagent, taskToolId, resultText || "Task failed to start");
      return;
    }
    const agentId = (_a3 = this.taskResultInterpreter.extractAgentId(toolUseResult)) != null ? _a3 : this.parseAgentId(resultText);
    if (!agentId) {
      const truncatedResult = resultText.length > 100 ? resultText.substring(0, 100) + "..." : resultText;
      this.transitionToError(subagent, taskToolId, `Failed to parse agent_id. Result: ${truncatedResult}`);
      return;
    }
    subagent.asyncStatus = "running";
    subagent.agentId = agentId;
    subagent.startedAt = Date.now();
    this.pendingAsyncSubagents.delete(taskToolId);
    this.activeAsyncSubagents.set(agentId, subagent);
    this.taskIdToAgentId.set(taskToolId, agentId);
    this.updateAsyncDomState(subagent);
    this.onStateChange(subagent);
  }
  handleAgentOutputToolUse(toolCall) {
    const agentId = this.extractAgentIdFromInput(toolCall.input);
    if (!agentId) return;
    const subagent = this.activeAsyncSubagents.get(agentId);
    if (!subagent) return;
    subagent.outputToolId = toolCall.id;
    this.outputToolIdToAgentId.set(toolCall.id, agentId);
  }
  handleAgentOutputToolResult(toolId, result, isError, toolUseResult) {
    const resultText = extractToolResultContent(result, { fallbackIndent: 2 });
    let agentId = this.outputToolIdToAgentId.get(toolId);
    let subagent = agentId ? this.activeAsyncSubagents.get(agentId) : void 0;
    if (!subagent) {
      const inferredAgentId = this.inferAgentIdFromResult(resultText);
      if (inferredAgentId) {
        agentId = inferredAgentId;
        subagent = this.activeAsyncSubagents.get(inferredAgentId);
      }
    }
    if (!subagent) return void 0;
    if (agentId) {
      subagent.agentId = subagent.agentId || agentId;
      this.outputToolIdToAgentId.set(toolId, agentId);
    }
    if (subagent.asyncStatus !== "running") {
      return void 0;
    }
    const stillRunning = this.isStillRunningResult(resultText, isError);
    if (stillRunning) {
      this.outputToolIdToAgentId.delete(toolId);
      return subagent;
    }
    const extractedResult = this.extractAgentResult(resultText, agentId != null ? agentId : "", toolUseResult);
    const finalStatus = this.taskResultInterpreter.resolveTerminalStatus(
      toolUseResult,
      isError ? "error" : "completed"
    );
    subagent.asyncStatus = finalStatus;
    subagent.status = finalStatus;
    subagent.result = extractedResult;
    subagent.completedAt = Date.now();
    if (agentId) this.activeAsyncSubagents.delete(agentId);
    this.outputToolIdToAgentId.delete(toolId);
    this.updateAsyncDomState(subagent);
    this.onStateChange(subagent);
    return subagent;
  }
  isPendingAsyncTask(taskToolId) {
    return this.pendingAsyncSubagents.has(taskToolId);
  }
  isLinkedAgentOutputTool(toolId) {
    return this.outputToolIdToAgentId.has(toolId);
  }
  getByTaskId(taskToolId) {
    const pending = this.pendingAsyncSubagents.get(taskToolId);
    if (pending) return pending;
    const agentId = this.taskIdToAgentId.get(taskToolId);
    if (agentId) {
      return this.activeAsyncSubagents.get(agentId);
    }
    return void 0;
  }
  /**
   * Re-renders an async subagent after data-only updates (for example,
   * hydrating tool calls from SDK sidecar files) without changing lifecycle state.
   */
  refreshAsyncSubagent(subagent) {
    this.updateAsyncDomState(subagent);
    this.onStateChange(subagent);
  }
  // ============================================
  // Hook State
  // ============================================
  hasRunningSubagents() {
    return this.pendingAsyncSubagents.size > 0 || this.activeAsyncSubagents.size > 0;
  }
  // ============================================
  // Lifecycle
  // ============================================
  get subagentsSpawnedThisStream() {
    return this._spawnedThisStream;
  }
  resetSpawnedCount() {
    this._spawnedThisStream = 0;
  }
  resetStreamingState() {
    this.syncSubagents.clear();
    this.pendingTasks.clear();
  }
  orphanAllActive() {
    const orphaned = [];
    for (const subagent of this.pendingAsyncSubagents.values()) {
      this.markOrphaned(subagent);
      orphaned.push(subagent);
    }
    for (const subagent of this.activeAsyncSubagents.values()) {
      if (subagent.asyncStatus === "running") {
        this.markOrphaned(subagent);
        orphaned.push(subagent);
      }
    }
    this.pendingAsyncSubagents.clear();
    this.activeAsyncSubagents.clear();
    this.taskIdToAgentId.clear();
    this.outputToolIdToAgentId.clear();
    return orphaned;
  }
  clear() {
    this.syncSubagents.clear();
    this.pendingTasks.clear();
    this.pendingAsyncSubagents.clear();
    this.activeAsyncSubagents.clear();
    this.taskIdToAgentId.clear();
    this.outputToolIdToAgentId.clear();
    this.asyncDomStates.clear();
  }
  // ============================================
  // Private: State Transitions
  // ============================================
  markOrphaned(subagent) {
    subagent.asyncStatus = "orphaned";
    subagent.status = "error";
    subagent.result = "Conversation ended before task completed";
    subagent.completedAt = Date.now();
    this.updateAsyncDomState(subagent);
    this.onStateChange(subagent);
  }
  transitionToError(subagent, taskToolId, errorResult) {
    subagent.asyncStatus = "error";
    subagent.status = "error";
    subagent.result = errorResult;
    subagent.completedAt = Date.now();
    this.pendingAsyncSubagents.delete(taskToolId);
    this.updateAsyncDomState(subagent);
    this.onStateChange(subagent);
  }
  // ============================================
  // Private: Task Creation
  // ============================================
  createSyncTask(taskToolId, taskInput, parentEl) {
    const subagentState = createSubagentBlock(parentEl, taskToolId, taskInput);
    this.syncSubagents.set(taskToolId, subagentState);
    return { action: "created_sync", subagentState };
  }
  createAsyncTask(taskToolId, taskInput, parentEl) {
    const description = taskInput.description || "Background task";
    const prompt = taskInput.prompt || "";
    const info = {
      id: taskToolId,
      description,
      prompt,
      mode: "async",
      isExpanded: false,
      status: "running",
      toolCalls: [],
      asyncStatus: "pending"
    };
    this.pendingAsyncSubagents.set(taskToolId, info);
    const domState = createAsyncSubagentBlock(parentEl, taskToolId, taskInput);
    this.asyncDomStates.set(taskToolId, domState);
    return { action: "created_async", info, domState };
  }
  // ============================================
  // Private: Label Update
  // ============================================
  updateSubagentLabel(wrapperEl, info, newInput) {
    if (!newInput || Object.keys(newInput).length === 0) return;
    const description = newInput.description || "";
    if (description) {
      info.description = description;
      const labelEl = wrapperEl.querySelector(".claudian-subagent-label");
      if (labelEl) {
        const truncated = description.length > 40 ? description.substring(0, 40) + "..." : description;
        labelEl.setText(truncated);
      }
    }
    const prompt = newInput.prompt || "";
    if (prompt) {
      info.prompt = prompt;
      const promptEl = wrapperEl.querySelector(".claudian-subagent-prompt-text");
      if (promptEl) {
        promptEl.setText(prompt);
      }
    }
  }
  resolveTaskMode(taskInput) {
    if (!Object.prototype.hasOwnProperty.call(taskInput, "run_in_background")) {
      return null;
    }
    if (taskInput.run_in_background === true) {
      return "async";
    }
    if (taskInput.run_in_background === false) {
      return "sync";
    }
    return null;
  }
  inferModeFromTaskResult(taskResult, isError, taskToolUseResult) {
    if (isError) {
      return "sync";
    }
    if (this.taskResultInterpreter.hasAsyncLaunchMarker(taskToolUseResult)) {
      return "async";
    }
    return this.parseAgentIdStrict(taskResult) ? "async" : "sync";
  }
  parseAgentIdStrict(result) {
    var _a3, _b2;
    const payload = this.unwrapTextPayload(result).trim();
    if (!payload) {
      return null;
    }
    try {
      const parsed = JSON.parse(payload);
      if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
        return null;
      }
      if (this.hasTerminalTaskStatus(parsed)) {
        return null;
      }
      const directAgentId = this.extractAgentIdFromRecord(parsed);
      if (directAgentId) {
        return directAgentId;
      }
      const taskRecord = parsed.task;
      if (taskRecord && typeof taskRecord === "object" && !Array.isArray(taskRecord)) {
        return this.extractAgentIdFromRecord(taskRecord);
      }
    } catch (e2) {
    }
    const xmlStatus = (_a3 = this.taskResultInterpreter.extractTagValue(payload, "retrieval_status")) != null ? _a3 : this.taskResultInterpreter.extractTagValue(payload, "status");
    if (this.isTerminalTaskStatusValue(xmlStatus)) {
      return null;
    }
    const exactLineMatch = payload.match(/^\s*(?:agent_id|agentId)\s*[=:]\s*"?([a-zA-Z0-9_-]+)"?\s*$/i);
    return (_b2 = exactLineMatch == null ? void 0 : exactLineMatch[1]) != null ? _b2 : null;
  }
  hasTerminalTaskStatus(value) {
    var _a3;
    if (!value || typeof value !== "object" || Array.isArray(value)) {
      return false;
    }
    const record2 = value;
    const rawStatus = (_a3 = record2.retrieval_status) != null ? _a3 : record2.status;
    return this.isTerminalTaskStatusValue(rawStatus);
  }
  isTerminalTaskStatusValue(rawStatus) {
    if (typeof rawStatus !== "string") {
      return false;
    }
    const normalized = rawStatus.toLowerCase();
    return normalized === "completed" || normalized === "success" || normalized === "error";
  }
  extractAgentIdFromRecord(record2) {
    var _a3, _b2;
    const direct = (_a3 = record2.agent_id) != null ? _a3 : record2.agentId;
    if (typeof direct === "string" && direct.length > 0) {
      return direct;
    }
    const data = record2.data;
    if (!data || typeof data !== "object" || Array.isArray(data)) {
      return null;
    }
    const nested = (_b2 = data.agent_id) != null ? _b2 : data.agentId;
    return typeof nested === "string" && nested.length > 0 ? nested : null;
  }
  extractAgentIdFromString(value) {
    const regexPatterns = [
      /"agent_id"\s*:\s*"([^"]+)"/,
      /"agentId"\s*:\s*"([^"]+)"/,
      /agent_id[=:]\s*"?([a-zA-Z0-9_-]+)"?/i,
      /agentId[=:]\s*"?([a-zA-Z0-9_-]+)"?/i
    ];
    for (const pattern of regexPatterns) {
      const match = value.match(pattern);
      if (match && match[1]) {
        return match[1];
      }
    }
    return null;
  }
  // ============================================
  // Private: Async DOM State Updates
  // ============================================
  updateAsyncDomState(subagent) {
    let asyncState = this.asyncDomStates.get(subagent.id);
    if (!asyncState) {
      for (const s4 of this.asyncDomStates.values()) {
        if (s4.info.agentId === subagent.agentId) {
          asyncState = s4;
          break;
        }
      }
      if (!asyncState) return;
    }
    asyncState.info = subagent;
    switch (subagent.asyncStatus) {
      case "running":
        updateAsyncSubagentRunning(asyncState, subagent.agentId || "");
        break;
      case "completed":
      case "error":
        finalizeAsyncSubagent(asyncState, subagent.result || "", subagent.asyncStatus === "error");
        break;
      case "orphaned":
        markAsyncSubagentOrphaned(asyncState);
        break;
    }
  }
  // ============================================
  // Private: Async Parsing Logic
  // ============================================
  isStillRunningResult(result, isError) {
    const trimmed = (result == null ? void 0 : result.trim()) || "";
    const payload = this.unwrapTextPayload(trimmed);
    if (isError) return false;
    if (!trimmed) return false;
    try {
      const parsed = JSON.parse(payload);
      const status = parsed.retrieval_status || parsed.status;
      const hasAgents = parsed.agents && Object.keys(parsed.agents).length > 0;
      if (status === "not_ready" || status === "running" || status === "pending") {
        return true;
      }
      if (hasAgents) {
        const agentStatuses = Object.values(parsed.agents).map((a2) => a2 && typeof a2 === "object" && "status" in a2 && typeof a2.status === "string" ? a2.status.toLowerCase() : "");
        const anyRunning = agentStatuses.some(
          (s4) => s4 === "running" || s4 === "pending" || s4 === "not_ready"
        );
        if (anyRunning) return true;
        return false;
      }
      if (status === "success" || status === "completed") {
        return false;
      }
      return false;
    } catch (e2) {
    }
    const lowerResult = payload.toLowerCase();
    if (lowerResult.includes("not_ready") || lowerResult.includes("not ready")) {
      return true;
    }
    const xmlStatusMatch = lowerResult.match(/<status>([^<]+)<\/status>/);
    if (xmlStatusMatch) {
      const status = xmlStatusMatch[1].trim();
      if (status === "running" || status === "pending" || status === "not_ready") {
        return true;
      }
    }
    return false;
  }
  extractAgentResult(result, agentId, toolUseResult) {
    const structuredResult = this.taskResultInterpreter.extractStructuredResult(toolUseResult);
    const normalizedStructuredResult = this.extractResultFromCandidateString(structuredResult);
    if (normalizedStructuredResult) {
      return normalizedStructuredResult;
    }
    if (structuredResult) {
      return structuredResult;
    }
    const payload = this.unwrapTextPayload(result);
    try {
      const parsed = JSON.parse(payload);
      const taskResult = this.extractResultFromTaskObject(parsed.task);
      if (taskResult) {
        return taskResult;
      }
      if (parsed.agents && agentId && parsed.agents[agentId]) {
        const agentData = parsed.agents[agentId];
        const parsedResult2 = this.extractResultFromCandidateString(agentData == null ? void 0 : agentData.result);
        if (parsedResult2) {
          return parsedResult2;
        }
        const parsedOutput2 = this.extractResultFromCandidateString(agentData == null ? void 0 : agentData.output);
        if (parsedOutput2) {
          return parsedOutput2;
        }
        return JSON.stringify(agentData, null, 2);
      }
      if (parsed.agents) {
        const agentIds = Object.keys(parsed.agents);
        if (agentIds.length > 0) {
          const firstAgent = parsed.agents[agentIds[0]];
          const parsedResult2 = this.extractResultFromCandidateString(firstAgent == null ? void 0 : firstAgent.result);
          if (parsedResult2) {
            return parsedResult2;
          }
          const parsedOutput2 = this.extractResultFromCandidateString(firstAgent == null ? void 0 : firstAgent.output);
          if (parsedOutput2) {
            return parsedOutput2;
          }
          return JSON.stringify(firstAgent, null, 2);
        }
      }
      const parsedResult = this.extractResultFromCandidateString(parsed.result);
      if (parsedResult) {
        return parsedResult;
      }
      const parsedOutput = this.extractResultFromCandidateString(parsed.output);
      if (parsedOutput) {
        return parsedOutput;
      }
    } catch (e2) {
    }
    const taggedResult = this.extractResultFromTaggedPayload(payload);
    if (taggedResult) {
      return taggedResult;
    }
    return payload;
  }
  extractResultFromTaskObject(task) {
    var _a3;
    if (!task || typeof task !== "object") {
      return null;
    }
    const taskRecord = task;
    return (_a3 = this.extractResultFromCandidateString(taskRecord.result)) != null ? _a3 : this.extractResultFromCandidateString(taskRecord.output);
  }
  extractResultFromCandidateString(candidate) {
    if (typeof candidate !== "string") {
      return null;
    }
    const trimmed = candidate.trim();
    if (!trimmed) {
      return null;
    }
    const taggedResult = this.extractResultFromTaggedPayload(trimmed);
    if (taggedResult) {
      return taggedResult;
    }
    const jsonlResult = this.extractResultFromOutputJsonl(trimmed);
    if (jsonlResult) {
      return jsonlResult;
    }
    return trimmed;
  }
  parseAgentId(result) {
    var _a3;
    const regexPatterns = [
      /"agent_id"\s*:\s*"([^"]+)"/,
      /"agentId"\s*:\s*"([^"]+)"/,
      /agent_id[=:]\s*"?([a-zA-Z0-9_-]+)"?/i,
      /agentId[=:]\s*"?([a-zA-Z0-9_-]+)"?/i,
      /\b([a-f0-9]{8})\b/
    ];
    for (const pattern of regexPatterns) {
      const match = result.match(pattern);
      if (match && match[1]) {
        return match[1];
      }
    }
    try {
      const parsed = JSON.parse(result);
      const agentId = parsed.agent_id || parsed.agentId;
      if (typeof agentId === "string" && agentId.length > 0) {
        return agentId;
      }
      if ((_a3 = parsed.data) == null ? void 0 : _a3.agent_id) {
        return parsed.data.agent_id;
      }
      if (parsed.id && typeof parsed.id === "string") {
        return parsed.id;
      }
    } catch (e2) {
    }
    return null;
  }
  inferAgentIdFromResult(result) {
    try {
      const parsed = JSON.parse(result);
      if (parsed.agents && typeof parsed.agents === "object") {
        const keys = Object.keys(parsed.agents);
        if (keys.length > 0) {
          return keys[0];
        }
      }
    } catch (e2) {
    }
    return null;
  }
  unwrapTextPayload(raw) {
    try {
      const parsed = JSON.parse(raw);
      if (Array.isArray(parsed)) {
        const textBlock = parsed.find((b10) => b10 && typeof b10.text === "string");
        if (textBlock == null ? void 0 : textBlock.text) return textBlock.text;
      } else if (parsed && typeof parsed === "object" && typeof parsed.text === "string") {
        return parsed.text;
      }
    } catch (e2) {
    }
    return raw;
  }
  extractResultFromTaggedPayload(payload) {
    const directResult = this.taskResultInterpreter.extractTagValue(payload, "result");
    if (directResult) return directResult;
    const outputContent = this.taskResultInterpreter.extractTagValue(payload, "output");
    if (!outputContent) return null;
    const extractedFromJsonl = this.extractResultFromOutputJsonl(outputContent);
    if (extractedFromJsonl) return extractedFromJsonl;
    const nestedResult = this.taskResultInterpreter.extractTagValue(outputContent, "result");
    if (nestedResult) return nestedResult;
    const trimmed = outputContent.trim();
    return trimmed.length > 0 ? trimmed : null;
  }
  extractResultFromOutputJsonl(outputContent) {
    const inlineResult = extractFinalResultFromSubagentJsonl(outputContent);
    if (inlineResult) {
      return inlineResult;
    }
    const fullOutputPath = this.extractFullOutputPath(outputContent);
    if (!fullOutputPath) {
      return null;
    }
    const fullOutput = this.readFullOutputFile(fullOutputPath);
    if (!fullOutput) {
      return null;
    }
    return extractFinalResultFromSubagentJsonl(fullOutput);
  }
  extractFullOutputPath(content) {
    const truncatedPattern = /\[Truncated\.\s*Full output:\s*([^\]\n]+)\]/i;
    const match = content.match(truncatedPattern);
    if (!match || !match[1]) {
      return null;
    }
    const outputPath = match[1].trim();
    return outputPath.length > 0 ? outputPath : null;
  }
  readFullOutputFile(fullOutputPath) {
    try {
      if (!this.isTrustedOutputPath(fullOutputPath)) {
        return null;
      }
      if (!(0, import_fs6.existsSync)(fullOutputPath)) {
        return null;
      }
      const fileContent = (0, import_fs6.readFileSync)(fullOutputPath, "utf-8");
      const trimmed = fileContent.trim();
      return trimmed.length > 0 ? trimmed : null;
    } catch (e2) {
      return null;
    }
  }
  extractAgentIdFromInput(input) {
    const agentId = input.task_id || input.agentId || input.agent_id;
    return agentId || null;
  }
  static resolveTrustedTmpRoots() {
    const roots = /* @__PURE__ */ new Set();
    const candidates = [(0, import_os4.tmpdir)(), "/tmp", "/private/tmp"];
    for (const candidate of candidates) {
      try {
        roots.add((0, import_fs6.realpathSync)(candidate));
      } catch (e2) {
      }
    }
    return Array.from(roots);
  }
  isTrustedOutputPath(fullOutputPath) {
    if (!(0, import_path29.isAbsolute)(fullOutputPath)) {
      return false;
    }
    if (!fullOutputPath.toLowerCase().endsWith(_SubagentManager.TRUSTED_OUTPUT_EXT)) {
      return false;
    }
    let resolvedPath;
    try {
      resolvedPath = (0, import_fs6.realpathSync)(fullOutputPath);
    } catch (e2) {
      return false;
    }
    return _SubagentManager.TRUSTED_TMP_ROOTS.some(
      (root) => resolvedPath === root || resolvedPath.startsWith(`${root}${import_path29.sep}`)
    );
  }
};
_SubagentManager.TRUSTED_OUTPUT_EXT = ".output";
_SubagentManager.TRUSTED_TMP_ROOTS = _SubagentManager.resolveTrustedTmpRoots();
var SubagentManager = _SubagentManager;

// src/features/chat/state/ChatState.ts
function createInitialState() {
  return {
    messages: [],
    isStreaming: false,
    cancelRequested: false,
    streamGeneration: 0,
    isCreatingConversation: false,
    isSwitchingConversation: false,
    hasPendingConversationSave: false,
    currentConversationId: null,
    queuedMessage: null,
    currentContentEl: null,
    currentTextEl: null,
    currentTextContent: "",
    currentThinkingState: null,
    thinkingEl: null,
    queueIndicatorEl: null,
    thinkingIndicatorTimeout: null,
    toolCallElements: /* @__PURE__ */ new Map(),
    writeEditStates: /* @__PURE__ */ new Map(),
    pendingTools: /* @__PURE__ */ new Map(),
    usage: null,
    ignoreUsageUpdates: false,
    currentTodos: null,
    needsAttention: false,
    autoScrollEnabled: true,
    // Default; controllers will override based on settings
    responseStartTime: null,
    flavorTimerInterval: null,
    pendingNewSessionPlan: null,
    planFilePath: null,
    prePlanPermissionMode: null
  };
}
var ChatState = class {
  constructor(callbacks = {}) {
    this.state = createInitialState();
    this._callbacks = callbacks;
  }
  get callbacks() {
    return this._callbacks;
  }
  set callbacks(value) {
    this._callbacks = value;
  }
  // ============================================
  // Messages
  // ============================================
  get messages() {
    return [...this.state.messages];
  }
  set messages(value) {
    var _a3, _b2;
    this.state.messages = value;
    (_b2 = (_a3 = this._callbacks).onMessagesChanged) == null ? void 0 : _b2.call(_a3);
  }
  addMessage(msg) {
    var _a3, _b2;
    this.state.messages.push(msg);
    (_b2 = (_a3 = this._callbacks).onMessagesChanged) == null ? void 0 : _b2.call(_a3);
  }
  clearMessages() {
    var _a3, _b2;
    this.state.messages = [];
    (_b2 = (_a3 = this._callbacks).onMessagesChanged) == null ? void 0 : _b2.call(_a3);
  }
  truncateAt(messageId) {
    var _a3, _b2;
    const idx = this.state.messages.findIndex((m2) => m2.id === messageId);
    if (idx === -1) return 0;
    const removed = this.state.messages.length - idx;
    this.state.messages = this.state.messages.slice(0, idx);
    (_b2 = (_a3 = this._callbacks).onMessagesChanged) == null ? void 0 : _b2.call(_a3);
    return removed;
  }
  // ============================================
  // Streaming Control
  // ============================================
  get isStreaming() {
    return this.state.isStreaming;
  }
  set isStreaming(value) {
    var _a3, _b2;
    this.state.isStreaming = value;
    (_b2 = (_a3 = this._callbacks).onStreamingStateChanged) == null ? void 0 : _b2.call(_a3, value);
  }
  get cancelRequested() {
    return this.state.cancelRequested;
  }
  set cancelRequested(value) {
    this.state.cancelRequested = value;
  }
  get streamGeneration() {
    return this.state.streamGeneration;
  }
  bumpStreamGeneration() {
    this.state.streamGeneration += 1;
    return this.state.streamGeneration;
  }
  get isCreatingConversation() {
    return this.state.isCreatingConversation;
  }
  set isCreatingConversation(value) {
    this.state.isCreatingConversation = value;
  }
  get isSwitchingConversation() {
    return this.state.isSwitchingConversation;
  }
  set isSwitchingConversation(value) {
    this.state.isSwitchingConversation = value;
  }
  get hasPendingConversationSave() {
    return this.state.hasPendingConversationSave;
  }
  set hasPendingConversationSave(value) {
    this.state.hasPendingConversationSave = value;
  }
  // ============================================
  // Conversation
  // ============================================
  get currentConversationId() {
    return this.state.currentConversationId;
  }
  set currentConversationId(value) {
    var _a3, _b2;
    this.state.currentConversationId = value;
    (_b2 = (_a3 = this._callbacks).onConversationChanged) == null ? void 0 : _b2.call(_a3, value);
  }
  // ============================================
  // Queued Message
  // ============================================
  get queuedMessage() {
    return this.state.queuedMessage;
  }
  set queuedMessage(value) {
    this.state.queuedMessage = value;
  }
  // ============================================
  // Streaming DOM State
  // ============================================
  get currentContentEl() {
    return this.state.currentContentEl;
  }
  set currentContentEl(value) {
    this.state.currentContentEl = value;
  }
  get currentTextEl() {
    return this.state.currentTextEl;
  }
  set currentTextEl(value) {
    this.state.currentTextEl = value;
  }
  get currentTextContent() {
    return this.state.currentTextContent;
  }
  set currentTextContent(value) {
    this.state.currentTextContent = value;
  }
  get currentThinkingState() {
    return this.state.currentThinkingState;
  }
  set currentThinkingState(value) {
    this.state.currentThinkingState = value;
  }
  get thinkingEl() {
    return this.state.thinkingEl;
  }
  set thinkingEl(value) {
    this.state.thinkingEl = value;
  }
  get queueIndicatorEl() {
    return this.state.queueIndicatorEl;
  }
  set queueIndicatorEl(value) {
    this.state.queueIndicatorEl = value;
  }
  get thinkingIndicatorTimeout() {
    return this.state.thinkingIndicatorTimeout;
  }
  set thinkingIndicatorTimeout(value) {
    this.state.thinkingIndicatorTimeout = value;
  }
  // ============================================
  // Tool Tracking Maps (mutable references)
  // ============================================
  get toolCallElements() {
    return this.state.toolCallElements;
  }
  get writeEditStates() {
    return this.state.writeEditStates;
  }
  get pendingTools() {
    return this.state.pendingTools;
  }
  // ============================================
  // Usage State
  // ============================================
  get usage() {
    return this.state.usage;
  }
  set usage(value) {
    var _a3, _b2;
    this.state.usage = value;
    (_b2 = (_a3 = this._callbacks).onUsageChanged) == null ? void 0 : _b2.call(_a3, value);
  }
  get ignoreUsageUpdates() {
    return this.state.ignoreUsageUpdates;
  }
  set ignoreUsageUpdates(value) {
    this.state.ignoreUsageUpdates = value;
  }
  // ============================================
  // Current Todos (for persistent bottom panel)
  // ============================================
  get currentTodos() {
    return this.state.currentTodos ? [...this.state.currentTodos] : null;
  }
  set currentTodos(value) {
    var _a3, _b2;
    const normalizedValue = value && value.length > 0 ? value : null;
    this.state.currentTodos = normalizedValue;
    (_b2 = (_a3 = this._callbacks).onTodosChanged) == null ? void 0 : _b2.call(_a3, normalizedValue);
  }
  // ============================================
  // Attention State (approval pending, error, etc.)
  // ============================================
  get needsAttention() {
    return this.state.needsAttention;
  }
  set needsAttention(value) {
    var _a3, _b2;
    this.state.needsAttention = value;
    (_b2 = (_a3 = this._callbacks).onAttentionChanged) == null ? void 0 : _b2.call(_a3, value);
  }
  // ============================================
  // Auto-Scroll Control
  // ============================================
  get autoScrollEnabled() {
    return this.state.autoScrollEnabled;
  }
  set autoScrollEnabled(value) {
    var _a3, _b2;
    const changed = this.state.autoScrollEnabled !== value;
    this.state.autoScrollEnabled = value;
    if (changed) {
      (_b2 = (_a3 = this._callbacks).onAutoScrollChanged) == null ? void 0 : _b2.call(_a3, value);
    }
  }
  // ============================================
  // Response Timer State
  // ============================================
  get responseStartTime() {
    return this.state.responseStartTime;
  }
  set responseStartTime(value) {
    this.state.responseStartTime = value;
  }
  get flavorTimerInterval() {
    return this.state.flavorTimerInterval;
  }
  set flavorTimerInterval(value) {
    this.state.flavorTimerInterval = value;
  }
  get pendingNewSessionPlan() {
    return this.state.pendingNewSessionPlan;
  }
  set pendingNewSessionPlan(value) {
    this.state.pendingNewSessionPlan = value;
  }
  get planFilePath() {
    return this.state.planFilePath;
  }
  set planFilePath(value) {
    this.state.planFilePath = value;
  }
  get prePlanPermissionMode() {
    return this.state.prePlanPermissionMode;
  }
  set prePlanPermissionMode(value) {
    this.state.prePlanPermissionMode = value;
  }
  // ============================================
  // Reset Methods
  // ============================================
  clearFlavorTimerInterval() {
    if (this.state.flavorTimerInterval) {
      clearInterval(this.state.flavorTimerInterval);
      this.state.flavorTimerInterval = null;
    }
  }
  resetStreamingState() {
    this.state.currentContentEl = null;
    this.state.currentTextEl = null;
    this.state.currentTextContent = "";
    this.state.currentThinkingState = null;
    this.state.isStreaming = false;
    this.state.cancelRequested = false;
    if (this.state.thinkingIndicatorTimeout) {
      clearTimeout(this.state.thinkingIndicatorTimeout);
      this.state.thinkingIndicatorTimeout = null;
    }
    this.clearFlavorTimerInterval();
    this.state.responseStartTime = null;
  }
  clearMaps() {
    this.state.toolCallElements.clear();
    this.state.writeEditStates.clear();
    this.state.pendingTools.clear();
  }
  resetForNewConversation() {
    this.clearMessages();
    this.resetStreamingState();
    this.clearMaps();
    this.state.queuedMessage = null;
    this.usage = null;
    this.currentTodos = null;
    this.autoScrollEnabled = true;
  }
  getPersistedMessages() {
    return this.state.messages;
  }
};

// src/features/chat/ui/BangBashModeManager.ts
var import_obsidian32 = require("obsidian");
var BangBashModeManager = class {
  constructor(inputEl, callbacks) {
    this.state = { active: false, rawCommand: "" };
    this.isSubmitting = false;
    this.originalPlaceholder = "";
    this.inputEl = inputEl;
    this.callbacks = callbacks;
    this.originalPlaceholder = inputEl.placeholder;
  }
  handleTriggerKey(e2) {
    if (!this.state.active && this.inputEl.value === "" && e2.key === "!") {
      if (this.enterMode()) {
        e2.preventDefault();
        return true;
      }
    }
    return false;
  }
  handleInputChange() {
    if (!this.state.active) return;
    this.state.rawCommand = this.inputEl.value;
  }
  enterMode() {
    const wrapper = this.callbacks.getInputWrapper();
    if (!wrapper) return false;
    wrapper.addClass("claudian-input-bang-bash-mode");
    this.state = { active: true, rawCommand: "" };
    this.inputEl.placeholder = t("chat.bangBash.placeholder");
    return true;
  }
  exitMode() {
    const wrapper = this.callbacks.getInputWrapper();
    if (wrapper) {
      wrapper.removeClass("claudian-input-bang-bash-mode");
    }
    this.state = { active: false, rawCommand: "" };
    this.inputEl.placeholder = this.originalPlaceholder;
  }
  handleKeydown(e2) {
    if (!this.state.active) return false;
    if (e2.key === "Enter" && !e2.shiftKey && !e2.isComposing) {
      e2.preventDefault();
      if (this.state.rawCommand.trim()) {
        this.submit();
      }
      return true;
    }
    if (e2.key === "Escape" && !e2.isComposing) {
      e2.preventDefault();
      this.clear();
      return true;
    }
    return false;
  }
  isActive() {
    return this.state.active;
  }
  getRawCommand() {
    return this.state.rawCommand;
  }
  async submit() {
    if (this.isSubmitting) return;
    const rawCommand = this.state.rawCommand.trim();
    if (!rawCommand) return;
    this.isSubmitting = true;
    try {
      this.clear();
      await this.callbacks.onSubmit(rawCommand);
    } catch (e2) {
      new import_obsidian32.Notice(`Command failed: ${e2 instanceof Error ? e2.message : String(e2)}`);
    } finally {
      this.isSubmitting = false;
    }
  }
  clear() {
    var _a3, _b2;
    this.inputEl.value = "";
    this.exitMode();
    (_b2 = (_a3 = this.callbacks).resetInputHeight) == null ? void 0 : _b2.call(_a3);
  }
  destroy() {
    this.exitMode();
  }
};

// src/features/chat/ui/FileContext.ts
var import_obsidian36 = require("obsidian");

// src/shared/mention/MentionDropdownController.ts
var import_obsidian33 = require("obsidian");

// src/utils/externalContext.ts
var fs24 = __toESM(require("fs"));
init_path();
function normalizePathForComparison3(p) {
  return normalizePathForComparison(p);
}
function normalizePathForDisplay(p) {
  if (!p) return "";
  return p.replace(/\\/g, "/").replace(/\/+$/, "");
}
function findConflictingPath(newPath, existingPaths) {
  const normalizedNew = normalizePathForComparison3(newPath);
  for (const existing of existingPaths) {
    const normalizedExisting = normalizePathForComparison3(existing);
    if (normalizedNew.startsWith(normalizedExisting + "/")) {
      return { path: existing, type: "parent" };
    }
    if (normalizedExisting.startsWith(normalizedNew + "/")) {
      return { path: existing, type: "child" };
    }
  }
  return null;
}
function getFolderName(p) {
  const normalized = normalizePathForDisplay(p);
  const segments = normalized.split("/");
  return segments[segments.length - 1] || normalized;
}
function getContextDisplayName(normalizedPath, folderName, needsDisambiguation) {
  if (!needsDisambiguation) return folderName;
  const segments = normalizedPath.split("/").filter(Boolean);
  if (segments.length < 2) return folderName;
  const parent = segments[segments.length - 2];
  if (!parent) return folderName;
  return `${parent}/${folderName}`;
}
function buildExternalContextDisplayEntries(externalContexts) {
  var _a3;
  const counts = /* @__PURE__ */ new Map();
  const normalizedPaths = /* @__PURE__ */ new Map();
  for (const contextPath of externalContexts) {
    const normalized = normalizePathForComparison3(contextPath);
    normalizedPaths.set(contextPath, normalized);
    const folderName = getFolderName(normalized);
    counts.set(folderName, ((_a3 = counts.get(folderName)) != null ? _a3 : 0) + 1);
  }
  return externalContexts.map((contextRoot) => {
    var _a4, _b2;
    const normalized = (_a4 = normalizedPaths.get(contextRoot)) != null ? _a4 : normalizePathForComparison3(contextRoot);
    const folderName = getFolderName(contextRoot);
    const needsDisambiguation = ((_b2 = counts.get(folderName)) != null ? _b2 : 0) > 1;
    const displayName = getContextDisplayName(normalized, folderName, needsDisambiguation);
    return {
      contextRoot,
      displayName,
      displayNameLower: displayName.toLowerCase()
    };
  });
}
function validateDirectoryPath(p) {
  try {
    const stats = fs24.statSync(p);
    if (!stats.isDirectory()) {
      return { valid: false, error: "Path exists but is not a directory" };
    }
    return { valid: true };
  } catch (err) {
    const error48 = err;
    if (error48.code === "ENOENT") {
      return { valid: false, error: "Path does not exist" };
    }
    if (error48.code === "EACCES") {
      return { valid: false, error: "Permission denied" };
    }
    return { valid: false, error: `Cannot access path: ${error48.message}` };
  }
}
function isValidDirectoryPath(p) {
  return validateDirectoryPath(p).valid;
}
function filterValidPaths(paths) {
  return paths.filter(isValidDirectoryPath);
}
function isDuplicatePath(newPath, existingPaths) {
  const normalizedNew = normalizePathForComparison3(newPath);
  return existingPaths.some((existing) => normalizePathForComparison3(existing) === normalizedNew);
}

// src/utils/externalContextScanner.ts
var fs25 = __toESM(require("fs"));
var path21 = __toESM(require("path"));
init_path();
var CACHE_TTL_MS = 3e4;
var MAX_FILES_PER_PATH = 1e3;
var MAX_DEPTH = 10;
var SKIP_DIRECTORIES = /* @__PURE__ */ new Set([
  "node_modules",
  "__pycache__",
  "venv",
  ".venv",
  ".git",
  ".svn",
  ".hg",
  "dist",
  "build",
  "out",
  ".next",
  ".nuxt",
  "target",
  "vendor",
  "Pods"
]);
var ExternalContextScanner = class {
  constructor() {
    this.cache = /* @__PURE__ */ new Map();
  }
  scanPaths(externalContextPaths) {
    const allFiles = [];
    const now = Date.now();
    for (const contextPath of externalContextPaths) {
      const expandedPath = normalizePathForFilesystem(contextPath);
      const cached2 = this.cache.get(expandedPath);
      if (cached2 && now - cached2.timestamp < CACHE_TTL_MS) {
        allFiles.push(...cached2.files);
        continue;
      }
      const files = this.scanDirectory(expandedPath, expandedPath, 0);
      this.cache.set(expandedPath, { files, timestamp: now });
      allFiles.push(...files);
    }
    return allFiles;
  }
  scanDirectory(dir, contextRoot, depth) {
    if (depth > MAX_DEPTH) return [];
    const files = [];
    try {
      if (!fs25.existsSync(dir)) return [];
      const stat = fs25.statSync(dir);
      if (!stat.isDirectory()) return [];
      const entries = fs25.readdirSync(dir, { withFileTypes: true });
      for (const entry of entries) {
        if (entry.name.startsWith(".")) continue;
        if (SKIP_DIRECTORIES.has(entry.name)) continue;
        if (entry.isSymbolicLink()) continue;
        const fullPath = path21.join(dir, entry.name);
        if (entry.isDirectory()) {
          const subFiles = this.scanDirectory(fullPath, contextRoot, depth + 1);
          files.push(...subFiles);
        } else if (entry.isFile()) {
          try {
            const fileStat = fs25.statSync(fullPath);
            files.push({
              path: fullPath,
              name: entry.name,
              relativePath: path21.relative(contextRoot, fullPath),
              contextRoot,
              mtime: fileStat.mtimeMs
            });
          } catch (e2) {
          }
        }
        if (files.length >= MAX_FILES_PER_PATH) break;
      }
    } catch (e2) {
    }
    return files;
  }
  invalidateCache() {
    this.cache.clear();
  }
  invalidatePath(contextPath) {
    const expandedPath = normalizePathForFilesystem(contextPath);
    this.cache.delete(expandedPath);
  }
};
var externalContextScanner = new ExternalContextScanner();

// src/shared/components/SelectableDropdown.ts
var SelectableDropdown = class {
  constructor(containerEl, options) {
    this.dropdownEl = null;
    this.items = [];
    this.itemEls = [];
    this.selectedIndex = 0;
    this.containerEl = containerEl;
    this.options = options;
  }
  isVisible() {
    var _a3, _b2;
    return (_b2 = (_a3 = this.dropdownEl) == null ? void 0 : _a3.hasClass("visible")) != null ? _b2 : false;
  }
  getElement() {
    return this.dropdownEl;
  }
  getSelectedIndex() {
    return this.selectedIndex;
  }
  getSelectedItem() {
    var _a3;
    return (_a3 = this.items[this.selectedIndex]) != null ? _a3 : null;
  }
  getItems() {
    return this.items;
  }
  hide() {
    if (this.dropdownEl) {
      this.dropdownEl.removeClass("visible");
    }
  }
  destroy() {
    if (this.dropdownEl) {
      this.dropdownEl.remove();
      this.dropdownEl = null;
    }
  }
  render(options) {
    var _a3;
    this.items = options.items;
    this.selectedIndex = options.selectedIndex;
    if (!this.dropdownEl) {
      this.dropdownEl = this.createDropdownElement();
    }
    this.dropdownEl.empty();
    this.itemEls = [];
    if (options.items.length === 0) {
      const emptyEl = this.dropdownEl.createDiv({ cls: this.options.emptyClassName });
      emptyEl.setText(options.emptyText);
    } else {
      for (let i2 = 0; i2 < options.items.length; i2++) {
        const item = options.items[i2];
        const itemEl = this.dropdownEl.createDiv({ cls: this.options.itemClassName });
        const extraClass = (_a3 = options.getItemClass) == null ? void 0 : _a3.call(options, item);
        if (Array.isArray(extraClass)) {
          extraClass.forEach((cls) => itemEl.addClass(cls));
        } else if (extraClass) {
          itemEl.addClass(extraClass);
        }
        if (i2 === this.selectedIndex) {
          itemEl.addClass("selected");
        }
        options.renderItem(item, itemEl);
        itemEl.addEventListener("click", (e2) => {
          var _a4;
          this.selectedIndex = i2;
          this.updateSelection();
          (_a4 = options.onItemClick) == null ? void 0 : _a4.call(options, item, i2, e2);
        });
        itemEl.addEventListener("mouseenter", () => {
          var _a4;
          this.selectedIndex = i2;
          this.updateSelection();
          (_a4 = options.onItemHover) == null ? void 0 : _a4.call(options, item, i2);
        });
        this.itemEls.push(itemEl);
      }
    }
    this.dropdownEl.addClass("visible");
  }
  updateSelection() {
    this.itemEls.forEach((itemEl, index) => {
      if (index === this.selectedIndex) {
        itemEl.addClass("selected");
        itemEl.scrollIntoView({ block: "nearest" });
      } else {
        itemEl.removeClass("selected");
      }
    });
  }
  moveSelection(delta) {
    const maxIndex = this.items.length - 1;
    this.selectedIndex = Math.max(0, Math.min(maxIndex, this.selectedIndex + delta));
    this.updateSelection();
  }
  createDropdownElement() {
    const className = this.options.fixed && this.options.fixedClassName ? `${this.options.listClassName} ${this.options.fixedClassName}` : this.options.listClassName;
    return this.containerEl.createDiv({ cls: className });
  }
};

// src/shared/mention/MentionDropdownController.ts
var MentionDropdownController = class {
  constructor(containerEl, inputEl, callbacks, options = {}) {
    this.mentionStartIndex = -1;
    this.selectedMentionIndex = 0;
    this.filteredMentionItems = [];
    this.filteredContextFiles = [];
    this.activeContextFilter = null;
    this.activeAgentFilter = false;
    this.mcpManager = null;
    this.agentService = null;
    this.debounceTimer = null;
    var _a3;
    this.containerEl = containerEl;
    this.inputEl = inputEl;
    this.callbacks = callbacks;
    this.fixed = (_a3 = options.fixed) != null ? _a3 : false;
    this.dropdown = new SelectableDropdown(this.containerEl, {
      listClassName: "claudian-mention-dropdown",
      itemClassName: "claudian-mention-item",
      emptyClassName: "claudian-mention-empty",
      fixed: this.fixed,
      fixedClassName: "claudian-mention-dropdown-fixed"
    });
  }
  setMcpManager(manager) {
    this.mcpManager = manager;
  }
  setAgentService(service) {
    if (this.agentService !== service && this.dropdown.isVisible()) {
      this.hide();
    }
    this.agentService = service;
  }
  preScanExternalContexts() {
    const externalContexts = this.callbacks.getExternalContexts() || [];
    if (externalContexts.length === 0) return;
    setTimeout(() => {
      try {
        externalContextScanner.scanPaths(externalContexts);
      } catch (e2) {
      }
    }, 0);
  }
  isVisible() {
    return this.dropdown.isVisible();
  }
  hide() {
    this.dropdown.hide();
    this.mentionStartIndex = -1;
  }
  containsElement(el) {
    var _a3, _b2;
    return (_b2 = (_a3 = this.dropdown.getElement()) == null ? void 0 : _a3.contains(el)) != null ? _b2 : false;
  }
  destroy() {
    if (this.debounceTimer !== null) {
      clearTimeout(this.debounceTimer);
    }
    this.dropdown.destroy();
  }
  updateMcpMentionsFromText(text) {
    var _a3, _b2;
    if (!this.mcpManager) return;
    const validNames = new Set(
      this.mcpManager.getContextSavingServers().map((s4) => s4.name)
    );
    const newMentions = extractMcpMentions(text, validNames);
    const changed = this.callbacks.setMentionedMcpServers(newMentions);
    if (changed) {
      (_b2 = (_a3 = this.callbacks).onMcpMentionChange) == null ? void 0 : _b2.call(_a3, newMentions);
    }
  }
  handleInputChange() {
    if (this.debounceTimer !== null) {
      clearTimeout(this.debounceTimer);
    }
    this.debounceTimer = setTimeout(() => {
      const text = this.inputEl.value;
      this.updateMcpMentionsFromText(text);
      const cursorPos = this.inputEl.selectionStart || 0;
      const textBeforeCursor = text.substring(0, cursorPos);
      const lastAtIndex = textBeforeCursor.lastIndexOf("@");
      if (lastAtIndex === -1) {
        this.hide();
        return;
      }
      const charBeforeAt = lastAtIndex > 0 ? textBeforeCursor[lastAtIndex - 1] : " ";
      if (!/\s/.test(charBeforeAt) && lastAtIndex !== 0) {
        this.hide();
        return;
      }
      const searchText = textBeforeCursor.substring(lastAtIndex + 1);
      if (/\s/.test(searchText)) {
        this.hide();
        return;
      }
      this.mentionStartIndex = lastAtIndex;
      this.showMentionDropdown(searchText);
    }, 200);
  }
  handleKeydown(e2) {
    if (!this.dropdown.isVisible()) return false;
    if (e2.key === "ArrowDown") {
      e2.preventDefault();
      this.dropdown.moveSelection(1);
      this.selectedMentionIndex = this.dropdown.getSelectedIndex();
      return true;
    }
    if (e2.key === "ArrowUp") {
      e2.preventDefault();
      this.dropdown.moveSelection(-1);
      this.selectedMentionIndex = this.dropdown.getSelectedIndex();
      return true;
    }
    if ((e2.key === "Enter" || e2.key === "Tab") && !e2.isComposing) {
      e2.preventDefault();
      this.selectMentionItem();
      return true;
    }
    if (e2.key === "Escape" && !e2.isComposing) {
      e2.preventDefault();
      if (this.activeContextFilter || this.activeAgentFilter) {
        this.returnToFirstLevel();
        return true;
      }
      this.hide();
      return true;
    }
    return false;
  }
  showMentionDropdown(searchText) {
    const searchLower = searchText.toLowerCase();
    this.filteredMentionItems = [];
    this.filteredContextFiles = [];
    const externalContexts = this.callbacks.getExternalContexts() || [];
    const contextEntries = buildExternalContextDisplayEntries(externalContexts);
    const isFilterSearch = searchText.includes("/");
    let fileSearchText = searchLower;
    if (isFilterSearch && searchLower.startsWith("agents/")) {
      this.activeAgentFilter = true;
      this.activeContextFilter = null;
      const agentSearchText = searchText.substring("agents/".length).toLowerCase();
      if (this.agentService) {
        const matchingAgents = this.agentService.searchAgents(agentSearchText);
        for (const agent of matchingAgents) {
          this.filteredMentionItems.push({
            type: "agent",
            id: agent.id,
            name: agent.name,
            description: agent.description,
            source: agent.source
          });
        }
      }
      this.selectedMentionIndex = 0;
      this.renderMentionDropdown();
      return;
    }
    if (isFilterSearch) {
      const matchingContext = contextEntries.filter((entry) => searchLower.startsWith(`${entry.displayNameLower}/`)).sort((a2, b10) => b10.displayNameLower.length - a2.displayNameLower.length)[0];
      if (matchingContext) {
        const prefixLength = matchingContext.displayName.length + 1;
        fileSearchText = searchText.substring(prefixLength).toLowerCase();
        this.activeContextFilter = {
          folderName: matchingContext.displayName,
          contextRoot: matchingContext.contextRoot
        };
      } else {
        this.activeContextFilter = null;
      }
    }
    if (this.activeContextFilter && isFilterSearch) {
      const contextFiles = externalContextScanner.scanPaths([this.activeContextFilter.contextRoot]);
      this.filteredContextFiles = contextFiles.filter((file2) => {
        const relativePath = file2.relativePath.replace(/\\/g, "/");
        const pathLower = relativePath.toLowerCase();
        const nameLower = file2.name.toLowerCase();
        return pathLower.includes(fileSearchText) || nameLower.includes(fileSearchText);
      }).sort((a2, b10) => {
        const aNameMatch = a2.name.toLowerCase().startsWith(fileSearchText);
        const bNameMatch = b10.name.toLowerCase().startsWith(fileSearchText);
        if (aNameMatch && !bNameMatch) return -1;
        if (!aNameMatch && bNameMatch) return 1;
        return b10.mtime - a2.mtime;
      });
      for (const file2 of this.filteredContextFiles) {
        const relativePath = file2.relativePath.replace(/\\/g, "/");
        this.filteredMentionItems.push({
          type: "context-file",
          name: relativePath,
          absolutePath: file2.path,
          contextRoot: file2.contextRoot,
          folderName: this.activeContextFilter.folderName
        });
      }
      const firstVaultItemIndex2 = this.filteredMentionItems.length;
      const vaultItemCount2 = this.appendVaultItems(searchLower);
      if (this.filteredContextFiles.length === 0 && vaultItemCount2 > 0) {
        this.selectedMentionIndex = firstVaultItemIndex2;
      } else {
        this.selectedMentionIndex = 0;
      }
      this.renderMentionDropdown();
      return;
    }
    this.activeContextFilter = null;
    this.activeAgentFilter = false;
    if (this.mcpManager) {
      const mcpServers = this.mcpManager.getContextSavingServers();
      for (const server of mcpServers) {
        if (server.name.toLowerCase().includes(searchLower)) {
          this.filteredMentionItems.push({
            type: "mcp-server",
            name: server.name
          });
        }
      }
    }
    if (this.agentService) {
      const hasAgents = this.agentService.searchAgents("").length > 0;
      if (hasAgents && "agents".includes(searchLower)) {
        this.filteredMentionItems.push({
          type: "agent-folder",
          name: "Agents"
        });
      }
    }
    if (contextEntries.length > 0) {
      const matchingFolders = /* @__PURE__ */ new Set();
      for (const entry of contextEntries) {
        if (entry.displayNameLower.includes(searchLower) && !matchingFolders.has(entry.displayName)) {
          matchingFolders.add(entry.displayName);
          this.filteredMentionItems.push({
            type: "context-folder",
            name: entry.displayName,
            contextRoot: entry.contextRoot,
            folderName: entry.displayName
          });
        }
      }
    }
    const firstVaultItemIndex = this.filteredMentionItems.length;
    const vaultItemCount = this.appendVaultItems(searchLower);
    this.selectedMentionIndex = vaultItemCount > 0 ? firstVaultItemIndex : 0;
    this.renderMentionDropdown();
  }
  appendVaultItems(searchLower) {
    var _a3;
    const compare = (a2, b10) => {
      if (a2.startsWithQuery !== b10.startsWithQuery) return a2.startsWithQuery ? -1 : 1;
      if (a2.mtime !== b10.mtime) return b10.mtime - a2.mtime;
      if (a2.type !== b10.type) return a2.type === "file" ? -1 : 1;
      return a2.path.localeCompare(b10.path);
    };
    const allFiles = this.callbacks.getCachedVaultFiles();
    const folderMtimeMap = /* @__PURE__ */ new Map();
    for (const f2 of allFiles) {
      const parts = f2.path.split("/");
      for (let i2 = 1; i2 < parts.length; i2++) {
        const folderPath = parts.slice(0, i2).join("/");
        const existing = (_a3 = folderMtimeMap.get(folderPath)) != null ? _a3 : 0;
        if (f2.stat.mtime > existing) {
          folderMtimeMap.set(folderPath, f2.stat.mtime);
        }
      }
    }
    const scoredFolders = this.callbacks.getCachedVaultFolders().map((f2) => ({
      name: f2.name,
      path: f2.path.replace(/\\/g, "/").replace(/\/+$/, "")
    })).filter(
      (f2) => f2.path.length > 0 && (f2.path.toLowerCase().includes(searchLower) || f2.name.toLowerCase().includes(searchLower))
    ).map((f2) => {
      var _a4;
      return {
        type: "folder",
        name: f2.name,
        path: f2.path,
        startsWithQuery: f2.name.toLowerCase().startsWith(searchLower),
        mtime: (_a4 = folderMtimeMap.get(f2.path)) != null ? _a4 : 0
      };
    }).sort(compare).slice(0, 50);
    const scoredFiles = allFiles.filter(
      (f2) => f2.path.toLowerCase().includes(searchLower) || f2.name.toLowerCase().includes(searchLower)
    ).map((f2) => ({
      type: "file",
      name: f2.name,
      path: f2.path,
      file: f2,
      startsWithQuery: f2.name.toLowerCase().startsWith(searchLower),
      mtime: f2.stat.mtime
    })).sort(compare).slice(0, 100);
    const merged = [...scoredFolders, ...scoredFiles].sort(compare);
    for (const item of merged) {
      if (item.type === "folder") {
        this.filteredMentionItems.push({ type: "folder", name: item.name, path: item.path });
      } else {
        this.filteredMentionItems.push({ type: "file", name: item.name, path: item.path, file: item.file });
      }
    }
    return merged.length;
  }
  renderMentionDropdown() {
    this.dropdown.render({
      items: this.filteredMentionItems,
      selectedIndex: this.selectedMentionIndex,
      emptyText: "No matches",
      getItemClass: (item) => {
        switch (item.type) {
          case "mcp-server":
            return "mcp-server";
          case "folder":
            return "vault-folder";
          case "agent":
            return "agent";
          case "agent-folder":
            return "agent-folder";
          case "context-file":
            return "context-file";
          case "context-folder":
            return "context-folder";
          default:
            return void 0;
        }
      },
      renderItem: (item, itemEl) => {
        const iconEl = itemEl.createSpan({ cls: "claudian-mention-icon" });
        switch (item.type) {
          case "mcp-server":
            iconEl.innerHTML = MCP_ICON_SVG;
            break;
          case "agent":
          case "agent-folder":
            (0, import_obsidian33.setIcon)(iconEl, "bot");
            break;
          case "context-file":
            (0, import_obsidian33.setIcon)(iconEl, "folder-open");
            break;
          case "folder":
          case "context-folder":
            (0, import_obsidian33.setIcon)(iconEl, "folder");
            break;
          default:
            (0, import_obsidian33.setIcon)(iconEl, "file-text");
        }
        const textEl = itemEl.createSpan({ cls: "claudian-mention-text" });
        switch (item.type) {
          case "mcp-server":
            textEl.createSpan({ cls: "claudian-mention-name" }).setText(`@${item.name}`);
            break;
          case "agent-folder":
            textEl.createSpan({
              cls: "claudian-mention-name claudian-mention-name-agent-folder"
            }).setText(`@${item.name}/`);
            break;
          case "agent": {
            textEl.createSpan({
              cls: "claudian-mention-name claudian-mention-name-agent"
            }).setText(`@${item.id}`);
            if (item.description) {
              textEl.createSpan({ cls: "claudian-mention-agent-desc" }).setText(item.description);
            }
            break;
          }
          case "context-folder":
            textEl.createSpan({
              cls: "claudian-mention-name claudian-mention-name-folder"
            }).setText(`@${item.name}/`);
            break;
          case "context-file":
            textEl.createSpan({
              cls: "claudian-mention-name claudian-mention-name-context"
            }).setText(item.name);
            break;
          case "folder":
            textEl.createSpan({
              cls: "claudian-mention-name claudian-mention-name-folder"
            }).setText(`@${item.path}/`);
            break;
          default:
            textEl.createSpan({ cls: "claudian-mention-path" }).setText(item.path || item.name);
        }
      },
      onItemClick: (item, index, e2) => {
        if (item.type === "context-folder" || item.type === "agent-folder") {
          e2.stopPropagation();
        }
        this.selectedMentionIndex = index;
        this.selectMentionItem();
      },
      onItemHover: (_item, index) => {
        this.selectedMentionIndex = index;
      }
    });
    if (this.fixed) {
      this.positionFixed();
    }
  }
  positionFixed() {
    const dropdownEl = this.dropdown.getElement();
    if (!dropdownEl) return;
    const inputRect = this.inputEl.getBoundingClientRect();
    dropdownEl.style.position = "fixed";
    dropdownEl.style.bottom = `${window.innerHeight - inputRect.top + 4}px`;
    dropdownEl.style.left = `${inputRect.left}px`;
    dropdownEl.style.right = "auto";
    dropdownEl.style.width = `${Math.max(inputRect.width, 280)}px`;
    dropdownEl.style.zIndex = "10001";
  }
  insertReplacement(beforeAt, replacement, afterCursor) {
    this.inputEl.value = beforeAt + replacement + afterCursor;
    this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + replacement.length;
  }
  returnToFirstLevel() {
    const text = this.inputEl.value;
    const beforeAt = text.substring(0, this.mentionStartIndex);
    const cursorPos = this.inputEl.selectionStart || 0;
    const afterCursor = text.substring(cursorPos);
    this.inputEl.value = beforeAt + "@" + afterCursor;
    this.inputEl.selectionStart = this.inputEl.selectionEnd = beforeAt.length + 1;
    this.activeContextFilter = null;
    this.activeAgentFilter = false;
    this.showMentionDropdown("");
  }
  selectMentionItem() {
    var _a3, _b2, _c, _d2, _e, _f;
    if (this.filteredMentionItems.length === 0) return;
    const selectedIndex = this.dropdown.getSelectedIndex();
    this.selectedMentionIndex = selectedIndex;
    const selectedItem = this.filteredMentionItems[selectedIndex];
    if (!selectedItem) return;
    const text = this.inputEl.value;
    const beforeAt = text.substring(0, this.mentionStartIndex);
    const cursorPos = this.inputEl.selectionStart || 0;
    const afterCursor = text.substring(cursorPos);
    switch (selectedItem.type) {
      case "mcp-server": {
        const replacement = `@${selectedItem.name} `;
        this.insertReplacement(beforeAt, replacement, afterCursor);
        this.callbacks.addMentionedMcpServer(selectedItem.name);
        (_b2 = (_a3 = this.callbacks).onMcpMentionChange) == null ? void 0 : _b2.call(_a3, this.callbacks.getMentionedMcpServers());
        break;
      }
      case "agent-folder":
        this.activeAgentFilter = true;
        this.inputEl.focus();
        this.showMentionDropdown("Agents/");
        return;
      case "agent": {
        const replacement = `@${selectedItem.id} (agent) `;
        this.insertReplacement(beforeAt, replacement, afterCursor);
        (_d2 = (_c = this.callbacks).onAgentMentionSelect) == null ? void 0 : _d2.call(_c, selectedItem.id);
        break;
      }
      case "context-folder": {
        const replacement = `@${selectedItem.name}/`;
        this.insertReplacement(beforeAt, replacement, afterCursor);
        this.inputEl.focus();
        this.handleInputChange();
        return;
      }
      case "context-file": {
        const displayName = selectedItem.folderName ? `@${selectedItem.folderName}/${selectedItem.name}` : `@${selectedItem.name}`;
        if (selectedItem.absolutePath) {
          this.callbacks.onAttachFile(selectedItem.absolutePath);
        }
        this.insertReplacement(beforeAt, `${displayName} `, afterCursor);
        break;
      }
      case "folder": {
        const normalizedPath = this.callbacks.normalizePathForVault(selectedItem.path);
        this.insertReplacement(beforeAt, `@${normalizedPath != null ? normalizedPath : selectedItem.path}/ `, afterCursor);
        break;
      }
      default: {
        const rawPath = (_f = (_e = selectedItem.file) == null ? void 0 : _e.path) != null ? _f : selectedItem.path;
        const normalizedPath = this.callbacks.normalizePathForVault(rawPath);
        if (normalizedPath) {
          this.callbacks.onAttachFile(normalizedPath);
        }
        this.insertReplacement(beforeAt, `@${normalizedPath != null ? normalizedPath : selectedItem.name} `, afterCursor);
        break;
      }
    }
    this.hide();
    this.inputEl.focus();
  }
};

// src/shared/mention/VaultMentionCache.ts
var import_obsidian34 = require("obsidian");
var VaultFileCache = class {
  constructor(app, options = {}) {
    this.app = app;
    this.options = options;
    this.cachedFiles = [];
    this.dirty = true;
    this.isInitialized = false;
  }
  initializeInBackground() {
    if (this.isInitialized) return;
    setTimeout(() => {
      this.tryRefreshFiles();
    }, 0);
  }
  markDirty() {
    this.dirty = true;
  }
  getFiles() {
    if (this.dirty || !this.isInitialized) {
      this.tryRefreshFiles();
    }
    return this.cachedFiles;
  }
  tryRefreshFiles() {
    var _a3, _b2;
    try {
      this.cachedFiles = this.app.vault.getFiles();
      this.dirty = false;
    } catch (error48) {
      (_b2 = (_a3 = this.options).onLoadError) == null ? void 0 : _b2.call(_a3, error48);
      if (this.cachedFiles.length > 0) {
        this.dirty = false;
      }
    } finally {
      this.isInitialized = true;
    }
  }
};
function isVisibleFolder(folder) {
  const normalizedPath = folder.path.replace(/\\/g, "/").replace(/\/+$/, "");
  if (!normalizedPath) return false;
  return !normalizedPath.split("/").some((segment) => segment.startsWith("."));
}
var VaultFolderCache = class {
  constructor(app) {
    this.app = app;
    this.cachedFolders = [];
    this.dirty = true;
    this.isInitialized = false;
  }
  initializeInBackground() {
    if (this.isInitialized) return;
    setTimeout(() => {
      this.tryRefreshFolders();
    }, 0);
  }
  markDirty() {
    this.dirty = true;
  }
  getFolders() {
    if (this.dirty || !this.isInitialized) {
      this.tryRefreshFolders();
    }
    return this.cachedFolders;
  }
  tryRefreshFolders() {
    try {
      this.cachedFolders = this.loadFolders();
      this.dirty = false;
    } catch (e2) {
      if (this.cachedFolders.length > 0) {
        this.dirty = false;
      }
    } finally {
      this.isInitialized = true;
    }
  }
  loadFolders() {
    return this.app.vault.getAllLoadedFiles().filter((file2) => file2 instanceof import_obsidian34.TFolder && isVisibleFolder(file2));
  }
};

// src/shared/mention/VaultMentionDataProvider.ts
var VaultMentionDataProvider = class {
  constructor(app, options = {}) {
    this.hasReportedFileLoadError = false;
    this.fileCache = new VaultFileCache(app, {
      onLoadError: () => {
        var _a3;
        if (this.hasReportedFileLoadError) return;
        this.hasReportedFileLoadError = true;
        (_a3 = options.onFileLoadError) == null ? void 0 : _a3.call(options);
      }
    });
    this.folderCache = new VaultFolderCache(app);
  }
  initializeInBackground() {
    this.fileCache.initializeInBackground();
    this.folderCache.initializeInBackground();
  }
  markFilesDirty() {
    this.fileCache.markDirty();
  }
  markFoldersDirty() {
    this.folderCache.markDirty();
  }
  getCachedVaultFiles() {
    return this.fileCache.getFiles();
  }
  getCachedVaultFolders() {
    return this.folderCache.getFolders().map((folder) => ({
      name: folder.name,
      path: folder.path
    }));
  }
};

// src/utils/contextMentionResolver.ts
var TRAILING_PUNCTUATION_REGEX = /[),.!?:;]+$/;
var BOUNDARY_PUNCTUATION = /* @__PURE__ */ new Set([",", ")", "!", "?", ":", ";"]);
function isWhitespace(char) {
  return /\s/.test(char);
}
function collectMentionEndCandidates(text, pathStart) {
  const candidates = /* @__PURE__ */ new Set();
  for (let index = pathStart; index < text.length; index++) {
    const char = text[index];
    if (isWhitespace(char)) {
      candidates.add(index);
      continue;
    }
    if (BOUNDARY_PUNCTUATION.has(char)) {
      candidates.add(index + 1);
    }
  }
  candidates.add(text.length);
  return Array.from(candidates).sort((a2, b10) => b10 - a2);
}
function isMentionStart(text, index) {
  if (text[index] !== "@") return false;
  if (index === 0) return true;
  return isWhitespace(text[index - 1]);
}
function normalizeMentionPath(pathText) {
  return pathText.replace(/\\/g, "/").replace(/^\.?\//, "").replace(/\/+/g, "/").replace(/\/+$/, "");
}
function normalizeForPlatformLookup(value) {
  return process.platform === "win32" ? value.toLowerCase() : value;
}
function buildExternalContextLookup(files) {
  const lookup = /* @__PURE__ */ new Map();
  for (const file2 of files) {
    const normalized = normalizeMentionPath(file2.relativePath);
    if (!normalized) continue;
    const key = normalizeForPlatformLookup(normalized);
    if (!lookup.has(key)) {
      lookup.set(key, file2.path);
    }
  }
  return lookup;
}
function resolveExternalMentionAtIndex(text, mentionStart, contextEntries, getContextLookup) {
  const mentionBodyStart = mentionStart + 1;
  let bestMatch = null;
  for (const entry of contextEntries) {
    const displayNameEnd = mentionBodyStart + entry.displayName.length;
    if (displayNameEnd >= text.length) continue;
    const mentionDisplayName = text.slice(mentionBodyStart, displayNameEnd).toLowerCase();
    if (mentionDisplayName !== entry.displayNameLower) continue;
    const separator = text[displayNameEnd];
    if (separator !== "/" && separator !== "\\") continue;
    const lookup = getContextLookup(entry.contextRoot);
    const match = findBestMentionLookupMatch(
      text,
      displayNameEnd + 1,
      lookup,
      normalizeMentionPath,
      normalizeForPlatformLookup
    );
    if (!match) continue;
    if (!bestMatch || match.endIndex > bestMatch.endIndex) {
      bestMatch = match;
    }
  }
  return bestMatch;
}
function findBestMentionLookupMatch(text, pathStart, pathLookup, normalizePath, normalizeLookupKey) {
  var _a3, _b2;
  if (pathLookup.size === 0 || pathStart >= text.length) return null;
  const endCandidates = collectMentionEndCandidates(text, pathStart);
  for (const endIndex of endCandidates) {
    if (endIndex <= pathStart) continue;
    const rawPath = text.slice(pathStart, endIndex);
    const trailingPunctuation = (_b2 = (_a3 = rawPath.match(TRAILING_PUNCTUATION_REGEX)) == null ? void 0 : _a3[0]) != null ? _b2 : "";
    const rawPathWithoutPunctuation = trailingPunctuation ? rawPath.slice(0, -trailingPunctuation.length) : rawPath;
    const normalizedPath = normalizePath(rawPathWithoutPunctuation);
    if (!normalizedPath) continue;
    const resolvedPath = pathLookup.get(normalizeLookupKey(normalizedPath));
    if (resolvedPath) {
      return {
        resolvedPath,
        endIndex,
        trailingPunctuation
      };
    }
  }
  return null;
}
function createExternalContextLookupGetter(getContextFiles) {
  const lookupCache = /* @__PURE__ */ new Map();
  return (contextRoot) => {
    const cached2 = lookupCache.get(contextRoot);
    if (cached2) return cached2;
    const lookup = buildExternalContextLookup(getContextFiles(contextRoot));
    lookupCache.set(contextRoot, lookup);
    return lookup;
  };
}

// src/features/chat/ui/FileContext.ts
init_path();

// src/features/chat/ui/file-context/state/FileContextState.ts
var FileContextState = class {
  constructor() {
    this.attachedFiles = /* @__PURE__ */ new Set();
    this.sessionStarted = false;
    this.mentionedMcpServers = /* @__PURE__ */ new Set();
    this.currentNoteSent = false;
  }
  getAttachedFiles() {
    return new Set(this.attachedFiles);
  }
  hasSentCurrentNote() {
    return this.currentNoteSent;
  }
  markCurrentNoteSent() {
    this.currentNoteSent = true;
  }
  isSessionStarted() {
    return this.sessionStarted;
  }
  startSession() {
    this.sessionStarted = true;
  }
  resetForNewConversation() {
    this.sessionStarted = false;
    this.currentNoteSent = false;
    this.attachedFiles.clear();
    this.clearMcpMentions();
  }
  resetForLoadedConversation(hasMessages) {
    this.currentNoteSent = hasMessages;
    this.attachedFiles.clear();
    this.sessionStarted = hasMessages;
    this.clearMcpMentions();
  }
  setAttachedFiles(files) {
    this.attachedFiles.clear();
    for (const file2 of files) {
      this.attachedFiles.add(file2);
    }
  }
  attachFile(path24) {
    this.attachedFiles.add(path24);
  }
  detachFile(path24) {
    this.attachedFiles.delete(path24);
  }
  clearAttachments() {
    this.attachedFiles.clear();
  }
  getMentionedMcpServers() {
    return new Set(this.mentionedMcpServers);
  }
  clearMcpMentions() {
    this.mentionedMcpServers.clear();
  }
  setMentionedMcpServers(mentions) {
    const changed = mentions.size !== this.mentionedMcpServers.size || [...mentions].some((name) => !this.mentionedMcpServers.has(name));
    if (changed) {
      this.mentionedMcpServers = new Set(mentions);
    }
    return changed;
  }
  addMentionedMcpServer(name) {
    this.mentionedMcpServers.add(name);
  }
};

// src/features/chat/ui/file-context/view/FileChipsView.ts
var import_obsidian35 = require("obsidian");
var FileChipsView = class {
  constructor(containerEl, callbacks) {
    this.containerEl = containerEl;
    this.callbacks = callbacks;
    const firstChild = this.containerEl.firstChild;
    this.fileIndicatorEl = this.containerEl.createDiv({ cls: "claudian-file-indicator" });
    if (firstChild) {
      this.containerEl.insertBefore(this.fileIndicatorEl, firstChild);
    }
  }
  destroy() {
    this.fileIndicatorEl.remove();
  }
  renderCurrentNote(filePath) {
    this.fileIndicatorEl.empty();
    if (!filePath) {
      this.fileIndicatorEl.style.display = "none";
      return;
    }
    this.fileIndicatorEl.style.display = "flex";
    this.renderFileChip(filePath, () => {
      this.callbacks.onRemoveAttachment(filePath);
    });
  }
  renderFileChip(filePath, onRemove) {
    const chipEl = this.fileIndicatorEl.createDiv({ cls: "claudian-file-chip" });
    const iconEl = chipEl.createSpan({ cls: "claudian-file-chip-icon" });
    (0, import_obsidian35.setIcon)(iconEl, "file-text");
    const normalizedPath = filePath.replace(/\\/g, "/");
    const filename = normalizedPath.split("/").pop() || filePath;
    const nameEl = chipEl.createSpan({ cls: "claudian-file-chip-name" });
    nameEl.setText(filename);
    nameEl.setAttribute("title", filePath);
    const removeEl = chipEl.createSpan({ cls: "claudian-file-chip-remove" });
    removeEl.setText("\xD7");
    removeEl.setAttribute("aria-label", "Remove");
    chipEl.addEventListener("click", (e2) => {
      if (!e2.target.closest(".claudian-file-chip-remove")) {
        this.callbacks.onOpenFile(filePath);
      }
    });
    removeEl.addEventListener("click", () => {
      onRemove();
    });
  }
};

// src/features/chat/ui/FileContext.ts
var FileContextManager = class {
  constructor(app, chipsContainerEl, inputEl, callbacks, dropdownContainerEl) {
    this.deleteEventRef = null;
    this.renameEventRef = null;
    // Current note (shown as chip)
    this.currentNotePath = null;
    // MCP server support
    this.onMcpMentionChange = null;
    this.app = app;
    this.chipsContainerEl = chipsContainerEl;
    this.dropdownContainerEl = dropdownContainerEl != null ? dropdownContainerEl : chipsContainerEl;
    this.inputEl = inputEl;
    this.callbacks = callbacks;
    this.state = new FileContextState();
    this.mentionDataProvider = new VaultMentionDataProvider(this.app);
    this.mentionDataProvider.initializeInBackground();
    this.chipsView = new FileChipsView(this.chipsContainerEl, {
      onRemoveAttachment: (filePath) => {
        if (filePath === this.currentNotePath) {
          this.currentNotePath = null;
          this.state.detachFile(filePath);
          this.refreshCurrentNoteChip();
        }
      },
      onOpenFile: async (filePath) => {
        const file2 = this.app.vault.getAbstractFileByPath(filePath);
        if (!(file2 instanceof import_obsidian36.TFile)) {
          new import_obsidian36.Notice(`Could not open file: ${filePath}`);
          return;
        }
        try {
          await this.app.workspace.getLeaf().openFile(file2);
        } catch (error48) {
          new import_obsidian36.Notice(`Failed to open file: ${error48 instanceof Error ? error48.message : String(error48)}`);
        }
      }
    });
    this.mentionDropdown = new MentionDropdownController(
      this.dropdownContainerEl,
      this.inputEl,
      {
        onAttachFile: (filePath) => this.state.attachFile(filePath),
        onMcpMentionChange: (servers) => {
          var _a3;
          return (_a3 = this.onMcpMentionChange) == null ? void 0 : _a3.call(this, servers);
        },
        onAgentMentionSelect: (agentId) => {
          var _a3, _b2;
          return (_b2 = (_a3 = this.callbacks).onAgentMentionSelect) == null ? void 0 : _b2.call(_a3, agentId);
        },
        getMentionedMcpServers: () => this.state.getMentionedMcpServers(),
        setMentionedMcpServers: (mentions) => this.state.setMentionedMcpServers(mentions),
        addMentionedMcpServer: (name) => this.state.addMentionedMcpServer(name),
        getExternalContexts: () => {
          var _a3, _b2;
          return ((_b2 = (_a3 = this.callbacks).getExternalContexts) == null ? void 0 : _b2.call(_a3)) || [];
        },
        getCachedVaultFolders: () => this.mentionDataProvider.getCachedVaultFolders(),
        getCachedVaultFiles: () => this.mentionDataProvider.getCachedVaultFiles(),
        normalizePathForVault: (rawPath) => this.normalizePathForVault(rawPath)
      }
    );
    this.deleteEventRef = this.app.vault.on("delete", (file2) => {
      if (file2 instanceof import_obsidian36.TFile) this.handleFileDeleted(file2.path);
    });
    this.renameEventRef = this.app.vault.on("rename", (file2, oldPath) => {
      if (file2 instanceof import_obsidian36.TFile) this.handleFileRenamed(oldPath, file2.path);
    });
  }
  /** Returns the current note path (shown as chip). */
  getCurrentNotePath() {
    return this.currentNotePath;
  }
  getAttachedFiles() {
    return this.state.getAttachedFiles();
  }
  /** Checks whether current note should be sent for this session. */
  shouldSendCurrentNote(notePath) {
    const resolvedPath = notePath != null ? notePath : this.currentNotePath;
    return !!resolvedPath && !this.state.hasSentCurrentNote();
  }
  /** Marks current note as sent (call after sending a message). */
  markCurrentNoteSent() {
    this.state.markCurrentNoteSent();
  }
  isSessionStarted() {
    return this.state.isSessionStarted();
  }
  startSession() {
    this.state.startSession();
  }
  /** Resets state for a new conversation. */
  resetForNewConversation() {
    this.currentNotePath = null;
    this.state.resetForNewConversation();
    this.refreshCurrentNoteChip();
  }
  /** Resets state for loading an existing conversation. */
  resetForLoadedConversation(hasMessages) {
    this.currentNotePath = null;
    this.state.resetForLoadedConversation(hasMessages);
    this.refreshCurrentNoteChip();
  }
  /** Sets current note (for restoring persisted state). */
  setCurrentNote(notePath) {
    this.currentNotePath = notePath;
    if (notePath) {
      this.state.attachFile(notePath);
    }
    this.refreshCurrentNoteChip();
  }
  /** Auto-attaches the currently focused file (for new sessions). */
  autoAttachActiveFile() {
    const activeFile = this.app.workspace.getActiveFile();
    if (activeFile && !this.hasExcludedTag(activeFile)) {
      const normalizedPath = this.normalizePathForVault(activeFile.path);
      if (normalizedPath) {
        this.currentNotePath = normalizedPath;
        this.state.attachFile(normalizedPath);
        this.refreshCurrentNoteChip();
      }
    }
  }
  /** Handles file open event. */
  handleFileOpen(file2) {
    const normalizedPath = this.normalizePathForVault(file2.path);
    if (!normalizedPath) return;
    if (!this.state.isSessionStarted()) {
      this.state.clearAttachments();
      if (!this.hasExcludedTag(file2)) {
        this.currentNotePath = normalizedPath;
        this.state.attachFile(normalizedPath);
      } else {
        this.currentNotePath = null;
      }
      this.refreshCurrentNoteChip();
    }
  }
  markFileCacheDirty() {
    this.mentionDataProvider.markFilesDirty();
  }
  markFolderCacheDirty() {
    this.mentionDataProvider.markFoldersDirty();
  }
  /** Handles input changes to detect @ mentions. */
  handleInputChange() {
    this.mentionDropdown.handleInputChange();
  }
  /** Handles keyboard navigation in mention dropdown. Returns true if handled. */
  handleMentionKeydown(e2) {
    return this.mentionDropdown.handleKeydown(e2);
  }
  isMentionDropdownVisible() {
    return this.mentionDropdown.isVisible();
  }
  hideMentionDropdown() {
    this.mentionDropdown.hide();
  }
  containsElement(el) {
    return this.mentionDropdown.containsElement(el);
  }
  transformContextMentions(text) {
    var _a3, _b2;
    const externalContexts = ((_b2 = (_a3 = this.callbacks).getExternalContexts) == null ? void 0 : _b2.call(_a3)) || [];
    if (externalContexts.length === 0 || !text.includes("@")) return text;
    const contextEntries = buildExternalContextDisplayEntries(externalContexts).sort((a2, b10) => b10.displayNameLower.length - a2.displayNameLower.length);
    const getContextLookup = createExternalContextLookupGetter(
      (contextRoot) => externalContextScanner.scanPaths([contextRoot])
    );
    let replaced = false;
    let cursor = 0;
    const chunks = [];
    for (let index = 0; index < text.length; index++) {
      if (!isMentionStart(text, index)) continue;
      const resolved = resolveExternalMentionAtIndex(text, index, contextEntries, getContextLookup);
      if (!resolved) continue;
      chunks.push(text.slice(cursor, index));
      chunks.push(`${resolved.resolvedPath}${resolved.trailingPunctuation}`);
      cursor = resolved.endIndex;
      index = resolved.endIndex - 1;
      replaced = true;
    }
    if (!replaced) return text;
    chunks.push(text.slice(cursor));
    return chunks.join("");
  }
  /** Cleans up event listeners (call on view close). */
  destroy() {
    if (this.deleteEventRef) this.app.vault.offref(this.deleteEventRef);
    if (this.renameEventRef) this.app.vault.offref(this.renameEventRef);
    this.mentionDropdown.destroy();
    this.chipsView.destroy();
  }
  /** Normalizes a file path to be vault-relative with forward slashes. */
  normalizePathForVault(rawPath) {
    const vaultPath = getVaultPath(this.app);
    return normalizePathForVault(rawPath, vaultPath);
  }
  refreshCurrentNoteChip() {
    var _a3, _b2;
    this.chipsView.renderCurrentNote(this.currentNotePath);
    (_b2 = (_a3 = this.callbacks).onChipsChanged) == null ? void 0 : _b2.call(_a3);
  }
  handleFileRenamed(oldPath, newPath) {
    const normalizedOld = this.normalizePathForVault(oldPath);
    const normalizedNew = this.normalizePathForVault(newPath);
    if (!normalizedOld) return;
    let needsUpdate = false;
    if (this.currentNotePath === normalizedOld) {
      this.currentNotePath = normalizedNew;
      needsUpdate = true;
    }
    if (this.state.getAttachedFiles().has(normalizedOld)) {
      this.state.detachFile(normalizedOld);
      if (normalizedNew) {
        this.state.attachFile(normalizedNew);
      }
      needsUpdate = true;
    }
    if (needsUpdate) {
      this.refreshCurrentNoteChip();
    }
  }
  handleFileDeleted(deletedPath) {
    const normalized = this.normalizePathForVault(deletedPath);
    if (!normalized) return;
    let needsUpdate = false;
    if (this.currentNotePath === normalized) {
      this.currentNotePath = null;
      needsUpdate = true;
    }
    if (this.state.getAttachedFiles().has(normalized)) {
      this.state.detachFile(normalized);
      needsUpdate = true;
    }
    if (needsUpdate) {
      this.refreshCurrentNoteChip();
    }
  }
  // ========================================
  // MCP Server Support
  // ========================================
  setMcpManager(manager) {
    this.mentionDropdown.setMcpManager(manager);
  }
  setAgentService(agentService) {
    this.mentionDropdown.setAgentService(agentService);
  }
  setOnMcpMentionChange(callback) {
    this.onMcpMentionChange = callback;
  }
  /**
   * Pre-scans external context paths in the background to warm the cache.
   * Should be called when external context paths are added/changed.
   */
  preScanExternalContexts() {
    this.mentionDropdown.preScanExternalContexts();
  }
  getMentionedMcpServers() {
    return this.state.getMentionedMcpServers();
  }
  clearMcpMentions() {
    this.state.clearMcpMentions();
  }
  updateMcpMentionsFromText(text) {
    this.mentionDropdown.updateMcpMentionsFromText(text);
  }
  hasExcludedTag(file2) {
    var _a3;
    const excludedTags = this.callbacks.getExcludedTags();
    if (excludedTags.length === 0) return false;
    const cache = this.app.metadataCache.getFileCache(file2);
    if (!cache) return false;
    const fileTags = [];
    if ((_a3 = cache.frontmatter) == null ? void 0 : _a3.tags) {
      const fmTags = cache.frontmatter.tags;
      if (Array.isArray(fmTags)) {
        fileTags.push(...fmTags.map((t2) => t2.replace(/^#/, "")));
      } else if (typeof fmTags === "string") {
        fileTags.push(fmTags.replace(/^#/, ""));
      }
    }
    if (cache.tags) {
      fileTags.push(...cache.tags.map((t2) => t2.tag.replace(/^#/, "")));
    }
    return fileTags.some((tag) => excludedTags.includes(tag));
  }
};

// src/features/chat/ui/ImageContext.ts
var import_obsidian37 = require("obsidian");
var path22 = __toESM(require("path"));
var MAX_IMAGE_SIZE = 5 * 1024 * 1024;
var IMAGE_EXTENSIONS2 = {
  ".jpg": "image/jpeg",
  ".jpeg": "image/jpeg",
  ".png": "image/png",
  ".gif": "image/gif",
  ".webp": "image/webp"
};
var ImageContextManager = class {
  constructor(containerEl, inputEl, callbacks, previewContainerEl) {
    this.dropOverlay = null;
    this.attachedImages = /* @__PURE__ */ new Map();
    this.enabled = true;
    this.containerEl = containerEl;
    this.previewContainerEl = previewContainerEl != null ? previewContainerEl : containerEl;
    this.inputEl = inputEl;
    this.callbacks = callbacks;
    const fileIndicator = this.previewContainerEl.querySelector(".claudian-file-indicator");
    this.imagePreviewEl = this.previewContainerEl.createDiv({ cls: "claudian-image-preview" });
    if (fileIndicator && fileIndicator.parentElement === this.previewContainerEl) {
      this.previewContainerEl.insertBefore(this.imagePreviewEl, fileIndicator);
    }
    this.setupDragAndDrop();
    this.setupPasteHandler();
  }
  setEnabled(enabled) {
    this.enabled = enabled;
    if (!enabled && this.attachedImages.size > 0) {
      this.clearImages();
    }
  }
  getAttachedImages() {
    return Array.from(this.attachedImages.values());
  }
  hasImages() {
    return this.attachedImages.size > 0;
  }
  clearImages() {
    this.attachedImages.clear();
    this.updateImagePreview();
    this.callbacks.onImagesChanged();
  }
  /** Sets images directly (used for queued messages). */
  setImages(images) {
    this.attachedImages.clear();
    for (const image of images) {
      this.attachedImages.set(image.id, image);
    }
    this.updateImagePreview();
    this.callbacks.onImagesChanged();
  }
  setupDragAndDrop() {
    const inputWrapper = this.containerEl.querySelector(".claudian-input-wrapper");
    if (!inputWrapper) return;
    this.dropOverlay = inputWrapper.createDiv({ cls: "claudian-drop-overlay" });
    const dropContent = this.dropOverlay.createDiv({ cls: "claudian-drop-content" });
    const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
    svg.setAttribute("viewBox", "0 0 24 24");
    svg.setAttribute("width", "32");
    svg.setAttribute("height", "32");
    svg.setAttribute("fill", "none");
    svg.setAttribute("stroke", "currentColor");
    svg.setAttribute("stroke-width", "2");
    const pathEl = document.createElementNS("http://www.w3.org/2000/svg", "path");
    pathEl.setAttribute("d", "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4");
    const polyline = document.createElementNS("http://www.w3.org/2000/svg", "polyline");
    polyline.setAttribute("points", "17 8 12 3 7 8");
    const line = document.createElementNS("http://www.w3.org/2000/svg", "line");
    line.setAttribute("x1", "12");
    line.setAttribute("y1", "3");
    line.setAttribute("x2", "12");
    line.setAttribute("y2", "15");
    svg.appendChild(pathEl);
    svg.appendChild(polyline);
    svg.appendChild(line);
    dropContent.appendChild(svg);
    dropContent.createSpan({ text: "Drop image here" });
    const dropZone = inputWrapper;
    dropZone.addEventListener("dragenter", (e2) => this.handleDragEnter(e2));
    dropZone.addEventListener("dragover", (e2) => this.handleDragOver(e2));
    dropZone.addEventListener("dragleave", (e2) => this.handleDragLeave(e2));
    dropZone.addEventListener("drop", (e2) => this.handleDrop(e2));
  }
  handleDragEnter(e2) {
    var _a3, _b2;
    e2.preventDefault();
    e2.stopPropagation();
    if ((_a3 = e2.dataTransfer) == null ? void 0 : _a3.types.includes("Files")) {
      (_b2 = this.dropOverlay) == null ? void 0 : _b2.addClass("visible");
    }
  }
  handleDragOver(e2) {
    e2.preventDefault();
    e2.stopPropagation();
  }
  handleDragLeave(e2) {
    var _a3, _b2;
    e2.preventDefault();
    e2.stopPropagation();
    const inputWrapper = this.containerEl.querySelector(".claudian-input-wrapper");
    if (!inputWrapper) {
      (_a3 = this.dropOverlay) == null ? void 0 : _a3.removeClass("visible");
      return;
    }
    const rect = inputWrapper.getBoundingClientRect();
    if (e2.clientX <= rect.left || e2.clientX >= rect.right || e2.clientY <= rect.top || e2.clientY >= rect.bottom) {
      (_b2 = this.dropOverlay) == null ? void 0 : _b2.removeClass("visible");
    }
  }
  async handleDrop(e2) {
    var _a3, _b2;
    e2.preventDefault();
    e2.stopPropagation();
    (_a3 = this.dropOverlay) == null ? void 0 : _a3.removeClass("visible");
    const files = (_b2 = e2.dataTransfer) == null ? void 0 : _b2.files;
    if (!files) return;
    for (let i2 = 0; i2 < files.length; i2++) {
      const file2 = files[i2];
      if (this.isImageFile(file2)) {
        await this.addImageFromFile(file2, "drop");
      }
    }
  }
  setupPasteHandler() {
    this.inputEl.addEventListener("paste", async (e2) => {
      var _a3;
      const items = (_a3 = e2.clipboardData) == null ? void 0 : _a3.items;
      if (!items) return;
      for (let i2 = 0; i2 < items.length; i2++) {
        const item = items[i2];
        if (item.type.startsWith("image/")) {
          e2.preventDefault();
          const file2 = item.getAsFile();
          if (file2) {
            await this.addImageFromFile(file2, "paste");
          }
          return;
        }
      }
    });
  }
  isImageFile(file2) {
    return file2.type.startsWith("image/") && this.getMediaType(file2.name) !== null;
  }
  getMediaType(filename) {
    const ext = path22.extname(filename).toLowerCase();
    return IMAGE_EXTENSIONS2[ext] || null;
  }
  async addImageFromFile(file2, source) {
    if (!this.enabled) {
      new import_obsidian37.Notice("Image attachments are not supported by this provider.");
      return false;
    }
    if (file2.size > MAX_IMAGE_SIZE) {
      this.notifyImageError(`Image exceeds ${this.formatSize(MAX_IMAGE_SIZE)} limit.`);
      return false;
    }
    const mediaType = this.getMediaType(file2.name) || file2.type;
    if (!mediaType) {
      this.notifyImageError("Unsupported image type.");
      return false;
    }
    try {
      const base643 = await this.fileToBase64(file2);
      const attachment = {
        id: this.generateId(),
        name: file2.name || `image-${Date.now()}.${mediaType.split("/")[1]}`,
        mediaType,
        data: base643,
        size: file2.size,
        source
      };
      this.attachedImages.set(attachment.id, attachment);
      this.updateImagePreview();
      this.callbacks.onImagesChanged();
      return true;
    } catch (error48) {
      this.notifyImageError("Failed to attach image.", error48);
      return false;
    }
  }
  async fileToBase64(file2) {
    const arrayBuffer = await file2.arrayBuffer();
    const buffer = Buffer.from(arrayBuffer);
    return buffer.toString("base64");
  }
  // ============================================
  // Private: Image Preview
  // ============================================
  updateImagePreview() {
    this.imagePreviewEl.empty();
    if (this.attachedImages.size === 0) {
      this.imagePreviewEl.style.display = "none";
      return;
    }
    this.imagePreviewEl.style.display = "flex";
    for (const [id, image] of this.attachedImages) {
      this.renderImagePreview(id, image);
    }
  }
  renderImagePreview(id, image) {
    const previewEl = this.imagePreviewEl.createDiv({ cls: "claudian-image-chip" });
    const thumbEl = previewEl.createDiv({ cls: "claudian-image-thumb" });
    thumbEl.createEl("img", {
      attr: {
        src: `data:${image.mediaType};base64,${image.data}`,
        alt: image.name
      }
    });
    const infoEl = previewEl.createDiv({ cls: "claudian-image-info" });
    const nameEl = infoEl.createSpan({ cls: "claudian-image-name" });
    nameEl.setText(this.truncateName(image.name, 20));
    nameEl.setAttribute("title", image.name);
    const sizeEl = infoEl.createSpan({ cls: "claudian-image-size" });
    sizeEl.setText(this.formatSize(image.size));
    const removeEl = previewEl.createSpan({ cls: "claudian-image-remove" });
    removeEl.setText("\xD7");
    removeEl.setAttribute("aria-label", "Remove image");
    removeEl.addEventListener("click", (e2) => {
      e2.stopPropagation();
      this.attachedImages.delete(id);
      this.updateImagePreview();
      this.callbacks.onImagesChanged();
    });
    thumbEl.addEventListener("click", () => {
      this.showFullImage(image);
    });
  }
  showFullImage(image) {
    const overlay = document.body.createDiv({ cls: "claudian-image-modal-overlay" });
    const modal = overlay.createDiv({ cls: "claudian-image-modal" });
    modal.createEl("img", {
      attr: {
        src: `data:${image.mediaType};base64,${image.data}`,
        alt: image.name
      }
    });
    const closeBtn = modal.createDiv({ cls: "claudian-image-modal-close" });
    closeBtn.setText("\xD7");
    const handleEsc = (e2) => {
      if (e2.key === "Escape") {
        close();
      }
    };
    const close = () => {
      document.removeEventListener("keydown", handleEsc);
      overlay.remove();
    };
    closeBtn.addEventListener("click", close);
    overlay.addEventListener("click", (e2) => {
      if (e2.target === overlay) close();
    });
    document.addEventListener("keydown", handleEsc);
  }
  generateId() {
    return `img-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
  }
  truncateName(name, maxLen) {
    if (name.length <= maxLen) return name;
    const ext = path22.extname(name);
    const base = name.slice(0, name.length - ext.length);
    const truncatedBase = base.slice(0, maxLen - ext.length - 3);
    return `${truncatedBase}...${ext}`;
  }
  formatSize(bytes) {
    if (bytes < 1024) return `${bytes} B`;
    if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
    return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
  }
  notifyImageError(message, error48) {
    let userMessage = message;
    if (error48 instanceof Error) {
      if (error48.message.includes("ENOENT") || error48.message.includes("no such file")) {
        userMessage = `${message} (File not found)`;
      } else if (error48.message.includes("EACCES") || error48.message.includes("permission denied")) {
        userMessage = `${message} (Permission denied)`;
      }
    }
    new import_obsidian37.Notice(userMessage);
  }
};

// src/features/chat/ui/InputToolbar.ts
var import_obsidian38 = require("obsidian");
var path23 = __toESM(require("path"));
init_path();
var ModelSelector = class {
  constructor(parentEl, callbacks) {
    this.buttonEl = null;
    this.dropdownEl = null;
    this.callbacks = callbacks;
    this.container = parentEl.createDiv({ cls: "claudian-model-selector" });
    this.render();
  }
  getAvailableModels() {
    var _a3, _b2;
    const settings11 = this.callbacks.getSettings();
    const uiConfig = this.callbacks.getUIConfig();
    return uiConfig.getModelOptions({
      ...settings11,
      environmentVariables: (_b2 = (_a3 = this.callbacks).getEnvironmentVariables) == null ? void 0 : _b2.call(_a3)
    });
  }
  render() {
    this.container.empty();
    this.buttonEl = this.container.createDiv({ cls: "claudian-model-btn" });
    this.updateDisplay();
    this.dropdownEl = this.container.createDiv({ cls: "claudian-model-dropdown" });
    this.renderOptions();
  }
  updateDisplay() {
    if (!this.buttonEl) return;
    const currentModel = this.callbacks.getSettings().model;
    const models = this.getAvailableModels();
    const modelInfo = models.find((m2) => m2.value === currentModel);
    const displayModel = modelInfo || models[0];
    this.buttonEl.empty();
    const labelEl = this.buttonEl.createSpan({ cls: "claudian-model-label" });
    labelEl.setText((displayModel == null ? void 0 : displayModel.label) || "Unknown");
  }
  renderOptions() {
    var _a3, _b2, _c;
    if (!this.dropdownEl) return;
    this.dropdownEl.empty();
    const currentModel = this.callbacks.getSettings().model;
    const models = this.getAvailableModels();
    const reversed = [...models].reverse();
    let lastGroup;
    for (const model of reversed) {
      if (model.group && model.group !== lastGroup) {
        const separator = this.dropdownEl.createDiv({ cls: "claudian-model-group" });
        separator.setText(model.group);
        lastGroup = model.group;
      }
      const option = this.dropdownEl.createDiv({ cls: "claudian-model-option" });
      if (model.value === currentModel) {
        option.addClass("selected");
      }
      const icon = (_c = model.providerIcon) != null ? _c : (_b2 = (_a3 = this.callbacks.getUIConfig()).getProviderIcon) == null ? void 0 : _b2.call(_a3);
      if (icon) {
        option.appendChild(createProviderIconSvg(icon, {
          className: "claudian-model-provider-icon",
          height: 12,
          width: 12
        }));
      }
      option.createSpan({ text: model.label });
      if (model.description) {
        option.setAttribute("title", model.description);
      }
      option.addEventListener("click", async (e2) => {
        e2.stopPropagation();
        await this.callbacks.onModelChange(model.value);
        this.updateDisplay();
        this.renderOptions();
      });
    }
  }
};
var ModeSelector = class {
  constructor(parentEl, callbacks) {
    this.labelEl = null;
    this.toggleEl = null;
    this.callbacks = callbacks;
    this.container = parentEl.createDiv({ cls: "claudian-mode-selector" });
    this.render();
  }
  getSelectorConfig() {
    var _a3, _b2, _c;
    return (_c = (_b2 = (_a3 = this.callbacks.getUIConfig()).getModeSelector) == null ? void 0 : _b2.call(_a3, this.callbacks.getSettings())) != null ? _c : null;
  }
  render() {
    this.container.empty();
    this.labelEl = this.container.createSpan({ cls: "claudian-mode-label" });
    this.toggleEl = this.container.createDiv({ cls: "claudian-toggle-switch" });
    this.toggleEl.addEventListener("click", () => this.toggle());
    this.updateDisplay();
  }
  /** Resolves the active/inactive option pair for a two-option toggle. */
  resolveOptionPair(selectorConfig) {
    var _a3;
    const [first, second] = selectorConfig.options;
    const active = selectorConfig.activeValue ? (_a3 = selectorConfig.options.find((option) => option.value === selectorConfig.activeValue)) != null ? _a3 : second : second;
    const inactive = active.value === first.value ? second : first;
    return { active, inactive };
  }
  updateDisplay() {
    var _a3;
    if (!this.toggleEl || !this.labelEl) {
      return;
    }
    const selectorConfig = this.getSelectorConfig();
    if (!selectorConfig || selectorConfig.options.length !== 2) {
      this.container.style.display = "none";
      return;
    }
    this.container.style.display = "";
    const { active, inactive } = this.resolveOptionPair(selectorConfig);
    const currentOption = (_a3 = selectorConfig.options.find((option) => option.value === selectorConfig.value)) != null ? _a3 : selectorConfig.options[0];
    const isActive = currentOption.value === active.value;
    this.labelEl.setText(currentOption.label || selectorConfig.label);
    this.labelEl.toggleClass("active", isActive);
    if (isActive) {
      this.toggleEl.addClass("active");
    } else {
      this.toggleEl.removeClass("active");
    }
    const titleParts = [`${inactive.label} <-> ${active.label}`];
    if (currentOption.description) {
      titleParts.push(currentOption.description);
    }
    this.container.setAttribute("title", titleParts.join("\n"));
  }
  renderOptions() {
    this.updateDisplay();
  }
  async toggle() {
    const selectorConfig = this.getSelectorConfig();
    if (!selectorConfig || selectorConfig.options.length !== 2) {
      return;
    }
    const { active, inactive } = this.resolveOptionPair(selectorConfig);
    const nextValue = selectorConfig.value === active.value ? inactive.value : active.value;
    await this.callbacks.onModeChange(nextValue);
    this.updateDisplay();
  }
};
var ThinkingBudgetSelector = class {
  constructor(parentEl, callbacks) {
    this.effortEl = null;
    this.effortGearsEl = null;
    this.budgetEl = null;
    this.budgetGearsEl = null;
    this.callbacks = callbacks;
    this.container = parentEl.createDiv({ cls: "claudian-thinking-selector" });
    this.render();
  }
  render() {
    this.container.empty();
    this.effortEl = this.container.createDiv({ cls: "claudian-thinking-effort" });
    const effortLabel = this.effortEl.createSpan({ cls: "claudian-thinking-label-text" });
    effortLabel.setText("Effort:");
    this.effortGearsEl = this.effortEl.createDiv({ cls: "claudian-thinking-gears" });
    this.budgetEl = this.container.createDiv({ cls: "claudian-thinking-budget" });
    const budgetLabel = this.budgetEl.createSpan({ cls: "claudian-thinking-label-text" });
    budgetLabel.setText("Thinking:");
    this.budgetGearsEl = this.budgetEl.createDiv({ cls: "claudian-thinking-gears" });
    this.updateDisplay();
  }
  renderEffortGears() {
    var _a3;
    if (!this.effortGearsEl) return;
    this.effortGearsEl.empty();
    const currentEffort = this.callbacks.getSettings().effortLevel;
    const uiConfig = this.callbacks.getUIConfig();
    const settings11 = this.callbacks.getSettings();
    const model = settings11.model;
    const options = uiConfig.getReasoningOptions(model, settings11);
    const currentInfo = options.find((e2) => e2.value === currentEffort);
    const currentEl = this.effortGearsEl.createDiv({ cls: "claudian-thinking-current" });
    currentEl.setText((currentInfo == null ? void 0 : currentInfo.label) || ((_a3 = options[0]) == null ? void 0 : _a3.label) || "High");
    const optionsEl = this.effortGearsEl.createDiv({ cls: "claudian-thinking-options" });
    for (const effort of [...options].reverse()) {
      const gearEl = optionsEl.createDiv({ cls: "claudian-thinking-gear" });
      gearEl.setText(effort.label);
      if (effort.value === currentEffort) {
        gearEl.addClass("selected");
      }
      gearEl.addEventListener("click", async (e2) => {
        e2.stopPropagation();
        await this.callbacks.onEffortLevelChange(effort.value);
        this.updateDisplay();
      });
    }
  }
  renderBudgetGears() {
    var _a3, _b2;
    if (!this.budgetGearsEl) return;
    this.budgetGearsEl.empty();
    const currentBudget = this.callbacks.getSettings().thinkingBudget;
    const uiConfig = this.callbacks.getUIConfig();
    const settings11 = this.callbacks.getSettings();
    const model = settings11.model;
    const options = uiConfig.getReasoningOptions(model, settings11);
    const currentBudgetInfo = options.find((b10) => b10.value === currentBudget);
    const currentEl = this.budgetGearsEl.createDiv({ cls: "claudian-thinking-current" });
    currentEl.setText((currentBudgetInfo == null ? void 0 : currentBudgetInfo.label) || ((_a3 = options[0]) == null ? void 0 : _a3.label) || "Off");
    const optionsEl = this.budgetGearsEl.createDiv({ cls: "claudian-thinking-options" });
    for (const budget of [...options].reverse()) {
      const gearEl = optionsEl.createDiv({ cls: "claudian-thinking-gear" });
      gearEl.setText(budget.label);
      const tokens = (_b2 = budget.tokens) != null ? _b2 : 0;
      gearEl.setAttribute("title", tokens > 0 ? `${tokens.toLocaleString()} tokens` : "Disabled");
      if (budget.value === currentBudget) {
        gearEl.addClass("selected");
      }
      gearEl.addEventListener("click", async (e2) => {
        e2.stopPropagation();
        await this.callbacks.onThinkingBudgetChange(budget.value);
        this.updateDisplay();
      });
    }
  }
  updateDisplay() {
    var _a3;
    const capabilities = this.callbacks.getCapabilities();
    if (capabilities.reasoningControl === "none") {
      if (this.effortEl) this.effortEl.style.display = "none";
      if (this.budgetEl) this.budgetEl.style.display = "none";
      return;
    }
    const settings11 = this.callbacks.getSettings();
    const model = settings11.model;
    const uiConfig = this.callbacks.getUIConfig();
    const options = uiConfig.getReasoningOptions(model, settings11);
    const defaultValue = uiConfig.getDefaultReasoningValue(model, settings11);
    const shouldHide = options.length === 0 || options.length === 1 && ((_a3 = options[0]) == null ? void 0 : _a3.value) === defaultValue;
    if (shouldHide) {
      if (this.effortEl) this.effortEl.style.display = "none";
      if (this.budgetEl) this.budgetEl.style.display = "none";
      return;
    }
    const adaptive = uiConfig.isAdaptiveReasoningModel(model, settings11);
    if (this.effortEl) {
      this.effortEl.style.display = adaptive ? "" : "none";
    }
    if (this.budgetEl) {
      this.budgetEl.style.display = adaptive ? "none" : "";
    }
    if (adaptive) {
      this.renderEffortGears();
    } else {
      this.renderBudgetGears();
    }
  }
};
var PermissionToggle = class {
  constructor(parentEl, callbacks) {
    this.toggleEl = null;
    this.labelEl = null;
    this.visible = true;
    this.callbacks = callbacks;
    this.container = parentEl.createDiv({ cls: "claudian-permission-toggle" });
    this.render();
  }
  setVisible(visible) {
    this.visible = visible;
    this.updateDisplay();
  }
  render() {
    this.container.empty();
    this.labelEl = this.container.createSpan({ cls: "claudian-permission-label" });
    this.toggleEl = this.container.createDiv({ cls: "claudian-toggle-switch" });
    this.updateDisplay();
    this.toggleEl.addEventListener("click", () => this.toggle());
  }
  getToggleConfig() {
    var _a3, _b2;
    const uiConfig = this.callbacks.getUIConfig();
    return (_b2 = (_a3 = uiConfig.getPermissionModeToggle) == null ? void 0 : _a3.call(uiConfig)) != null ? _b2 : null;
  }
  updateDisplay() {
    var _a3;
    if (!this.toggleEl || !this.labelEl) return;
    const toggleConfig = this.getToggleConfig();
    const capabilities = this.callbacks.getCapabilities();
    if (!this.visible || !toggleConfig) {
      this.container.style.display = "none";
      return;
    }
    this.container.style.display = "";
    const mode = this.callbacks.getSettings().permissionMode;
    const planValue = toggleConfig.planValue;
    const planLabel = (_a3 = toggleConfig.planLabel) != null ? _a3 : "PLAN";
    const canShowPlan = Boolean(planValue) && capabilities.supportsPlanMode;
    if (canShowPlan && planValue && mode === planValue) {
      this.toggleEl.style.display = "none";
      this.labelEl.setText(planLabel);
      this.labelEl.addClass("plan-active");
    } else {
      this.toggleEl.style.display = "";
      this.labelEl.removeClass("plan-active");
      if (mode === toggleConfig.activeValue) {
        this.toggleEl.addClass("active");
        this.labelEl.setText(toggleConfig.activeLabel);
      } else {
        this.toggleEl.removeClass("active");
        this.labelEl.setText(toggleConfig.inactiveLabel);
      }
    }
  }
  async toggle() {
    const toggleConfig = this.getToggleConfig();
    if (!toggleConfig) return;
    const current = this.callbacks.getSettings().permissionMode;
    const newMode = current === toggleConfig.activeValue ? toggleConfig.inactiveValue : toggleConfig.activeValue;
    await this.callbacks.onPermissionModeChange(newMode);
    this.updateDisplay();
  }
};
var ServiceTierToggle = class {
  constructor(parentEl, callbacks) {
    this.buttonEl = null;
    this.iconEl = null;
    this.callbacks = callbacks;
    this.container = parentEl.createDiv({ cls: "claudian-service-tier-toggle" });
    this.render();
  }
  render() {
    this.container.empty();
    this.buttonEl = this.container.createDiv({ cls: "claudian-service-tier-button" });
    this.iconEl = this.buttonEl.createSpan({ cls: "claudian-service-tier-icon" });
    (0, import_obsidian38.setIcon)(this.iconEl, "zap");
    this.updateDisplay();
    this.buttonEl.addEventListener("click", () => this.toggle());
  }
  getToggleConfig() {
    var _a3, _b2;
    const uiConfig = this.callbacks.getUIConfig();
    return (_b2 = (_a3 = uiConfig.getServiceTierToggle) == null ? void 0 : _a3.call(uiConfig, this.callbacks.getSettings())) != null ? _b2 : null;
  }
  updateDisplay() {
    if (!this.buttonEl || !this.iconEl) return;
    const toggleConfig = this.getToggleConfig();
    if (!toggleConfig) {
      this.container.style.display = "none";
      return;
    }
    this.container.style.display = "";
    const current = this.callbacks.getSettings().serviceTier;
    const isActive = current === toggleConfig.activeValue;
    if (isActive) {
      this.buttonEl.addClass("active");
    } else {
      this.buttonEl.removeClass("active");
    }
    this.container.setAttribute("title", "Toggle on/off fast mode");
  }
  async toggle() {
    const toggleConfig = this.getToggleConfig();
    if (!toggleConfig) return;
    const current = this.callbacks.getSettings().serviceTier;
    const next = current === toggleConfig.activeValue ? toggleConfig.inactiveValue : toggleConfig.activeValue;
    await this.callbacks.onServiceTierChange(next);
    this.updateDisplay();
  }
};
var ExternalContextSelector = class {
  constructor(parentEl, callbacks) {
    this.iconEl = null;
    this.badgeEl = null;
    this.dropdownEl = null;
    /**
     * Current external context paths. May contain:
     * - Persistent paths only (new sessions via clearExternalContexts)
     * - Restored session paths (loaded sessions via setExternalContexts)
     * - Mixed paths during active sessions
     */
    this.externalContextPaths = [];
    /** Paths that persist across all sessions (stored in settings). */
    this.persistentPaths = /* @__PURE__ */ new Set();
    this.onChangeCallback = null;
    this.onPersistenceChangeCallback = null;
    this.callbacks = callbacks;
    this.container = parentEl.createDiv({ cls: "claudian-external-context-selector" });
    this.render();
  }
  setOnChange(callback) {
    this.onChangeCallback = callback;
  }
  setOnPersistenceChange(callback) {
    this.onPersistenceChangeCallback = callback;
  }
  getExternalContexts() {
    return [...this.externalContextPaths];
  }
  getPersistentPaths() {
    return [...this.persistentPaths];
  }
  setPersistentPaths(paths) {
    var _a3;
    const validPaths = filterValidPaths(paths);
    const invalidPaths = paths.filter((p) => !validPaths.includes(p));
    this.persistentPaths = new Set(validPaths);
    this.mergePersistentPaths();
    this.updateDisplay();
    this.renderDropdown();
    if (invalidPaths.length > 0) {
      const pathNames = invalidPaths.map((p) => this.shortenPath(p)).join(", ");
      new import_obsidian38.Notice(`Removed ${invalidPaths.length} invalid external context path(s): ${pathNames}`, 5e3);
      (_a3 = this.onPersistenceChangeCallback) == null ? void 0 : _a3.call(this, [...this.persistentPaths]);
    }
  }
  togglePersistence(path24) {
    var _a3;
    if (this.persistentPaths.has(path24)) {
      this.persistentPaths.delete(path24);
    } else {
      if (!isValidDirectoryPath(path24)) {
        new import_obsidian38.Notice(`Cannot persist "${this.shortenPath(path24)}" - directory no longer exists`, 4e3);
        return;
      }
      this.persistentPaths.add(path24);
    }
    (_a3 = this.onPersistenceChangeCallback) == null ? void 0 : _a3.call(this, [...this.persistentPaths]);
    this.renderDropdown();
  }
  mergePersistentPaths() {
    const pathSet = new Set(this.externalContextPaths);
    for (const path24 of this.persistentPaths) {
      pathSet.add(path24);
    }
    this.externalContextPaths = [...pathSet];
  }
  /**
   * Restore exact external context paths from a saved conversation.
   * Does NOT merge with persistent paths - preserves the session's historical state.
   * Use clearExternalContexts() for new sessions to start with current persistent paths.
   */
  setExternalContexts(paths) {
    this.externalContextPaths = [...paths];
    this.updateDisplay();
    this.renderDropdown();
  }
  /**
   * Remove a path from external contexts (and persistent paths if applicable).
   * Exposed for testing the remove button behavior.
   */
  removePath(pathStr) {
    var _a3, _b2;
    this.externalContextPaths = this.externalContextPaths.filter((p) => p !== pathStr);
    if (this.persistentPaths.has(pathStr)) {
      this.persistentPaths.delete(pathStr);
      (_a3 = this.onPersistenceChangeCallback) == null ? void 0 : _a3.call(this, [...this.persistentPaths]);
    }
    (_b2 = this.onChangeCallback) == null ? void 0 : _b2.call(this, this.externalContextPaths);
    this.updateDisplay();
    this.renderDropdown();
  }
  /**
   * Add an external context path programmatically (e.g., from /add-dir command).
   * Validates the path and handles duplicates/conflicts.
   * @param pathInput - Path string (supports ~/ expansion)
   * @returns Result with success status and normalized path, or error message on failure
   */
  addExternalContext(pathInput) {
    var _a3;
    const trimmed = pathInput == null ? void 0 : pathInput.trim();
    if (!trimmed) {
      return { success: false, error: "No path provided. Usage: /add-dir /absolute/path" };
    }
    let cleanPath = trimmed;
    if (cleanPath.startsWith('"') && cleanPath.endsWith('"') || cleanPath.startsWith("'") && cleanPath.endsWith("'")) {
      cleanPath = cleanPath.slice(1, -1);
    }
    const expandedPath = expandHomePath(cleanPath);
    const normalizedPath = normalizePathForFilesystem(expandedPath);
    if (!path23.isAbsolute(normalizedPath)) {
      return { success: false, error: "Path must be absolute. Usage: /add-dir /absolute/path" };
    }
    const validation = validateDirectoryPath(normalizedPath);
    if (!validation.valid) {
      return { success: false, error: `${validation.error}: ${pathInput}` };
    }
    if (isDuplicatePath(normalizedPath, this.externalContextPaths)) {
      return { success: false, error: "This folder is already added as an external context." };
    }
    const conflict = findConflictingPath(normalizedPath, this.externalContextPaths);
    if (conflict) {
      return { success: false, error: this.formatConflictMessage(normalizedPath, conflict) };
    }
    this.externalContextPaths = [...this.externalContextPaths, normalizedPath];
    (_a3 = this.onChangeCallback) == null ? void 0 : _a3.call(this, this.externalContextPaths);
    this.updateDisplay();
    this.renderDropdown();
    return { success: true, normalizedPath };
  }
  /**
   * Clear session-only external context paths (call on new conversation).
   * Uses persistent paths from settings if provided, otherwise falls back to local cache.
   * Validates paths before using them (silently filters invalid during session init).
   */
  clearExternalContexts(persistentPathsFromSettings) {
    if (persistentPathsFromSettings) {
      const validPaths = filterValidPaths(persistentPathsFromSettings);
      this.persistentPaths = new Set(validPaths);
    }
    this.externalContextPaths = [...this.persistentPaths];
    this.updateDisplay();
    this.renderDropdown();
  }
  render() {
    this.container.empty();
    const iconWrapper = this.container.createDiv({ cls: "claudian-external-context-icon-wrapper" });
    this.iconEl = iconWrapper.createDiv({ cls: "claudian-external-context-icon" });
    (0, import_obsidian38.setIcon)(this.iconEl, "folder");
    this.badgeEl = iconWrapper.createDiv({ cls: "claudian-external-context-badge" });
    this.updateDisplay();
    iconWrapper.addEventListener("click", (e2) => {
      e2.stopPropagation();
      this.openFolderPicker();
    });
    this.dropdownEl = this.container.createDiv({ cls: "claudian-external-context-dropdown" });
    this.renderDropdown();
  }
  async openFolderPicker() {
    var _a3;
    try {
      const { remote } = require("electron");
      const result = await remote.dialog.showOpenDialog({
        properties: ["openDirectory"],
        title: "Select External Context"
      });
      if (!result.canceled && result.filePaths.length > 0) {
        const selectedPath = result.filePaths[0];
        if (isDuplicatePath(selectedPath, this.externalContextPaths)) {
          new import_obsidian38.Notice("This folder is already added as an external context.", 3e3);
          return;
        }
        const conflict = findConflictingPath(selectedPath, this.externalContextPaths);
        if (conflict) {
          new import_obsidian38.Notice(this.formatConflictMessage(selectedPath, conflict), 5e3);
          return;
        }
        this.externalContextPaths = [...this.externalContextPaths, selectedPath];
        (_a3 = this.onChangeCallback) == null ? void 0 : _a3.call(this, this.externalContextPaths);
        this.updateDisplay();
        this.renderDropdown();
      }
    } catch (e2) {
      new import_obsidian38.Notice("Unable to open folder picker.", 5e3);
    }
  }
  /** Formats a conflict error message for display. */
  formatConflictMessage(newPath, conflict) {
    const shortNew = this.shortenPath(newPath);
    const shortExisting = this.shortenPath(conflict.path);
    return conflict.type === "parent" ? `Cannot add "${shortNew}" - it's inside existing path "${shortExisting}"` : `Cannot add "${shortNew}" - it contains existing path "${shortExisting}"`;
  }
  renderDropdown() {
    if (!this.dropdownEl) return;
    this.dropdownEl.empty();
    const headerEl = this.dropdownEl.createDiv({ cls: "claudian-external-context-header" });
    headerEl.setText("External Contexts");
    const listEl = this.dropdownEl.createDiv({ cls: "claudian-external-context-list" });
    if (this.externalContextPaths.length === 0) {
      const emptyEl = listEl.createDiv({ cls: "claudian-external-context-empty" });
      emptyEl.setText("Click folder icon to add");
    } else {
      for (const pathStr of this.externalContextPaths) {
        const itemEl = listEl.createDiv({ cls: "claudian-external-context-item" });
        const pathTextEl = itemEl.createSpan({ cls: "claudian-external-context-text" });
        const displayPath = this.shortenPath(pathStr);
        pathTextEl.setText(displayPath);
        pathTextEl.setAttribute("title", pathStr);
        const isPersistent = this.persistentPaths.has(pathStr);
        const lockBtn = itemEl.createSpan({ cls: "claudian-external-context-lock" });
        if (isPersistent) {
          lockBtn.addClass("locked");
        }
        (0, import_obsidian38.setIcon)(lockBtn, isPersistent ? "lock" : "unlock");
        lockBtn.setAttribute("title", isPersistent ? "Persistent (click to make session-only)" : "Session-only (click to persist)");
        lockBtn.addEventListener("click", (e2) => {
          e2.stopPropagation();
          this.togglePersistence(pathStr);
        });
        const removeBtn = itemEl.createSpan({ cls: "claudian-external-context-remove" });
        (0, import_obsidian38.setIcon)(removeBtn, "x");
        removeBtn.setAttribute("title", "Remove path");
        removeBtn.addEventListener("click", (e2) => {
          e2.stopPropagation();
          this.removePath(pathStr);
        });
      }
    }
  }
  /** Shorten path for display (replace home dir with ~) */
  shortenPath(fullPath) {
    try {
      const os12 = require("os");
      const homeDir = os12.homedir();
      const normalize3 = (value) => value.replace(/\\/g, "/");
      const normalizedFull = normalize3(fullPath);
      const normalizedHome = normalize3(homeDir);
      const compareFull = process.platform === "win32" ? normalizedFull.toLowerCase() : normalizedFull;
      const compareHome = process.platform === "win32" ? normalizedHome.toLowerCase() : normalizedHome;
      if (compareFull.startsWith(compareHome)) {
        const remainder = normalizedFull.slice(normalizedHome.length);
        return "~" + remainder;
      }
    } catch (e2) {
    }
    return fullPath;
  }
  updateDisplay() {
    if (!this.iconEl || !this.badgeEl) return;
    const count = this.externalContextPaths.length;
    if (count > 0) {
      this.iconEl.addClass("active");
      this.iconEl.setAttribute("title", `${count} external context${count > 1 ? "s" : ""} (click to add more)`);
      if (count > 1) {
        this.badgeEl.setText(String(count));
        this.badgeEl.addClass("visible");
      } else {
        this.badgeEl.removeClass("visible");
      }
    } else {
      this.iconEl.removeClass("active");
      this.iconEl.setAttribute("title", "Add external contexts (click)");
      this.badgeEl.removeClass("visible");
    }
  }
};
var McpServerSelector = class {
  constructor(parentEl) {
    this.iconEl = null;
    this.badgeEl = null;
    this.dropdownEl = null;
    this.mcpManager = null;
    this.enabledServers = /* @__PURE__ */ new Set();
    this.onChangeCallback = null;
    this.visible = true;
    this.container = parentEl.createDiv({ cls: "claudian-mcp-selector" });
    this.render();
  }
  setVisible(visible) {
    this.visible = visible;
    if (!visible) {
      this.container.style.display = "none";
    } else {
      this.updateDisplay();
    }
  }
  setMcpManager(manager) {
    var _a3;
    this.mcpManager = manager;
    if (!manager && this.enabledServers.size > 0) {
      this.enabledServers.clear();
      (_a3 = this.onChangeCallback) == null ? void 0 : _a3.call(this, this.enabledServers);
    }
    this.pruneEnabledServers();
    this.updateDisplay();
    this.renderDropdown();
  }
  setOnChange(callback) {
    this.onChangeCallback = callback;
  }
  getEnabledServers() {
    return new Set(this.enabledServers);
  }
  addMentionedServers(names) {
    let changed = false;
    for (const name of names) {
      if (!this.enabledServers.has(name)) {
        this.enabledServers.add(name);
        changed = true;
      }
    }
    if (changed) {
      this.updateDisplay();
      this.renderDropdown();
    }
  }
  clearEnabled() {
    this.enabledServers.clear();
    this.updateDisplay();
    this.renderDropdown();
  }
  setEnabledServers(names) {
    this.enabledServers = new Set(names);
    this.pruneEnabledServers();
    this.updateDisplay();
    this.renderDropdown();
  }
  pruneEnabledServers() {
    var _a3;
    if (!this.mcpManager) return;
    const activeNames = new Set(this.mcpManager.getServers().filter((s4) => s4.enabled).map((s4) => s4.name));
    let changed = false;
    for (const name of this.enabledServers) {
      if (!activeNames.has(name)) {
        this.enabledServers.delete(name);
        changed = true;
      }
    }
    if (changed) {
      (_a3 = this.onChangeCallback) == null ? void 0 : _a3.call(this, this.enabledServers);
    }
  }
  render() {
    this.container.empty();
    const iconWrapper = this.container.createDiv({ cls: "claudian-mcp-selector-icon-wrapper" });
    this.iconEl = iconWrapper.createDiv({ cls: "claudian-mcp-selector-icon" });
    this.iconEl.innerHTML = MCP_ICON_SVG;
    this.badgeEl = iconWrapper.createDiv({ cls: "claudian-mcp-selector-badge" });
    this.updateDisplay();
    this.dropdownEl = this.container.createDiv({ cls: "claudian-mcp-selector-dropdown" });
    this.renderDropdown();
    this.container.addEventListener("mouseenter", () => {
      this.renderDropdown();
    });
  }
  renderDropdown() {
    var _a3;
    if (!this.dropdownEl) return;
    this.pruneEnabledServers();
    this.dropdownEl.empty();
    const headerEl = this.dropdownEl.createDiv({ cls: "claudian-mcp-selector-header" });
    headerEl.setText("MCP Servers");
    const listEl = this.dropdownEl.createDiv({ cls: "claudian-mcp-selector-list" });
    const allServers = ((_a3 = this.mcpManager) == null ? void 0 : _a3.getServers()) || [];
    const servers = allServers.filter((s4) => s4.enabled);
    if (servers.length === 0) {
      const emptyEl = listEl.createDiv({ cls: "claudian-mcp-selector-empty" });
      emptyEl.setText(allServers.length === 0 ? "No MCP servers configured" : "All MCP servers disabled");
      return;
    }
    for (const server of servers) {
      this.renderServerItem(listEl, server);
    }
  }
  renderServerItem(listEl, server) {
    const itemEl = listEl.createDiv({ cls: "claudian-mcp-selector-item" });
    itemEl.dataset.serverName = server.name;
    const isEnabled = this.enabledServers.has(server.name);
    if (isEnabled) {
      itemEl.addClass("enabled");
    }
    const checkEl = itemEl.createDiv({ cls: "claudian-mcp-selector-check" });
    if (isEnabled) {
      checkEl.innerHTML = CHECK_ICON_SVG;
    }
    const infoEl = itemEl.createDiv({ cls: "claudian-mcp-selector-item-info" });
    const nameEl = infoEl.createSpan({ cls: "claudian-mcp-selector-item-name" });
    nameEl.setText(server.name);
    if (server.contextSaving) {
      const csEl = infoEl.createSpan({ cls: "claudian-mcp-selector-cs-badge" });
      csEl.setText("@");
      csEl.setAttribute("title", "Context-saving: can also enable via @" + server.name);
    }
    itemEl.addEventListener("mousedown", (e2) => {
      e2.preventDefault();
      e2.stopPropagation();
      this.toggleServer(server.name, itemEl);
    });
  }
  toggleServer(name, itemEl) {
    var _a3;
    if (this.enabledServers.has(name)) {
      this.enabledServers.delete(name);
    } else {
      this.enabledServers.add(name);
    }
    const isEnabled = this.enabledServers.has(name);
    const checkEl = itemEl.querySelector(".claudian-mcp-selector-check");
    if (isEnabled) {
      itemEl.addClass("enabled");
      if (checkEl) checkEl.innerHTML = CHECK_ICON_SVG;
    } else {
      itemEl.removeClass("enabled");
      if (checkEl) checkEl.innerHTML = "";
    }
    this.updateDisplay();
    (_a3 = this.onChangeCallback) == null ? void 0 : _a3.call(this, this.enabledServers);
  }
  updateDisplay() {
    var _a3;
    this.pruneEnabledServers();
    if (!this.iconEl || !this.badgeEl) return;
    const count = this.enabledServers.size;
    const hasServers = (((_a3 = this.mcpManager) == null ? void 0 : _a3.getServers().length) || 0) > 0;
    if (!hasServers || !this.visible) {
      this.container.style.display = "none";
      return;
    }
    this.container.style.display = "";
    if (count > 0) {
      this.iconEl.addClass("active");
      this.iconEl.setAttribute("title", `${count} MCP server${count > 1 ? "s" : ""} enabled (click to manage)`);
      if (count > 1) {
        this.badgeEl.setText(String(count));
        this.badgeEl.addClass("visible");
      } else {
        this.badgeEl.removeClass("visible");
      }
    } else {
      this.iconEl.removeClass("active");
      this.iconEl.setAttribute("title", "MCP servers (click to enable)");
      this.badgeEl.removeClass("visible");
    }
  }
};
var ContextUsageMeter = class {
  constructor(parentEl) {
    this.fillPath = null;
    this.percentEl = null;
    this.circumference = 0;
    this.container = parentEl.createDiv({ cls: "claudian-context-meter" });
    this.render();
    this.container.style.display = "none";
  }
  setVisible(visible) {
    this.container.style.display = visible ? "" : "none";
  }
  render() {
    const size = 16;
    const strokeWidth = 2;
    const radius = (size - strokeWidth) / 2;
    const cx = size / 2;
    const cy = size / 2;
    const startAngle = 150;
    const endAngle = 390;
    const arcDegrees = endAngle - startAngle;
    const arcRadians = arcDegrees * Math.PI / 180;
    this.circumference = radius * arcRadians;
    const startRad = startAngle * Math.PI / 180;
    const endRad = endAngle * Math.PI / 180;
    const x12 = cx + radius * Math.cos(startRad);
    const y1 = cy + radius * Math.sin(startRad);
    const x22 = cx + radius * Math.cos(endRad);
    const y22 = cy + radius * Math.sin(endRad);
    const gaugeEl = this.container.createDiv({ cls: "claudian-context-meter-gauge" });
    gaugeEl.innerHTML = `
      <svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}">
        <path class="claudian-meter-bg"
          d="M ${x12} ${y1} A ${radius} ${radius} 0 1 1 ${x22} ${y22}"
          fill="none" stroke-width="${strokeWidth}" stroke-linecap="round"/>
        <path class="claudian-meter-fill"
          d="M ${x12} ${y1} A ${radius} ${radius} 0 1 1 ${x22} ${y22}"
          fill="none" stroke-width="${strokeWidth}" stroke-linecap="round"
          stroke-dasharray="${this.circumference}" stroke-dashoffset="${this.circumference}"/>
      </svg>
    `;
    this.fillPath = gaugeEl.querySelector(".claudian-meter-fill");
    this.percentEl = this.container.createSpan({ cls: "claudian-context-meter-percent" });
  }
  update(usage) {
    if (!usage || usage.contextTokens <= 0) {
      this.container.style.display = "none";
      return;
    }
    this.container.style.display = "flex";
    const fillLength = usage.percentage / 100 * this.circumference;
    if (this.fillPath) {
      this.fillPath.style.strokeDashoffset = String(this.circumference - fillLength);
    }
    if (this.percentEl) {
      this.percentEl.setText(`${usage.percentage}%`);
    }
    if (usage.percentage > 80) {
      this.container.addClass("warning");
    } else {
      this.container.removeClass("warning");
    }
    let tooltip = `${this.formatTokens(usage.contextTokens)} / ${this.formatTokens(usage.contextWindow)}`;
    if (usage.percentage > 80) {
      tooltip += " (Approaching limit, run `/compact` to continue)";
    }
    this.container.setAttribute("data-tooltip", tooltip);
  }
  formatTokens(tokens) {
    if (tokens >= 1e3) {
      return `${Math.round(tokens / 1e3)}k`;
    }
    return String(tokens);
  }
};
function createInputToolbar(parentEl, callbacks) {
  const modelSelector = new ModelSelector(parentEl, callbacks);
  const thinkingBudgetSelector = new ThinkingBudgetSelector(parentEl, callbacks);
  const serviceTierToggle = new ServiceTierToggle(parentEl, callbacks);
  const contextUsageMeter = new ContextUsageMeter(parentEl);
  const externalContextSelector = new ExternalContextSelector(parentEl, callbacks);
  const mcpServerSelector = new McpServerSelector(parentEl);
  const permissionToggle = new PermissionToggle(parentEl, callbacks);
  const modeSelector = new ModeSelector(parentEl, callbacks);
  return {
    modelSelector,
    modeSelector,
    thinkingBudgetSelector,
    serviceTierToggle,
    contextUsageMeter,
    externalContextSelector,
    mcpServerSelector,
    permissionToggle
  };
}

// src/features/chat/ui/InstructionModeManager.ts
var INSTRUCTION_MODE_PLACEHOLDER = "# Save in custom system prompt";
var InstructionModeManager = class {
  constructor(inputEl, callbacks) {
    this.state = { active: false, rawInstruction: "" };
    this.isSubmitting = false;
    this.originalPlaceholder = "";
    this.inputEl = inputEl;
    this.callbacks = callbacks;
    this.originalPlaceholder = inputEl.placeholder;
  }
  /**
   * Handles keydown to detect # trigger.
   * Returns true if the event was consumed (should prevent default).
   */
  handleTriggerKey(e2) {
    if (!this.state.active && this.inputEl.value === "" && e2.key === "#") {
      if (this.enterMode()) {
        e2.preventDefault();
        return true;
      }
    }
    return false;
  }
  /** Handles input changes to track instruction text. */
  handleInputChange() {
    if (!this.state.active) return;
    const text = this.inputEl.value;
    if (text === "") {
      this.exitMode();
    } else {
      this.state.rawInstruction = text;
    }
  }
  /**
   * Enters instruction mode.
   * Only enters if the indicator can be successfully shown.
   * Returns true if mode was entered, false otherwise.
   */
  enterMode() {
    const wrapper = this.callbacks.getInputWrapper();
    if (!wrapper) return false;
    wrapper.addClass("claudian-input-instruction-mode");
    this.state = { active: true, rawInstruction: "" };
    this.inputEl.placeholder = INSTRUCTION_MODE_PLACEHOLDER;
    return true;
  }
  /** Exits instruction mode, restoring original state. */
  exitMode() {
    const wrapper = this.callbacks.getInputWrapper();
    if (wrapper) {
      wrapper.removeClass("claudian-input-instruction-mode");
    }
    this.state = { active: false, rawInstruction: "" };
    this.inputEl.placeholder = this.originalPlaceholder;
  }
  /** Handles keydown events. Returns true if handled. */
  handleKeydown(e2) {
    if (!this.state.active) return false;
    if (e2.key === "Enter" && !e2.shiftKey && !e2.isComposing) {
      if (!this.state.rawInstruction.trim()) {
        return false;
      }
      e2.preventDefault();
      this.submit();
      return true;
    }
    if (e2.key === "Escape" && !e2.isComposing) {
      e2.preventDefault();
      this.cancel();
      return true;
    }
    return false;
  }
  /** Checks if instruction mode is active. */
  isActive() {
    return this.state.active;
  }
  /** Gets the current raw instruction text. */
  getRawInstruction() {
    return this.state.rawInstruction;
  }
  /** Submits the instruction for refinement. */
  async submit() {
    if (this.isSubmitting) return;
    const rawInstruction = this.state.rawInstruction.trim();
    if (!rawInstruction) return;
    this.isSubmitting = true;
    try {
      await this.callbacks.onSubmit(rawInstruction);
    } finally {
      this.isSubmitting = false;
    }
  }
  /** Cancels instruction mode and clears input. */
  cancel() {
    var _a3, _b2;
    this.inputEl.value = "";
    this.exitMode();
    (_b2 = (_a3 = this.callbacks).resetInputHeight) == null ? void 0 : _b2.call(_a3);
  }
  /** Clears the input and resets state (called after successful submission). */
  clear() {
    var _a3, _b2;
    this.inputEl.value = "";
    this.exitMode();
    (_b2 = (_a3 = this.callbacks).resetInputHeight) == null ? void 0 : _b2.call(_a3);
  }
  /** Cleans up event listeners. */
  destroy() {
    const wrapper = this.callbacks.getInputWrapper();
    if (wrapper) {
      wrapper.removeClass("claudian-input-instruction-mode");
    }
    this.inputEl.placeholder = this.originalPlaceholder;
  }
};

// src/features/chat/ui/NavigationSidebar.ts
var import_obsidian39 = require("obsidian");
var NavigationSidebar = class {
  constructor(parentEl, messagesEl) {
    this.parentEl = parentEl;
    this.messagesEl = messagesEl;
    this.scrollHandler = () => {
    };
    this.pendingVisibilityFrame = null;
    this.isVisible = null;
    this.container = this.parentEl.createDiv({ cls: "claudian-nav-sidebar" });
    this.topBtn = this.createButton("claudian-nav-btn-top", "chevrons-up", "Scroll to top");
    this.prevBtn = this.createButton("claudian-nav-btn-prev", "chevron-up", "Previous message");
    this.nextBtn = this.createButton("claudian-nav-btn-next", "chevron-down", "Next message");
    this.bottomBtn = this.createButton("claudian-nav-btn-bottom", "chevrons-down", "Scroll to bottom");
    this.setupEventListeners();
    this.applyVisibility();
  }
  createButton(cls, icon, label) {
    const btn = this.container.createDiv({ cls: `claudian-nav-btn ${cls}` });
    (0, import_obsidian39.setIcon)(btn, icon);
    btn.setAttribute("aria-label", label);
    return btn;
  }
  setupEventListeners() {
    this.scrollHandler = () => this.updateVisibility();
    this.messagesEl.addEventListener("scroll", this.scrollHandler, { passive: true });
    this.topBtn.addEventListener("click", () => {
      this.messagesEl.scrollTo({ top: 0, behavior: "smooth" });
    });
    this.bottomBtn.addEventListener("click", () => {
      this.messagesEl.scrollTo({ top: this.messagesEl.scrollHeight, behavior: "smooth" });
    });
    this.prevBtn.addEventListener("click", () => this.scrollToMessage("prev"));
    this.nextBtn.addEventListener("click", () => this.scrollToMessage("next"));
  }
  /**
   * Updates visibility of the sidebar based on scroll state.
   * Visible if content overflows.
   */
  updateVisibility() {
    if (this.pendingVisibilityFrame !== null) return;
    this.pendingVisibilityFrame = scheduleAnimationFrame(() => {
      this.pendingVisibilityFrame = null;
      this.applyVisibility();
    });
  }
  applyVisibility() {
    const { scrollHeight, clientHeight } = this.messagesEl;
    const isScrollable = scrollHeight > clientHeight + 50;
    if (this.isVisible === isScrollable) return;
    this.isVisible = isScrollable;
    this.container.classList.toggle("visible", isScrollable);
  }
  /**
   * Scrolls to previous or next user message, skipping assistant messages.
   */
  scrollToMessage(direction) {
    const messages = Array.from(this.messagesEl.querySelectorAll(".claudian-message-user"));
    if (messages.length === 0) return;
    const scrollTop = this.messagesEl.scrollTop;
    const threshold = 30;
    if (direction === "prev") {
      for (let i2 = messages.length - 1; i2 >= 0; i2--) {
        if (messages[i2].offsetTop < scrollTop - threshold) {
          this.messagesEl.scrollTo({ top: messages[i2].offsetTop - 10, behavior: "smooth" });
          return;
        }
      }
      this.messagesEl.scrollTo({ top: 0, behavior: "smooth" });
    } else {
      for (let i2 = 0; i2 < messages.length; i2++) {
        if (messages[i2].offsetTop > scrollTop + threshold) {
          this.messagesEl.scrollTo({ top: messages[i2].offsetTop - 10, behavior: "smooth" });
          return;
        }
      }
      this.messagesEl.scrollTo({ top: this.messagesEl.scrollHeight, behavior: "smooth" });
    }
  }
  destroy() {
    if (this.pendingVisibilityFrame !== null) {
      cancelScheduledAnimationFrame(this.pendingVisibilityFrame);
      this.pendingVisibilityFrame = null;
    }
    this.messagesEl.removeEventListener("scroll", this.scrollHandler);
    this.container.remove();
  }
};

// src/features/chat/ui/StatusPanel.ts
var import_obsidian40 = require("obsidian");
var MAX_BASH_OUTPUTS = 50;
var StatusPanel = class {
  constructor() {
    this.containerEl = null;
    this.panelEl = null;
    // Bash output section
    this.bashOutputContainerEl = null;
    this.bashHeaderEl = null;
    this.bashContentEl = null;
    this.isBashExpanded = true;
    this.currentBashOutputs = /* @__PURE__ */ new Map();
    this.bashEntryExpanded = /* @__PURE__ */ new Map();
    // Todo section
    this.todoContainerEl = null;
    this.todoHeaderEl = null;
    this.todoContentEl = null;
    this.isTodoExpanded = false;
    this.currentTodos = null;
    // Event handler references for cleanup
    this.todoClickHandler = null;
    this.todoKeydownHandler = null;
    this.bashClickHandler = null;
    this.bashKeydownHandler = null;
  }
  /**
   * Mount the panel into the messages container.
   * Appends to the end of the messages area.
   */
  mount(containerEl) {
    this.containerEl = containerEl;
    this.createPanel();
  }
  /**
   * Remount the panel to restore state after conversation changes.
   * Re-creates the panel structure and re-renders current state.
   */
  remount() {
    if (!this.containerEl) {
      return;
    }
    if (this.todoHeaderEl) {
      if (this.todoClickHandler) {
        this.todoHeaderEl.removeEventListener("click", this.todoClickHandler);
      }
      if (this.todoKeydownHandler) {
        this.todoHeaderEl.removeEventListener("keydown", this.todoKeydownHandler);
      }
    }
    this.todoClickHandler = null;
    this.todoKeydownHandler = null;
    if (this.bashHeaderEl) {
      if (this.bashClickHandler) {
        this.bashHeaderEl.removeEventListener("click", this.bashClickHandler);
      }
      if (this.bashKeydownHandler) {
        this.bashHeaderEl.removeEventListener("keydown", this.bashKeydownHandler);
      }
    }
    this.bashClickHandler = null;
    this.bashKeydownHandler = null;
    if (this.panelEl) {
      this.panelEl.remove();
    }
    this.panelEl = null;
    this.bashOutputContainerEl = null;
    this.bashHeaderEl = null;
    this.bashContentEl = null;
    this.todoContainerEl = null;
    this.todoHeaderEl = null;
    this.todoContentEl = null;
    this.createPanel();
    this.renderBashOutputs();
    if (this.currentTodos && this.currentTodos.length > 0) {
      this.updateTodos(this.currentTodos);
    }
  }
  /**
   * Create the panel structure.
   */
  createPanel() {
    if (!this.containerEl) {
      return;
    }
    this.panelEl = document.createElement("div");
    this.panelEl.className = "claudian-status-panel";
    this.bashOutputContainerEl = document.createElement("div");
    this.bashOutputContainerEl.className = "claudian-status-panel-bash";
    this.bashOutputContainerEl.style.display = "none";
    this.bashHeaderEl = document.createElement("div");
    this.bashHeaderEl.className = "claudian-tool-header claudian-status-panel-bash-header";
    this.bashHeaderEl.setAttribute("tabindex", "0");
    this.bashHeaderEl.setAttribute("role", "button");
    this.bashClickHandler = () => this.toggleBashSection();
    this.bashKeydownHandler = (e2) => {
      if (e2.key === "Enter" || e2.key === " ") {
        e2.preventDefault();
        this.toggleBashSection();
      }
    };
    this.bashHeaderEl.addEventListener("click", this.bashClickHandler);
    this.bashHeaderEl.addEventListener("keydown", this.bashKeydownHandler);
    this.bashContentEl = document.createElement("div");
    this.bashContentEl.className = "claudian-status-panel-bash-content";
    this.bashOutputContainerEl.appendChild(this.bashHeaderEl);
    this.bashOutputContainerEl.appendChild(this.bashContentEl);
    this.panelEl.appendChild(this.bashOutputContainerEl);
    this.todoContainerEl = document.createElement("div");
    this.todoContainerEl.className = "claudian-status-panel-todos";
    this.todoContainerEl.style.display = "none";
    this.panelEl.appendChild(this.todoContainerEl);
    this.todoHeaderEl = document.createElement("div");
    this.todoHeaderEl.className = "claudian-status-panel-header";
    this.todoHeaderEl.setAttribute("tabindex", "0");
    this.todoHeaderEl.setAttribute("role", "button");
    this.todoClickHandler = () => this.toggleTodos();
    this.todoKeydownHandler = (e2) => {
      if (e2.key === "Enter" || e2.key === " ") {
        e2.preventDefault();
        this.toggleTodos();
      }
    };
    this.todoHeaderEl.addEventListener("click", this.todoClickHandler);
    this.todoHeaderEl.addEventListener("keydown", this.todoKeydownHandler);
    this.todoContainerEl.appendChild(this.todoHeaderEl);
    this.todoContentEl = document.createElement("div");
    this.todoContentEl.className = "claudian-status-panel-content claudian-todo-list-container";
    this.todoContentEl.style.display = "none";
    this.todoContainerEl.appendChild(this.todoContentEl);
    this.containerEl.appendChild(this.panelEl);
  }
  /**
   * Update the panel with new todo items.
   * Called by ChatState.onTodosChanged callback when TodoWrite tool is used.
   * Passing null or empty array hides the panel.
   */
  updateTodos(todos) {
    if (!this.todoContainerEl || !this.todoHeaderEl || !this.todoContentEl) {
      return;
    }
    this.currentTodos = todos;
    if (!todos || todos.length === 0) {
      this.todoContainerEl.style.display = "none";
      this.todoHeaderEl.empty();
      this.todoContentEl.empty();
      return;
    }
    this.todoContainerEl.style.display = "block";
    const completedCount = todos.filter((t2) => t2.status === "completed").length;
    const totalCount = todos.length;
    const currentTask = todos.find((t2) => t2.status === "in_progress");
    this.renderTodoHeader(completedCount, totalCount, currentTask);
    this.renderTodoContent(todos);
    this.updateTodoAriaLabel(completedCount, totalCount);
    this.scrollToBottom();
  }
  /**
   * Render the todo collapsed header.
   */
  renderTodoHeader(completedCount, totalCount, currentTask) {
    if (!this.todoHeaderEl) return;
    this.todoHeaderEl.empty();
    const icon = document.createElement("span");
    icon.className = "claudian-status-panel-icon";
    (0, import_obsidian40.setIcon)(icon, getToolIcon(TOOL_TODO_WRITE));
    this.todoHeaderEl.appendChild(icon);
    const label = document.createElement("span");
    label.className = "claudian-status-panel-label";
    label.textContent = `Tasks (${completedCount}/${totalCount})`;
    this.todoHeaderEl.appendChild(label);
    if (!this.isTodoExpanded) {
      if (completedCount === totalCount && totalCount > 0) {
        const status = document.createElement("span");
        status.className = "claudian-status-panel-status status-completed";
        (0, import_obsidian40.setIcon)(status, "check");
        this.todoHeaderEl.appendChild(status);
      }
      if (currentTask) {
        const current = document.createElement("span");
        current.className = "claudian-status-panel-current";
        current.textContent = currentTask.activeForm;
        this.todoHeaderEl.appendChild(current);
      }
    }
  }
  /**
   * Render the expanded todo content.
   */
  renderTodoContent(todos) {
    if (!this.todoContentEl) return;
    renderTodoItems(this.todoContentEl, todos);
  }
  /**
   * Toggle todo expanded/collapsed state.
   */
  toggleTodos() {
    this.isTodoExpanded = !this.isTodoExpanded;
    this.updateTodoDisplay();
  }
  /**
   * Update todo display based on expanded state.
   */
  updateTodoDisplay() {
    if (!this.todoContentEl || !this.todoHeaderEl) return;
    this.todoContentEl.style.display = this.isTodoExpanded ? "block" : "none";
    if (this.currentTodos && this.currentTodos.length > 0) {
      const completedCount = this.currentTodos.filter((t2) => t2.status === "completed").length;
      const totalCount = this.currentTodos.length;
      const currentTask = this.currentTodos.find((t2) => t2.status === "in_progress");
      this.renderTodoHeader(completedCount, totalCount, currentTask);
      this.updateTodoAriaLabel(completedCount, totalCount);
    }
    this.scrollToBottom();
  }
  /**
   * Update todo ARIA label.
   */
  updateTodoAriaLabel(completedCount, totalCount) {
    if (!this.todoHeaderEl) return;
    const action = this.isTodoExpanded ? "Collapse" : "Expand";
    this.todoHeaderEl.setAttribute(
      "aria-label",
      `${action} task list - ${completedCount} of ${totalCount} completed`
    );
    this.todoHeaderEl.setAttribute("aria-expanded", String(this.isTodoExpanded));
  }
  /**
   * Scroll messages container to bottom.
   */
  scrollToBottom() {
    if (this.containerEl) {
      this.containerEl.scrollTop = this.containerEl.scrollHeight;
    }
  }
  // ============================================
  // Bash Output Methods
  // ============================================
  truncateDescription(description, maxLength = 50) {
    if (description.length <= maxLength) return description;
    return description.substring(0, maxLength) + "...";
  }
  addBashOutput(info) {
    this.currentBashOutputs.set(info.id, info);
    while (this.currentBashOutputs.size > MAX_BASH_OUTPUTS) {
      const oldest = this.currentBashOutputs.keys().next().value;
      if (!oldest) break;
      this.currentBashOutputs.delete(oldest);
      this.bashEntryExpanded.delete(oldest);
    }
    this.renderBashOutputs();
  }
  updateBashOutput(id, updates) {
    const existing = this.currentBashOutputs.get(id);
    if (!existing) return;
    this.currentBashOutputs.set(id, { ...existing, ...updates });
    this.renderBashOutputs();
  }
  clearBashOutputs() {
    this.currentBashOutputs.clear();
    this.bashEntryExpanded.clear();
    this.renderBashOutputs();
  }
  renderBashOutputs(options = {}) {
    var _a3;
    if (!this.bashOutputContainerEl || !this.bashHeaderEl || !this.bashContentEl) return;
    const scroll = (_a3 = options.scroll) != null ? _a3 : true;
    if (this.currentBashOutputs.size === 0) {
      this.bashOutputContainerEl.style.display = "none";
      return;
    }
    this.bashOutputContainerEl.style.display = "block";
    this.bashHeaderEl.empty();
    this.bashContentEl.empty();
    const headerIconEl = document.createElement("span");
    headerIconEl.className = "claudian-tool-icon";
    headerIconEl.setAttribute("aria-hidden", "true");
    (0, import_obsidian40.setIcon)(headerIconEl, "terminal");
    this.bashHeaderEl.appendChild(headerIconEl);
    const latest = Array.from(this.currentBashOutputs.values()).at(-1);
    const headerLabelEl = document.createElement("span");
    headerLabelEl.className = "claudian-tool-label";
    if (this.isBashExpanded) {
      headerLabelEl.textContent = t("chat.bangBash.commandPanel");
    } else {
      headerLabelEl.textContent = latest ? this.truncateDescription(latest.command, 60) : t("chat.bangBash.commandPanel");
    }
    this.bashHeaderEl.appendChild(headerLabelEl);
    const previewEl = document.createElement("span");
    previewEl.className = "claudian-tool-current";
    previewEl.style.display = this.isBashExpanded ? "" : "none";
    this.bashHeaderEl.appendChild(previewEl);
    const summaryStatusEl = document.createElement("span");
    summaryStatusEl.className = "claudian-tool-status";
    if (!this.isBashExpanded && latest) {
      summaryStatusEl.classList.add(`status-${latest.status}`);
      summaryStatusEl.setAttribute("aria-label", t("chat.bangBash.statusLabel", { status: latest.status }));
      if (latest.status === "completed") (0, import_obsidian40.setIcon)(summaryStatusEl, "check");
      if (latest.status === "error") (0, import_obsidian40.setIcon)(summaryStatusEl, "x");
    } else {
      summaryStatusEl.style.display = "none";
    }
    this.bashHeaderEl.appendChild(summaryStatusEl);
    this.bashHeaderEl.setAttribute("aria-expanded", String(this.isBashExpanded));
    const actionsEl = document.createElement("span");
    actionsEl.className = "claudian-status-panel-bash-actions";
    this.appendActionButton(actionsEl, "copy", t("chat.bangBash.copyAriaLabel"), "copy", () => {
      void this.copyLatestBashOutput();
    });
    this.appendActionButton(actionsEl, "clear", t("chat.bangBash.clearAriaLabel"), "trash", () => {
      this.clearBashOutputs();
    });
    this.bashHeaderEl.appendChild(actionsEl);
    this.bashContentEl.style.display = this.isBashExpanded ? "block" : "none";
    if (!this.isBashExpanded) {
      return;
    }
    for (const info of this.currentBashOutputs.values()) {
      this.bashContentEl.appendChild(this.renderBashEntry(info));
    }
    if (scroll) {
      this.bashContentEl.scrollTop = this.bashContentEl.scrollHeight;
      this.scrollToBottom();
    }
  }
  renderBashEntry(info) {
    var _a3;
    const entryEl = document.createElement("div");
    entryEl.className = "claudian-tool-call claudian-status-panel-bash-entry";
    const entryHeaderEl = document.createElement("div");
    entryHeaderEl.className = "claudian-tool-header";
    entryHeaderEl.setAttribute("tabindex", "0");
    entryHeaderEl.setAttribute("role", "button");
    const entryIconEl = document.createElement("span");
    entryIconEl.className = "claudian-tool-icon";
    entryIconEl.setAttribute("aria-hidden", "true");
    (0, import_obsidian40.setIcon)(entryIconEl, "dollar-sign");
    entryHeaderEl.appendChild(entryIconEl);
    const entryLabelEl = document.createElement("span");
    entryLabelEl.className = "claudian-tool-label";
    entryLabelEl.textContent = t("chat.bangBash.commandLabel", { command: this.truncateDescription(info.command, 60) });
    entryHeaderEl.appendChild(entryLabelEl);
    const entryStatusEl = document.createElement("span");
    entryStatusEl.className = "claudian-tool-status";
    entryStatusEl.classList.add(`status-${info.status}`);
    entryStatusEl.setAttribute("aria-label", t("chat.bangBash.statusLabel", { status: info.status }));
    if (info.status === "completed") (0, import_obsidian40.setIcon)(entryStatusEl, "check");
    if (info.status === "error") (0, import_obsidian40.setIcon)(entryStatusEl, "x");
    entryHeaderEl.appendChild(entryStatusEl);
    entryEl.appendChild(entryHeaderEl);
    const contentEl = document.createElement("div");
    contentEl.className = "claudian-tool-content";
    const isEntryExpanded = (_a3 = this.bashEntryExpanded.get(info.id)) != null ? _a3 : true;
    contentEl.style.display = isEntryExpanded ? "block" : "none";
    entryHeaderEl.setAttribute("aria-expanded", String(isEntryExpanded));
    entryHeaderEl.setAttribute("aria-label", isEntryExpanded ? t("chat.bangBash.collapseOutput") : t("chat.bangBash.expandOutput"));
    entryHeaderEl.addEventListener("click", () => {
      this.bashEntryExpanded.set(info.id, !isEntryExpanded);
      this.renderBashOutputs({ scroll: false });
    });
    entryHeaderEl.addEventListener("keydown", (e2) => {
      if (e2.key === "Enter" || e2.key === " ") {
        e2.preventDefault();
        this.bashEntryExpanded.set(info.id, !isEntryExpanded);
        this.renderBashOutputs({ scroll: false });
      }
    });
    const rowEl = document.createElement("div");
    rowEl.className = "claudian-tool-result-row";
    const textEl = document.createElement("span");
    textEl.className = "claudian-tool-result-text";
    if (info.status === "running" && !info.output) {
      textEl.textContent = t("chat.bangBash.running");
    } else if (info.output) {
      textEl.textContent = info.output;
    }
    rowEl.appendChild(textEl);
    contentEl.appendChild(rowEl);
    entryEl.appendChild(contentEl);
    return entryEl;
  }
  async copyLatestBashOutput() {
    var _a3;
    const latest = Array.from(this.currentBashOutputs.values()).at(-1);
    if (!latest) return;
    const output = ((_a3 = latest.output) == null ? void 0 : _a3.trim()) || (latest.status === "running" ? t("chat.bangBash.running") : "");
    const text = output ? `$ ${latest.command}
${output}` : `$ ${latest.command}`;
    try {
      await navigator.clipboard.writeText(text);
    } catch (e2) {
      new import_obsidian40.Notice(t("chat.bangBash.copyFailed"));
    }
  }
  appendActionButton(parent, name, ariaLabel, icon, action) {
    const el = document.createElement("span");
    el.className = `claudian-status-panel-bash-action claudian-status-panel-bash-action-${name}`;
    el.setAttribute("role", "button");
    el.setAttribute("tabindex", "0");
    el.setAttribute("aria-label", ariaLabel);
    (0, import_obsidian40.setIcon)(el, icon);
    el.addEventListener("click", (e2) => {
      e2.stopPropagation();
      action();
    });
    el.addEventListener("keydown", (e2) => {
      if (e2.key === "Enter" || e2.key === " ") {
        e2.preventDefault();
        e2.stopPropagation();
        action();
      }
    });
    parent.appendChild(el);
  }
  toggleBashSection() {
    this.isBashExpanded = !this.isBashExpanded;
    this.renderBashOutputs({ scroll: false });
  }
  // ============================================
  // Cleanup
  // ============================================
  /**
   * Destroy the panel.
   */
  destroy() {
    if (this.todoHeaderEl) {
      if (this.todoClickHandler) {
        this.todoHeaderEl.removeEventListener("click", this.todoClickHandler);
      }
      if (this.todoKeydownHandler) {
        this.todoHeaderEl.removeEventListener("keydown", this.todoKeydownHandler);
      }
    }
    this.todoClickHandler = null;
    this.todoKeydownHandler = null;
    if (this.bashHeaderEl) {
      if (this.bashClickHandler) {
        this.bashHeaderEl.removeEventListener("click", this.bashClickHandler);
      }
      if (this.bashKeydownHandler) {
        this.bashHeaderEl.removeEventListener("keydown", this.bashKeydownHandler);
      }
    }
    this.bashClickHandler = null;
    this.bashKeydownHandler = null;
    this.currentBashOutputs.clear();
    if (this.panelEl) {
      this.panelEl.remove();
      this.panelEl = null;
    }
    this.bashOutputContainerEl = null;
    this.bashHeaderEl = null;
    this.bashContentEl = null;
    this.todoContainerEl = null;
    this.todoHeaderEl = null;
    this.todoContentEl = null;
    this.containerEl = null;
    this.currentTodos = null;
  }
};

// src/features/chat/utils/usageInfo.ts
function calculateUsagePercentage(contextTokens, contextWindow) {
  return contextWindow > 0 ? Math.min(100, Math.max(0, Math.round(contextTokens / contextWindow * 100))) : 0;
}
function recalculateUsageForModel(usage, model, fallbackContextWindow) {
  const preserveAuthoritativeWindow = usage.contextWindowIsAuthoritative === true && usage.contextWindow > 0 && usage.model === model;
  const contextWindow = preserveAuthoritativeWindow ? usage.contextWindow : fallbackContextWindow;
  return {
    ...usage,
    model,
    contextWindow,
    contextWindowIsAuthoritative: preserveAuthoritativeWindow,
    percentage: calculateUsagePercentage(usage.contextTokens, contextWindow)
  };
}

// src/features/chat/tabs/providerResolution.ts
function getStoredConversationProviderId(tab, plugin) {
  var _a3, _b2;
  if (tab.conversationId) {
    const conversation = plugin.getConversationSync(tab.conversationId);
    if (conversation == null ? void 0 : conversation.providerId) {
      return conversation.providerId;
    }
  }
  if (tab.lifecycleState === "blank" && tab.draftModel) {
    return getEnabledProviderForModel(
      tab.draftModel,
      plugin.settings
    );
  }
  return (_b2 = (_a3 = tab.service) == null ? void 0 : _a3.providerId) != null ? _b2 : tab.providerId;
}
function getTabProviderId(tab, plugin, conversation) {
  var _a3;
  return (_a3 = conversation == null ? void 0 : conversation.providerId) != null ? _a3 : getStoredConversationProviderId(tab, plugin);
}

// src/features/chat/tabs/types.ts
var DEFAULT_MAX_TABS = 3;
var MIN_TABS = 3;
var MAX_TABS = 10;
var TEXTAREA_MIN_MAX_HEIGHT = 150;
var TEXTAREA_MAX_HEIGHT_PERCENT = 0.55;
function generateTabId() {
  return `tab-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
}

// src/features/chat/tabs/Tab.ts
function getBlankTabModelOptions(settings11) {
  return ProviderRegistry.getEnabledProviderIds(settings11).flatMap((providerId) => {
    var _a3, _b2;
    const uiConfig = ProviderRegistry.getChatUIConfig(providerId);
    const providerIcon = (_b2 = (_a3 = uiConfig.getProviderIcon) == null ? void 0 : _a3.call(uiConfig)) != null ? _b2 : void 0;
    const group = ProviderRegistry.getProviderDisplayName(providerId);
    return uiConfig.getModelOptions(settings11).map((model) => ({ ...model, group, providerIcon }));
  });
}
function resolveBlankTabModel(plugin, providerId) {
  const settings11 = plugin.settings;
  if (!providerId) {
    return settings11.model;
  }
  const targetProviderId = ProviderRegistry.isEnabled(providerId, settings11) ? providerId : ProviderRegistry.resolveSettingsProviderId(settings11);
  const snapshot = ProviderSettingsCoordinator.getProviderSettingsSnapshot(settings11, targetProviderId);
  return snapshot.model;
}
function getTabCapabilities(tab, plugin, conversation) {
  var _a3;
  const providerId = getTabProviderId(tab, plugin, conversation);
  if (((_a3 = tab.service) == null ? void 0 : _a3.providerId) === providerId) {
    return tab.service.getCapabilities();
  }
  return ProviderRegistry.getCapabilities(providerId);
}
function getTabChatUIConfig(tab, plugin, conversation) {
  return ProviderRegistry.getChatUIConfig(getTabProviderId(tab, plugin, conversation));
}
function getTabSettingsSnapshot(tab, plugin) {
  return ProviderSettingsCoordinator.getProviderSettingsSnapshot(
    plugin.settings,
    getTabProviderId(tab, plugin)
  );
}
function getTabPermissionMode(tab, plugin) {
  const permissionMode = getTabSettingsSnapshot(tab, plugin).permissionMode;
  return typeof permissionMode === "string" && permissionMode ? permissionMode : "normal";
}
function getTabHiddenCommands(tab, plugin, conversation) {
  return getHiddenProviderCommandSet(
    plugin.settings,
    getTabProviderId(tab, plugin, conversation)
  );
}
function getRegistryProviderCatalogInfo(providerId) {
  const catalog = ProviderWorkspaceRegistry.getCommandCatalog(providerId);
  if (!catalog) {
    return null;
  }
  return {
    config: catalog.getDropdownConfig(),
    getEntries: () => catalog.listDropdownEntries({ includeBuiltIns: false })
  };
}
function getProviderMcpManager(providerId) {
  return ProviderWorkspaceRegistry.getMcpServerManager(providerId);
}
function syncSlashCommandDropdownForProvider(tab, plugin, getProviderCatalogConfig, conversation) {
  var _a3, _b2;
  const dropdown = tab.ui.slashCommandDropdown;
  if (!dropdown) {
    return;
  }
  const catalogInfo = (_a3 = getProviderCatalogConfig == null ? void 0 : getProviderCatalogConfig()) != null ? _a3 : getRegistryProviderCatalogInfo(getTabProviderId(tab, plugin, conversation));
  if (catalogInfo) {
    (_b2 = dropdown.setProviderCatalog) == null ? void 0 : _b2.call(dropdown, catalogInfo.config, catalogInfo.getEntries);
  } else {
    dropdown.resetSdkSkillsCache();
  }
  dropdown.setHiddenCommands(getTabHiddenCommands(tab, plugin, conversation));
}
async function updateTabProviderSettings(tab, plugin, update) {
  const providerId = getTabProviderId(tab, plugin);
  const snapshot = getTabSettingsSnapshot(tab, plugin);
  update(snapshot);
  ProviderSettingsCoordinator.commitProviderSettingsSnapshot(
    plugin.settings,
    providerId,
    snapshot
  );
  await plugin.saveSettings();
  return snapshot;
}
function refreshTabProviderUI(tab, plugin) {
  var _a3, _b2, _c, _d2, _e, _f, _g;
  const capabilities = getTabCapabilities(tab, plugin);
  const permissionMode = getTabPermissionMode(tab, plugin);
  (_a3 = tab.ui.modelSelector) == null ? void 0 : _a3.updateDisplay();
  (_b2 = tab.ui.modelSelector) == null ? void 0 : _b2.renderOptions();
  (_c = tab.ui.modeSelector) == null ? void 0 : _c.updateDisplay();
  (_d2 = tab.ui.modeSelector) == null ? void 0 : _d2.renderOptions();
  (_e = tab.ui.thinkingBudgetSelector) == null ? void 0 : _e.updateDisplay();
  (_f = tab.ui.permissionToggle) == null ? void 0 : _f.updateDisplay();
  (_g = tab.ui.serviceTierToggle) == null ? void 0 : _g.updateDisplay();
  tab.dom.inputWrapper.toggleClass(
    "claudian-input-plan-mode",
    permissionMode === "plan" && capabilities.supportsPlanMode
  );
}
function applyProviderUIGating(tab, plugin) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h;
  const capabilities = getTabCapabilities(tab, plugin);
  const uiConfig = getTabChatUIConfig(tab, plugin);
  const mcpManager = capabilities.supportsMcpTools ? getProviderMcpManager(capabilities.providerId) : null;
  const hasPermissionToggle = Boolean((_a3 = uiConfig.getPermissionModeToggle) == null ? void 0 : _a3.call(uiConfig));
  if (!capabilities.supportsMcpTools) {
    (_b2 = tab.ui.mcpServerSelector) == null ? void 0 : _b2.clearEnabled();
  }
  (_c = tab.ui.mcpServerSelector) == null ? void 0 : _c.setVisible(capabilities.supportsMcpTools);
  (_d2 = tab.ui.permissionToggle) == null ? void 0 : _d2.setVisible(hasPermissionToggle);
  (_e = tab.ui.fileContextManager) == null ? void 0 : _e.setMcpManager(mcpManager);
  (_f = tab.ui.fileContextManager) == null ? void 0 : _f.setAgentService(
    ProviderWorkspaceRegistry.getAgentMentionProvider(capabilities.providerId)
  );
  (_g = tab.ui.imageContextManager) == null ? void 0 : _g.setEnabled(capabilities.supportsImageAttachments);
  (_h = tab.ui.contextUsageMeter) == null ? void 0 : _h.update(tab.state.usage);
}
function syncTabProviderServices(tab, plugin) {
  var _a3, _b2, _c, _d2, _e;
  (_a3 = tab.services.instructionRefineService) == null ? void 0 : _a3.cancel();
  (_b2 = tab.services.instructionRefineService) == null ? void 0 : _b2.resetConversation();
  (_c = tab.services.titleGenerationService) == null ? void 0 : _c.cancel();
  tab.services.instructionRefineService = ProviderRegistry.createInstructionRefineService(plugin, tab.providerId);
  tab.services.titleGenerationService = ProviderRegistry.createTitleGenerationService(plugin, tab.providerId);
  (_e = (_d2 = tab.services.subagentManager).setTaskResultInterpreter) == null ? void 0 : _e.call(
    _d2,
    ProviderRegistry.getTaskResultInterpreter(tab.providerId)
  );
}
function cleanupTabRuntime(tab) {
  if (tab.service && typeof tab.service.cleanup === "function") {
    tab.service.cleanup();
  }
  tab.service = null;
  tab.serviceInitialized = false;
}
function onProviderAvailabilityChanged(tab, plugin) {
  var _a3, _b2, _c, _d2, _e;
  if (tab.lifecycleState !== "blank") return;
  const settingsSnapshot = plugin.settings;
  const enabledProviderIds = ProviderRegistry.getEnabledProviderIds(settingsSnapshot);
  let nextProviderId = tab.providerId;
  if (tab.draftModel) {
    const draftProvider = getEnabledProviderForModel(tab.draftModel, settingsSnapshot);
    const draftProviderOwnsModel = ProviderRegistry.getChatUIConfig(draftProvider).ownsModel(tab.draftModel, settingsSnapshot);
    if (!enabledProviderIds.includes(draftProvider) || !draftProviderOwnsModel) {
      const fallbackProviderId = (_a3 = enabledProviderIds[0]) != null ? _a3 : DEFAULT_CHAT_PROVIDER_ID;
      const fallbackModels = ProviderRegistry.getChatUIConfig(fallbackProviderId).getModelOptions(settingsSnapshot);
      tab.draftModel = (_c = (_b2 = fallbackModels[0]) == null ? void 0 : _b2.value) != null ? _c : tab.draftModel;
      nextProviderId = fallbackProviderId;
    } else {
      nextProviderId = draftProvider;
    }
  }
  tab.providerId = nextProviderId;
  if (tab.service && tab.service.providerId !== nextProviderId) {
    tab.service.cleanup();
    tab.service = null;
    tab.serviceInitialized = false;
  }
  syncTabProviderServices(tab, plugin);
  (_d2 = tab.ui.slashCommandDropdown) == null ? void 0 : _d2.setHiddenCommands(getTabHiddenCommands(tab, plugin));
  (_e = tab.ui.slashCommandDropdown) == null ? void 0 : _e.resetSdkSkillsCache();
  refreshTabProviderUI(tab, plugin);
  applyProviderUIGating(tab, plugin);
}
function createTab(options) {
  var _a3, _b2;
  const {
    plugin,
    containerEl,
    conversation,
    tabId,
    onStreamingChanged,
    onAttentionChanged,
    onConversationIdChanged
  } = options;
  const id = tabId != null ? tabId : generateTabId();
  const contentEl = containerEl.createDiv({ cls: "claudian-tab-content" });
  contentEl.style.display = "none";
  const state = new ChatState({
    onStreamingStateChanged: onStreamingChanged,
    onAttentionChanged,
    onConversationChanged: onConversationIdChanged
  });
  const subagentManager = new SubagentManager(() => {
  });
  const dom = buildTabDOM(contentEl);
  state.queueIndicatorEl = dom.queueIndicatorEl;
  const isBound = !!(conversation == null ? void 0 : conversation.id);
  const restoredDraftModel = typeof options.draftModel === "string" ? options.draftModel.trim() : "";
  const draftModel = isBound ? null : restoredDraftModel || resolveBlankTabModel(plugin, options.defaultProviderId);
  const initialProviderId = (_a3 = conversation == null ? void 0 : conversation.providerId) != null ? _a3 : draftModel ? getEnabledProviderForModel(draftModel, plugin.settings) : DEFAULT_CHAT_PROVIDER_ID;
  const tab = {
    id,
    lifecycleState: isBound ? "bound_cold" : "blank",
    draftModel,
    providerId: initialProviderId,
    conversationId: (_b2 = conversation == null ? void 0 : conversation.id) != null ? _b2 : null,
    service: null,
    serviceInitialized: false,
    state,
    controllers: {
      selectionController: null,
      browserSelectionController: null,
      canvasSelectionController: null,
      conversationController: null,
      streamController: null,
      inputController: null,
      navigationController: null
    },
    services: {
      subagentManager,
      instructionRefineService: null,
      titleGenerationService: null
    },
    ui: {
      fileContextManager: null,
      imageContextManager: null,
      modelSelector: null,
      modeSelector: null,
      thinkingBudgetSelector: null,
      externalContextSelector: null,
      mcpServerSelector: null,
      permissionToggle: null,
      serviceTierToggle: null,
      slashCommandDropdown: null,
      instructionModeManager: null,
      bangBashModeManager: null,
      contextUsageMeter: null,
      statusPanel: null,
      navigationSidebar: null
    },
    dom,
    renderer: null
  };
  return tab;
}
function autoResizeTextarea(textarea) {
  var _a3, _b2;
  textarea.style.minHeight = "";
  const viewHeight = (_b2 = (_a3 = textarea.closest(".claudian-container")) == null ? void 0 : _a3.clientHeight) != null ? _b2 : window.innerHeight;
  const maxHeight = Math.max(TEXTAREA_MIN_MAX_HEIGHT, viewHeight * TEXTAREA_MAX_HEIGHT_PERCENT);
  const flexAllocatedHeight = textarea.offsetHeight;
  const contentHeight = Math.min(textarea.scrollHeight, maxHeight);
  if (contentHeight > flexAllocatedHeight) {
    textarea.style.minHeight = `${contentHeight}px`;
  }
  textarea.style.maxHeight = `${maxHeight}px`;
}
function buildTabDOM(contentEl) {
  const messagesWrapperEl = contentEl.createDiv({ cls: "claudian-messages-wrapper" });
  const messagesEl = messagesWrapperEl.createDiv({ cls: "claudian-messages" });
  const welcomeEl = messagesEl.createDiv({ cls: "claudian-welcome" });
  const statusPanelContainerEl = contentEl.createDiv({ cls: "claudian-status-panel-container" });
  const inputContainerEl = contentEl.createDiv({ cls: "claudian-input-container" });
  const queueIndicatorEl = inputContainerEl.createDiv({ cls: "claudian-input-queue-row" });
  const navRowEl = inputContainerEl.createDiv({ cls: "claudian-input-nav-row" });
  const inputWrapper = inputContainerEl.createDiv({ cls: "claudian-input-wrapper" });
  const contextRowEl = inputWrapper.createDiv({ cls: "claudian-context-row" });
  const inputEl = inputWrapper.createEl("textarea", {
    cls: "claudian-input",
    attr: {
      placeholder: "How can I help you today?",
      rows: "3",
      dir: "auto"
    }
  });
  return {
    contentEl,
    messagesEl,
    welcomeEl,
    statusPanelContainerEl,
    inputContainerEl,
    queueIndicatorEl,
    inputWrapper,
    inputEl,
    navRowEl,
    contextRowEl,
    selectionIndicatorEl: null,
    browserIndicatorEl: null,
    canvasIndicatorEl: null,
    eventCleanups: []
  };
}
async function initializeTabService(tab, plugin, argOrOverride, maybeOverride) {
  var _a3;
  if (tab.lifecycleState === "closing") {
    return;
  }
  const conversationOverride = isConversationLike(argOrOverride) ? argOrOverride : argOrOverride === null ? null : maybeOverride;
  const conversation = conversationOverride != null ? conversationOverride : tab.conversationId ? await plugin.getConversationById(tab.conversationId) : null;
  const providerId = getTabProviderId(tab, plugin, conversation);
  if (tab.serviceInitialized && ((_a3 = tab.service) == null ? void 0 : _a3.providerId) === providerId) {
    return;
  }
  let service = null;
  let unsubscribeReadyState = null;
  const previousService = tab.service;
  try {
    if (typeof (previousService == null ? void 0 : previousService.cleanup) === "function") {
      previousService.cleanup();
    }
    tab.service = null;
    tab.serviceInitialized = false;
    const runtime = ProviderRegistry.createChatRuntime({ plugin, providerId });
    service = runtime;
    unsubscribeReadyState = runtime.onReadyStateChange(() => {
    });
    tab.dom.eventCleanups.push(() => unsubscribeReadyState == null ? void 0 : unsubscribeReadyState());
    if (conversation) {
      const hasMessages = conversation.messages.length > 0;
      const externalContextPaths = hasMessages ? conversation.externalContextPaths || [] : plugin.settings.persistentExternalContextPaths || [];
      runtime.syncConversationState(conversation, externalContextPaths);
    }
    if (tab.lifecycleState === "closing") {
      unsubscribeReadyState == null ? void 0 : unsubscribeReadyState();
      service == null ? void 0 : service.cleanup();
      return;
    }
    tab.providerId = providerId;
    tab.service = service;
    tab.serviceInitialized = true;
    if (tab.lifecycleState === "blank") {
      tab.draftModel = null;
    }
    tab.lifecycleState = "bound_active";
  } catch (error48) {
    unsubscribeReadyState == null ? void 0 : unsubscribeReadyState();
    service == null ? void 0 : service.cleanup();
    tab.service = null;
    tab.serviceInitialized = false;
    throw error48;
  }
}
function isConversationLike(value) {
  return !!value && typeof value === "object" && typeof value.id === "string" && Array.isArray(value.messages);
}
function initializeContextManagers(tab, plugin) {
  const { dom } = tab;
  const app = plugin.app;
  tab.ui.fileContextManager = new FileContextManager(
    app,
    dom.contextRowEl,
    dom.inputEl,
    {
      getExcludedTags: () => plugin.settings.excludedTags,
      onChipsChanged: () => {
        var _a3, _b2, _c, _d2;
        (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.updateContextRowVisibility();
        (_b2 = tab.controllers.browserSelectionController) == null ? void 0 : _b2.updateContextRowVisibility();
        (_c = tab.controllers.canvasSelectionController) == null ? void 0 : _c.updateContextRowVisibility();
        autoResizeTextarea(dom.inputEl);
        (_d2 = tab.renderer) == null ? void 0 : _d2.scrollToBottomIfNeeded();
      },
      getExternalContexts: () => {
        var _a3;
        return ((_a3 = tab.ui.externalContextSelector) == null ? void 0 : _a3.getExternalContexts()) || [];
      }
    },
    dom.inputContainerEl
  );
  tab.ui.fileContextManager.setMcpManager(getProviderMcpManager(getTabProviderId(tab, plugin)));
  tab.ui.imageContextManager = new ImageContextManager(
    dom.inputContainerEl,
    dom.inputEl,
    {
      onImagesChanged: () => {
        var _a3, _b2, _c, _d2;
        (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.updateContextRowVisibility();
        (_b2 = tab.controllers.browserSelectionController) == null ? void 0 : _b2.updateContextRowVisibility();
        (_c = tab.controllers.canvasSelectionController) == null ? void 0 : _c.updateContextRowVisibility();
        autoResizeTextarea(dom.inputEl);
        (_d2 = tab.renderer) == null ? void 0 : _d2.scrollToBottomIfNeeded();
      }
    },
    dom.contextRowEl
  );
}
function initializeSlashCommands(tab, getHiddenCommands, catalogInfo) {
  var _a3;
  const { dom } = tab;
  tab.ui.slashCommandDropdown = new SlashCommandDropdown(
    dom.inputContainerEl,
    dom.inputEl,
    {
      onSelect: () => {
      },
      onHide: () => {
      }
    },
    {
      hiddenCommands: (_a3 = getHiddenCommands == null ? void 0 : getHiddenCommands()) != null ? _a3 : /* @__PURE__ */ new Set(),
      providerConfig: catalogInfo == null ? void 0 : catalogInfo.config,
      getProviderEntries: catalogInfo == null ? void 0 : catalogInfo.getEntries
    }
  );
}
function initializeInstructionAndTodo(tab, plugin) {
  const { dom } = tab;
  syncTabProviderServices(tab, plugin);
  tab.ui.instructionModeManager = new InstructionModeManager(
    dom.inputEl,
    {
      onSubmit: async (rawInstruction) => {
        var _a3;
        await ((_a3 = tab.controllers.inputController) == null ? void 0 : _a3.handleInstructionSubmit(rawInstruction));
      },
      getInputWrapper: () => dom.inputWrapper
    }
  );
  if (isBangBashEnabled(plugin.settings)) {
    const vaultPath = getVaultPath(plugin.app);
    if (vaultPath) {
      const enhancedPath = getEnhancedPath();
      const bashService = new BangBashService(vaultPath, enhancedPath);
      tab.ui.bangBashModeManager = new BangBashModeManager(
        dom.inputEl,
        {
          onSubmit: async (command) => {
            const statusPanel = tab.ui.statusPanel;
            if (!statusPanel) return;
            const id = `bash-${Date.now()}`;
            statusPanel.addBashOutput({ id, command, status: "running", output: "" });
            const result = await bashService.execute(command);
            const output = [result.stdout, result.stderr, result.error].filter(Boolean).join("\n").trim();
            const status = result.exitCode === 0 ? "completed" : "error";
            statusPanel.updateBashOutput(id, { status, output, exitCode: result.exitCode });
          },
          getInputWrapper: () => dom.inputWrapper
        }
      );
    }
  }
  tab.ui.statusPanel = new StatusPanel();
  tab.ui.statusPanel.mount(dom.statusPanelContainerEl);
}
function isBangBashEnabled(settings11) {
  return ProviderRegistry.getEnabledProviderIds(settings11).some((providerId) => {
    var _a3, _b2, _c;
    return (_c = (_b2 = (_a3 = ProviderRegistry.getChatUIConfig(providerId)).isBangBashEnabled) == null ? void 0 : _b2.call(_a3, settings11)) != null ? _c : false;
  });
}
function initializeInputToolbar(tab, plugin, getProviderCatalogConfig, onProviderChanged) {
  var _a3;
  const { dom } = tab;
  const inputToolbar = dom.inputWrapper.createDiv({ cls: "claudian-input-toolbar" });
  const blankTabUIConfigProxy = () => {
    const draftProvider = tab.draftModel ? getEnabledProviderForModel(tab.draftModel, plugin.settings) : DEFAULT_CHAT_PROVIDER_ID;
    const baseConfig = ProviderRegistry.getChatUIConfig(draftProvider);
    return {
      ...baseConfig,
      getModelOptions: (settings11) => getBlankTabModelOptions(settings11)
    };
  };
  const toolbarComponents = createInputToolbar(inputToolbar, {
    getUIConfig: () => {
      if (tab.lifecycleState === "blank") {
        return blankTabUIConfigProxy();
      }
      return getTabChatUIConfig(tab, plugin);
    },
    getCapabilities: () => getTabCapabilities(tab, plugin),
    getSettings: () => getTabSettingsSnapshot(tab, plugin),
    getEnvironmentVariables: () => plugin.getActiveEnvironmentVariables(),
    onModelChange: async (model) => {
      var _a4, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k;
      if (tab.lifecycleState === "blank") {
        const previousProvider = tab.providerId;
        tab.draftModel = model;
        const newProvider = getEnabledProviderForModel(
          model,
          plugin.settings
        );
        const didProviderChange = newProvider !== previousProvider;
        if (tab.service) {
          cleanupTabRuntime(tab);
        }
        tab.providerId = newProvider;
        if (didProviderChange) {
          syncTabProviderServices(tab, plugin);
        }
        syncSlashCommandDropdownForProvider(tab, plugin, getProviderCatalogConfig);
        const uiConfig2 = ProviderRegistry.getChatUIConfig(newProvider);
        await updateTabProviderSettings(tab, plugin, (settings11) => {
          settings11.model = model;
          uiConfig2.applyModelDefaults(model, settings11);
        });
        if (didProviderChange) {
          await (onProviderChanged == null ? void 0 : onProviderChanged(newProvider));
        }
        (_a4 = tab.ui.thinkingBudgetSelector) == null ? void 0 : _a4.updateDisplay();
        (_b2 = tab.ui.serviceTierToggle) == null ? void 0 : _b2.updateDisplay();
        (_c = tab.ui.modelSelector) == null ? void 0 : _c.updateDisplay();
        (_d2 = tab.ui.modeSelector) == null ? void 0 : _d2.updateDisplay();
        (_e = tab.ui.modelSelector) == null ? void 0 : _e.renderOptions();
        (_f = tab.ui.modeSelector) == null ? void 0 : _f.renderOptions();
        applyProviderUIGating(tab, plugin);
        return;
      }
      const boundProvider = tab.providerId;
      const modelProvider = getProviderForModel(model, plugin.settings);
      if (modelProvider !== boundProvider) {
        new import_obsidian41.Notice("Cannot switch provider on a bound session. Start a new tab instead.");
        (_g = tab.ui.modelSelector) == null ? void 0 : _g.updateDisplay();
        return;
      }
      const uiConfig = getTabChatUIConfig(tab, plugin);
      const providerSettings = await updateTabProviderSettings(tab, plugin, (settings11) => {
        settings11.model = model;
        uiConfig.applyModelDefaults(model, settings11);
      });
      (_h = tab.ui.thinkingBudgetSelector) == null ? void 0 : _h.updateDisplay();
      (_i = tab.ui.serviceTierToggle) == null ? void 0 : _i.updateDisplay();
      (_j2 = tab.ui.modelSelector) == null ? void 0 : _j2.updateDisplay();
      (_k = tab.ui.modelSelector) == null ? void 0 : _k.renderOptions();
      const currentUsage = tab.state.usage;
      if (currentUsage) {
        const newContextWindow = uiConfig.getContextWindowSize(
          model,
          providerSettings.customContextLimits
        );
        tab.state.usage = recalculateUsageForModel(currentUsage, model, newContextWindow);
      }
    },
    onModeChange: async (mode) => {
      var _a4, _b2;
      await updateTabProviderSettings(tab, plugin, (settings11) => {
        var _a5, _b3;
        (_b3 = (_a5 = getTabChatUIConfig(tab, plugin)).applyModeSelection) == null ? void 0 : _b3.call(_a5, mode, settings11);
      });
      (_a4 = tab.ui.modeSelector) == null ? void 0 : _a4.updateDisplay();
      (_b2 = tab.ui.modeSelector) == null ? void 0 : _b2.renderOptions();
    },
    onThinkingBudgetChange: async (budget) => {
      await updateTabProviderSettings(tab, plugin, (settings11) => {
        var _a4, _b2;
        settings11.thinkingBudget = budget;
        (_b2 = (_a4 = getTabChatUIConfig(tab, plugin)).applyReasoningSelection) == null ? void 0 : _b2.call(_a4, settings11.model, budget, settings11);
      });
    },
    onEffortLevelChange: async (effort) => {
      await updateTabProviderSettings(tab, plugin, (settings11) => {
        var _a4, _b2;
        settings11.effortLevel = effort;
        (_b2 = (_a4 = getTabChatUIConfig(tab, plugin)).applyReasoningSelection) == null ? void 0 : _b2.call(_a4, settings11.model, effort, settings11);
      });
    },
    onServiceTierChange: async (serviceTier) => {
      var _a4;
      await updateTabProviderSettings(tab, plugin, (settings11) => {
        settings11.serviceTier = serviceTier;
      });
      (_a4 = tab.ui.serviceTierToggle) == null ? void 0 : _a4.updateDisplay();
    },
    onPermissionModeChange: async (mode) => {
      var _a4;
      await updateTabProviderSettings(tab, plugin, (settings11) => {
        const uiConfig = getTabChatUIConfig(tab, plugin);
        if (uiConfig.applyPermissionMode) {
          uiConfig.applyPermissionMode(mode, settings11);
        } else {
          settings11.permissionMode = mode;
        }
      });
      (_a4 = tab.ui.permissionToggle) == null ? void 0 : _a4.updateDisplay();
      dom.inputWrapper.toggleClass(
        "claudian-input-plan-mode",
        mode === "plan" && getTabCapabilities(tab, plugin).supportsPlanMode
      );
    }
  });
  tab.ui.modelSelector = toolbarComponents.modelSelector;
  tab.ui.modeSelector = toolbarComponents.modeSelector;
  tab.ui.thinkingBudgetSelector = toolbarComponents.thinkingBudgetSelector;
  tab.ui.contextUsageMeter = toolbarComponents.contextUsageMeter;
  tab.ui.externalContextSelector = toolbarComponents.externalContextSelector;
  tab.ui.mcpServerSelector = toolbarComponents.mcpServerSelector;
  tab.ui.permissionToggle = toolbarComponents.permissionToggle;
  tab.ui.serviceTierToggle = toolbarComponents.serviceTierToggle;
  tab.ui.mcpServerSelector.setMcpManager(getProviderMcpManager(getTabProviderId(tab, plugin)));
  (_a3 = tab.ui.fileContextManager) == null ? void 0 : _a3.setOnMcpMentionChange((servers) => {
    var _a4;
    (_a4 = tab.ui.mcpServerSelector) == null ? void 0 : _a4.addMentionedServers(servers);
  });
  tab.ui.externalContextSelector.setOnChange(() => {
    var _a4;
    (_a4 = tab.ui.fileContextManager) == null ? void 0 : _a4.preScanExternalContexts();
  });
  tab.ui.externalContextSelector.setPersistentPaths(
    plugin.settings.persistentExternalContextPaths || []
  );
  tab.ui.externalContextSelector.setOnPersistenceChange(async (paths) => {
    plugin.settings.persistentExternalContextPaths = paths;
    await plugin.saveSettings();
  });
  refreshTabProviderUI(tab, plugin);
  applyProviderUIGating(tab, plugin);
}
function initializeTabUI(tab, plugin, options = {}) {
  var _a3, _b2;
  const { dom, state } = tab;
  initializeContextManagers(tab, plugin);
  dom.selectionIndicatorEl = dom.contextRowEl.createDiv({ cls: "claudian-selection-indicator" });
  dom.selectionIndicatorEl.style.display = "none";
  dom.browserIndicatorEl = dom.contextRowEl.createDiv({ cls: "claudian-browser-selection-indicator" });
  dom.browserIndicatorEl.style.display = "none";
  dom.canvasIndicatorEl = dom.contextRowEl.createDiv({ cls: "claudian-canvas-indicator" });
  dom.canvasIndicatorEl.style.display = "none";
  const catalogInfo = (_b2 = (_a3 = options.getProviderCatalogConfig) == null ? void 0 : _a3.call(options)) != null ? _b2 : null;
  initializeSlashCommands(
    tab,
    () => getTabHiddenCommands(tab, plugin),
    catalogInfo
  );
  if (dom.messagesEl.parentElement) {
    tab.ui.navigationSidebar = new NavigationSidebar(
      dom.messagesEl.parentElement,
      dom.messagesEl
    );
  }
  initializeInstructionAndTodo(tab, plugin);
  initializeInputToolbar(tab, plugin, options.getProviderCatalogConfig, options.onProviderChanged);
  state.callbacks = {
    ...state.callbacks,
    onUsageChanged: (usage) => {
      var _a4;
      (_a4 = tab.ui.contextUsageMeter) == null ? void 0 : _a4.update(usage);
    },
    onTodosChanged: (todos) => {
      var _a4;
      return (_a4 = tab.ui.statusPanel) == null ? void 0 : _a4.updateTodos(todos);
    },
    onAutoScrollChanged: () => {
      var _a4;
      return (_a4 = tab.ui.navigationSidebar) == null ? void 0 : _a4.updateVisibility();
    }
  };
  const resizeObserver = new ResizeObserver(() => {
    var _a4;
    (_a4 = tab.ui.navigationSidebar) == null ? void 0 : _a4.updateVisibility();
  });
  resizeObserver.observe(dom.messagesEl);
  dom.eventCleanups.push(() => resizeObserver.disconnect());
}
function deepCloneMessages(messages) {
  const sc = globalThis.structuredClone;
  if (typeof sc === "function") {
    return sc(messages);
  }
  return JSON.parse(JSON.stringify(messages));
}
function countUserMessagesForForkTitle(messages) {
  return messages.filter((m2) => m2.role === "user" && !m2.isInterrupt && !m2.isRebuiltContext).length;
}
function resolveForkSource(tab, plugin) {
  var _a3;
  const conversation = tab.conversationId ? plugin.getConversationSync(tab.conversationId) : null;
  const sourceSessionId = tab.service ? tab.service.resolveSessionIdForFork(conversation != null ? conversation : null) : ProviderRegistry.getConversationHistoryService((_a3 = conversation == null ? void 0 : conversation.providerId) != null ? _a3 : tab.providerId).resolveSessionIdForConversation(conversation);
  if (!sourceSessionId) {
    new import_obsidian41.Notice(t("chat.fork.failed", { error: t("chat.fork.errorNoSession") }));
    return null;
  }
  return {
    providerId: getTabProviderId(tab, plugin, conversation),
    sourceSessionId,
    sourceProviderState: conversation == null ? void 0 : conversation.providerState,
    sourceTitle: conversation == null ? void 0 : conversation.title,
    currentNote: conversation == null ? void 0 : conversation.currentNote
  };
}
async function handleForkRequest(tab, plugin, userMessageId, forkRequestCallback) {
  const { state } = tab;
  if (!getTabCapabilities(tab, plugin).supportsFork) {
    new import_obsidian41.Notice("Fork is not supported by this provider.");
    return;
  }
  if (state.isStreaming) {
    new import_obsidian41.Notice(t("chat.fork.unavailableStreaming"));
    return;
  }
  const msgs = state.messages;
  const userIdx = msgs.findIndex((m2) => m2.id === userMessageId);
  if (userIdx === -1) {
    new import_obsidian41.Notice(t("chat.fork.failed", { error: t("chat.fork.errorMessageNotFound") }));
    return;
  }
  if (!msgs[userIdx].userMessageId) {
    new import_obsidian41.Notice(t("chat.fork.unavailableNoUuid"));
    return;
  }
  const rewindCtx = findRewindContext(msgs, userIdx);
  if (!rewindCtx.hasResponse || !rewindCtx.prevAssistantUuid) {
    new import_obsidian41.Notice(t("chat.fork.unavailableNoResponse"));
    return;
  }
  const source = resolveForkSource(tab, plugin);
  if (!source) return;
  await forkRequestCallback({
    messages: deepCloneMessages(msgs.slice(0, userIdx)),
    providerId: source.providerId,
    sourceSessionId: source.sourceSessionId,
    sourceProviderState: source.sourceProviderState,
    resumeAt: rewindCtx.prevAssistantUuid,
    sourceTitle: source.sourceTitle,
    forkAtUserMessage: countUserMessagesForForkTitle(msgs.slice(0, userIdx + 1)),
    currentNote: source.currentNote
  });
}
async function handleForkAll(tab, plugin, forkRequestCallback) {
  const { state } = tab;
  if (!getTabCapabilities(tab, plugin).supportsFork) {
    new import_obsidian41.Notice("Fork is not supported by this provider.");
    return;
  }
  if (state.isStreaming) {
    new import_obsidian41.Notice(t("chat.fork.unavailableStreaming"));
    return;
  }
  const msgs = state.messages;
  if (msgs.length === 0) {
    new import_obsidian41.Notice(t("chat.fork.commandNoMessages"));
    return;
  }
  let lastAssistantUuid;
  for (let i2 = msgs.length - 1; i2 >= 0; i2--) {
    if (msgs[i2].role === "assistant" && msgs[i2].assistantMessageId) {
      lastAssistantUuid = msgs[i2].assistantMessageId;
      break;
    }
  }
  if (!lastAssistantUuid) {
    new import_obsidian41.Notice(t("chat.fork.commandNoAssistantUuid"));
    return;
  }
  const source = resolveForkSource(tab, plugin);
  if (!source) return;
  await forkRequestCallback({
    messages: deepCloneMessages(msgs),
    providerId: source.providerId,
    sourceSessionId: source.sourceSessionId,
    sourceProviderState: source.sourceProviderState,
    resumeAt: lastAssistantUuid,
    sourceTitle: source.sourceTitle,
    forkAtUserMessage: countUserMessagesForForkTitle(msgs) + 1,
    currentNote: source.currentNote
  });
}
function initializeTabControllers(tab, plugin, component, arg4, arg5, arg6, arg7) {
  const isLegacy = arg4 !== void 0 && typeof arg4 !== "function";
  const forkRequestCallback = isLegacy ? arg5 : arg4;
  const openConversation = isLegacy ? arg6 : arg5;
  const getProviderCatalogConfig = isLegacy ? arg7 : arg6;
  const { dom, state, services, ui } = tab;
  tab.renderer = new MessageRenderer(
    plugin,
    component,
    dom.messagesEl,
    (id) => tab.controllers.conversationController.rewind(id),
    forkRequestCallback ? (id) => handleForkRequest(tab, plugin, id, forkRequestCallback) : void 0,
    () => getTabCapabilities(tab, plugin)
  );
  tab.controllers.selectionController = new SelectionController(
    plugin.app,
    dom.selectionIndicatorEl,
    dom.inputEl,
    dom.contextRowEl,
    () => autoResizeTextarea(dom.inputEl),
    dom.contentEl
  );
  tab.controllers.browserSelectionController = new BrowserSelectionController(
    plugin.app,
    dom.browserIndicatorEl,
    dom.inputEl,
    dom.contextRowEl,
    () => autoResizeTextarea(dom.inputEl)
  );
  tab.controllers.canvasSelectionController = new CanvasSelectionController(
    plugin.app,
    dom.canvasIndicatorEl,
    dom.inputEl,
    dom.contextRowEl,
    () => autoResizeTextarea(dom.inputEl)
  );
  tab.controllers.streamController = new StreamController({
    plugin,
    state,
    renderer: tab.renderer,
    subagentManager: services.subagentManager,
    getMessagesEl: () => dom.messagesEl,
    getFileContextManager: () => ui.fileContextManager,
    updateQueueIndicator: () => {
      var _a3;
      return (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.updateQueueIndicator();
    },
    getAgentService: () => tab.service
  });
  services.subagentManager.setCallback(
    (subagent) => {
      var _a3, _b2;
      (_a3 = tab.controllers.streamController) == null ? void 0 : _a3.onAsyncSubagentStateChange(subagent);
      if (!tab.state.isStreaming && tab.state.currentConversationId) {
        void ((_b2 = tab.controllers.conversationController) == null ? void 0 : _b2.save(false).catch(() => {
        }));
      }
    }
  );
  tab.controllers.conversationController = new ConversationController(
    {
      plugin,
      state,
      renderer: tab.renderer,
      subagentManager: services.subagentManager,
      getHistoryDropdown: () => null,
      // Tab doesn't have its own history dropdown
      getWelcomeEl: () => dom.welcomeEl,
      setWelcomeEl: (el) => {
        dom.welcomeEl = el;
      },
      getMessagesEl: () => dom.messagesEl,
      getInputEl: () => dom.inputEl,
      getFileContextManager: () => ui.fileContextManager,
      getImageContextManager: () => ui.imageContextManager,
      getMcpServerSelector: () => ui.mcpServerSelector,
      getExternalContextSelector: () => ui.externalContextSelector,
      clearQueuedMessage: () => {
        var _a3;
        return (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.clearQueuedMessage();
      },
      getTitleGenerationService: () => services.titleGenerationService,
      getStatusPanel: () => ui.statusPanel,
      getAgentService: () => tab.service,
      // Use tab's service instead of plugin's
      dismissPendingInlinePrompts: () => {
        var _a3;
        return (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.dismissPendingApproval();
      },
      ensureServiceForConversation: async (conversation) => {
        var _a3;
        const nextProviderId = getTabProviderId(tab, plugin, conversation);
        const providerChanged = tab.providerId !== nextProviderId;
        tab.providerId = nextProviderId;
        if (providerChanged) {
          syncTabProviderServices(tab, plugin);
        }
        tab.conversationId = (_a3 = conversation == null ? void 0 : conversation.id) != null ? _a3 : null;
        tab.draftModel = null;
        tab.lifecycleState = conversation ? "bound_cold" : "blank";
        syncSlashCommandDropdownForProvider(tab, plugin, getProviderCatalogConfig, conversation);
        if (tab.service && tab.service.providerId === nextProviderId && conversation) {
          const hasMessages = conversation.messages.length > 0;
          const externalContextPaths = hasMessages ? conversation.externalContextPaths || [] : plugin.settings.persistentExternalContextPaths || [];
          tab.service.syncConversationState(conversation, externalContextPaths);
        }
        refreshTabProviderUI(tab, plugin);
        applyProviderUIGating(tab, plugin);
      }
    },
    {
      onNewConversation: () => {
        const previousProviderId = tab.providerId;
        cleanupTabRuntime(tab);
        tab.lifecycleState = "blank";
        tab.draftModel = resolveBlankTabModel(plugin, previousProviderId);
        tab.conversationId = null;
        tab.providerId = getTabProviderId(tab, plugin);
        if (tab.providerId !== previousProviderId) {
          syncTabProviderServices(tab, plugin);
        }
        refreshTabProviderUI(tab, plugin);
        applyProviderUIGating(tab, plugin);
        syncSlashCommandDropdownForProvider(tab, plugin, getProviderCatalogConfig);
      },
      onConversationLoaded: () => {
        var _a3;
        return (_a3 = ui.slashCommandDropdown) == null ? void 0 : _a3.resetSdkSkillsCache();
      },
      onConversationSwitched: () => {
        var _a3;
        return (_a3 = ui.slashCommandDropdown) == null ? void 0 : _a3.resetSdkSkillsCache();
      }
    }
  );
  tab.controllers.inputController = new InputController({
    plugin,
    state,
    renderer: tab.renderer,
    streamController: tab.controllers.streamController,
    selectionController: tab.controllers.selectionController,
    browserSelectionController: tab.controllers.browserSelectionController,
    canvasSelectionController: tab.controllers.canvasSelectionController,
    conversationController: tab.controllers.conversationController,
    getInputEl: () => dom.inputEl,
    getInputContainerEl: () => dom.inputContainerEl,
    getWelcomeEl: () => dom.welcomeEl,
    getMessagesEl: () => dom.messagesEl,
    getFileContextManager: () => ui.fileContextManager,
    getImageContextManager: () => ui.imageContextManager,
    getMcpServerSelector: () => ui.mcpServerSelector,
    getExternalContextSelector: () => ui.externalContextSelector,
    getInstructionModeManager: () => ui.instructionModeManager,
    getInstructionRefineService: () => services.instructionRefineService,
    getTitleGenerationService: () => services.titleGenerationService,
    getStatusPanel: () => ui.statusPanel,
    generateId: generateMessageId,
    resetInputHeight: () => {
    },
    getAuxiliaryModel: () => {
      var _a3, _b2, _c, _d2;
      return (_d2 = (_c = (_b2 = (_a3 = tab.service) == null ? void 0 : _a3.getAuxiliaryModel) == null ? void 0 : _b2.call(_a3)) != null ? _c : tab.draftModel) != null ? _d2 : null;
    },
    getAgentService: () => tab.service,
    getSubagentManager: () => services.subagentManager,
    getTabProviderId: () => getTabProviderId(tab, plugin),
    ensureServiceInitialized: async () => {
      if (tab.serviceInitialized && tab.lifecycleState === "bound_active") {
        return true;
      }
      try {
        if (tab.lifecycleState === "blank" && tab.draftModel) {
          const derivedProvider = getEnabledProviderForModel(
            tab.draftModel,
            plugin.settings
          );
          tab.providerId = derivedProvider;
        }
        await initializeTabService(tab, plugin);
        setupServiceCallbacks(tab, plugin);
        refreshTabProviderUI(tab, plugin);
        applyProviderUIGating(tab, plugin);
        return true;
      } catch (error48) {
        new import_obsidian41.Notice(error48 instanceof Error ? error48.message : "Failed to initialize chat service");
        return false;
      }
    },
    openConversation,
    onForkAll: forkRequestCallback ? () => handleForkAll(tab, plugin, forkRequestCallback) : void 0,
    restorePrePlanPermissionModeIfNeeded: () => {
      var _a3;
      if (getTabPermissionMode(tab, plugin) === "plan") {
        const restoreMode = (_a3 = tab.state.prePlanPermissionMode) != null ? _a3 : "normal";
        tab.state.prePlanPermissionMode = null;
        updatePlanModeUI(tab, plugin, restoreMode);
      }
    }
  });
  tab.controllers.navigationController = new NavigationController({
    getMessagesEl: () => dom.messagesEl,
    getInputEl: () => dom.inputEl,
    getSettings: () => plugin.settings.keyboardNavigation,
    isStreaming: () => state.isStreaming,
    shouldSkipEscapeHandling: () => {
      var _a3, _b2, _c, _d2, _e;
      if ((_a3 = ui.instructionModeManager) == null ? void 0 : _a3.isActive()) return true;
      if ((_b2 = ui.bangBashModeManager) == null ? void 0 : _b2.isActive()) return true;
      if ((_c = tab.controllers.inputController) == null ? void 0 : _c.isResumeDropdownVisible()) return true;
      if ((_d2 = ui.slashCommandDropdown) == null ? void 0 : _d2.isVisible()) return true;
      if ((_e = ui.fileContextManager) == null ? void 0 : _e.isMentionDropdownVisible()) return true;
      return false;
    }
  });
  tab.controllers.navigationController.initialize();
}
function wireTabInputEvents(tab, plugin) {
  var _a3, _b2;
  const { dom, ui, state, controllers } = tab;
  let wasBangBashActive = (_b2 = (_a3 = ui.bangBashModeManager) == null ? void 0 : _a3.isActive()) != null ? _b2 : false;
  const syncBangBashSuppression = () => {
    var _a4, _b3, _c, _d2;
    const isActive = (_b3 = (_a4 = ui.bangBashModeManager) == null ? void 0 : _a4.isActive()) != null ? _b3 : false;
    if (isActive === wasBangBashActive) return;
    wasBangBashActive = isActive;
    (_c = ui.slashCommandDropdown) == null ? void 0 : _c.setEnabled(!isActive);
    if (isActive) {
      (_d2 = ui.fileContextManager) == null ? void 0 : _d2.hideMentionDropdown();
    }
  };
  const keydownHandler = (e2) => {
    var _a4, _b3, _c, _d2, _e, _f, _g, _h, _i;
    if ((_a4 = ui.bangBashModeManager) == null ? void 0 : _a4.isActive()) {
      ui.bangBashModeManager.handleKeydown(e2);
      syncBangBashSuppression();
      return;
    }
    if (getTabCapabilities(tab, plugin).supportsInstructionMode && ((_b3 = ui.instructionModeManager) == null ? void 0 : _b3.handleTriggerKey(e2))) {
      return;
    }
    if ((_c = ui.bangBashModeManager) == null ? void 0 : _c.handleTriggerKey(e2)) {
      syncBangBashSuppression();
      return;
    }
    if (getTabCapabilities(tab, plugin).supportsInstructionMode && ((_d2 = ui.instructionModeManager) == null ? void 0 : _d2.handleKeydown(e2))) {
      return;
    }
    if ((_e = controllers.inputController) == null ? void 0 : _e.handleResumeKeydown(e2)) {
      return;
    }
    if ((_f = ui.slashCommandDropdown) == null ? void 0 : _f.handleKeydown(e2)) {
      return;
    }
    if ((_g = ui.fileContextManager) == null ? void 0 : _g.handleMentionKeydown(e2)) {
      return;
    }
    if (e2.key === "Escape" && !e2.isComposing && state.isStreaming) {
      e2.preventDefault();
      (_h = controllers.inputController) == null ? void 0 : _h.cancelStreaming();
      return;
    }
    if (e2.key === "Enter" && !e2.shiftKey && !e2.isComposing) {
      e2.preventDefault();
      void ((_i = controllers.inputController) == null ? void 0 : _i.sendMessage());
    }
  };
  dom.inputEl.addEventListener("keydown", keydownHandler);
  dom.eventCleanups.push(() => dom.inputEl.removeEventListener("keydown", keydownHandler));
  const inputHandler = () => {
    var _a4, _b3, _c, _d2;
    if (!((_a4 = ui.bangBashModeManager) == null ? void 0 : _a4.isActive())) {
      (_b3 = ui.fileContextManager) == null ? void 0 : _b3.handleInputChange();
    }
    (_c = ui.instructionModeManager) == null ? void 0 : _c.handleInputChange();
    (_d2 = ui.bangBashModeManager) == null ? void 0 : _d2.handleInputChange();
    syncBangBashSuppression();
    autoResizeTextarea(dom.inputEl);
  };
  dom.inputEl.addEventListener("input", inputHandler);
  dom.eventCleanups.push(() => dom.inputEl.removeEventListener("input", inputHandler));
  const focusHandler = (e2) => {
    var _a4;
    if (e2.relatedTarget && dom.contentEl.contains(e2.relatedTarget)) return;
    (_a4 = controllers.selectionController) == null ? void 0 : _a4.showHighlight();
  };
  dom.contentEl.addEventListener("focusin", focusHandler);
  dom.eventCleanups.push(() => dom.contentEl.removeEventListener("focusin", focusHandler));
  const SCROLL_THRESHOLD = 20;
  const RE_ENABLE_DELAY = 150;
  let reEnableTimeout = null;
  const isAutoScrollAllowed = () => {
    var _a4;
    return (_a4 = plugin.settings.enableAutoScroll) != null ? _a4 : true;
  };
  const scrollHandler = () => {
    if (!isAutoScrollAllowed()) {
      if (reEnableTimeout) {
        clearTimeout(reEnableTimeout);
        reEnableTimeout = null;
      }
      state.autoScrollEnabled = false;
      return;
    }
    const { scrollTop, scrollHeight, clientHeight } = dom.messagesEl;
    const isAtBottom = scrollHeight - scrollTop - clientHeight <= SCROLL_THRESHOLD;
    if (!isAtBottom) {
      if (reEnableTimeout) {
        clearTimeout(reEnableTimeout);
        reEnableTimeout = null;
      }
      state.autoScrollEnabled = false;
    } else if (!state.autoScrollEnabled) {
      if (!reEnableTimeout) {
        reEnableTimeout = setTimeout(() => {
          reEnableTimeout = null;
          const { scrollTop: scrollTop2, scrollHeight: scrollHeight2, clientHeight: clientHeight2 } = dom.messagesEl;
          if (scrollHeight2 - scrollTop2 - clientHeight2 <= SCROLL_THRESHOLD) {
            state.autoScrollEnabled = true;
          }
        }, RE_ENABLE_DELAY);
      }
    }
  };
  dom.messagesEl.addEventListener("scroll", scrollHandler, { passive: true });
  dom.eventCleanups.push(() => {
    dom.messagesEl.removeEventListener("scroll", scrollHandler);
    if (reEnableTimeout) clearTimeout(reEnableTimeout);
  });
}
function activateTab(tab) {
  var _a3, _b2, _c, _d2;
  tab.dom.contentEl.style.display = "flex";
  (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.start();
  (_b2 = tab.controllers.browserSelectionController) == null ? void 0 : _b2.start();
  (_c = tab.controllers.canvasSelectionController) == null ? void 0 : _c.start();
  (_d2 = tab.ui.navigationSidebar) == null ? void 0 : _d2.updateVisibility();
}
function deactivateTab(tab) {
  var _a3, _b2, _c;
  tab.dom.contentEl.style.display = "none";
  (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.stop();
  (_b2 = tab.controllers.browserSelectionController) == null ? void 0 : _b2.stop();
  (_c = tab.controllers.canvasSelectionController) == null ? void 0 : _c.stop();
}
async function destroyTab(tab) {
  var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2, _k, _l, _m, _n, _o, _p2, _q, _r, _s;
  tab.lifecycleState = "closing";
  (_a3 = tab.controllers.selectionController) == null ? void 0 : _a3.stop();
  (_b2 = tab.controllers.selectionController) == null ? void 0 : _b2.clear();
  (_c = tab.controllers.browserSelectionController) == null ? void 0 : _c.stop();
  (_d2 = tab.controllers.browserSelectionController) == null ? void 0 : _d2.clear();
  (_e = tab.controllers.canvasSelectionController) == null ? void 0 : _e.stop();
  (_f = tab.controllers.canvasSelectionController) == null ? void 0 : _f.clear();
  (_g = tab.controllers.navigationController) == null ? void 0 : _g.dispose();
  cleanupThinkingBlock(tab.state.currentThinkingState);
  tab.state.currentThinkingState = null;
  (_h = tab.controllers.inputController) == null ? void 0 : _h.dismissPendingApproval();
  (_i = tab.controllers.inputController) == null ? void 0 : _i.destroyResumeDropdown();
  (_j2 = tab.ui.fileContextManager) == null ? void 0 : _j2.destroy();
  (_k = tab.ui.slashCommandDropdown) == null ? void 0 : _k.destroy();
  tab.ui.slashCommandDropdown = null;
  (_l = tab.ui.instructionModeManager) == null ? void 0 : _l.destroy();
  tab.ui.instructionModeManager = null;
  (_m = tab.ui.bangBashModeManager) == null ? void 0 : _m.destroy();
  tab.ui.bangBashModeManager = null;
  (_n = tab.services.instructionRefineService) == null ? void 0 : _n.cancel();
  (_o = tab.services.instructionRefineService) == null ? void 0 : _o.resetConversation();
  tab.services.instructionRefineService = null;
  (_p2 = tab.services.titleGenerationService) == null ? void 0 : _p2.cancel();
  tab.services.titleGenerationService = null;
  (_q = tab.ui.statusPanel) == null ? void 0 : _q.destroy();
  tab.ui.statusPanel = null;
  (_r = tab.ui.navigationSidebar) == null ? void 0 : _r.destroy();
  tab.ui.navigationSidebar = null;
  tab.services.subagentManager.orphanAllActive();
  tab.services.subagentManager.clear();
  for (const cleanup of tab.dom.eventCleanups) {
    cleanup();
  }
  tab.dom.eventCleanups.length = 0;
  (_s = tab.service) == null ? void 0 : _s.cleanup();
  tab.service = null;
  tab.dom.contentEl.remove();
}
function getTabTitle(tab, plugin) {
  if (tab.conversationId) {
    const conversation = plugin.getConversationSync(tab.conversationId);
    if (conversation == null ? void 0 : conversation.title) {
      return conversation.title;
    }
  }
  return "New Chat";
}
function setupServiceCallbacks(tab, plugin) {
  if (tab.service && tab.controllers.inputController) {
    tab.service.setApprovalCallback(
      async (toolName, input, description, options) => {
        var _a3, _b2;
        return (_b2 = await ((_a3 = tab.controllers.inputController) == null ? void 0 : _a3.handleApprovalRequest(toolName, input, description, options))) != null ? _b2 : "cancel";
      }
    );
    tab.service.setApprovalDismisser(
      () => {
        var _a3;
        return (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.dismissPendingApprovalPrompt();
      }
    );
    tab.service.setAskUserQuestionCallback(
      async (input, signal) => {
        var _a3, _b2;
        return (_b2 = await ((_a3 = tab.controllers.inputController) == null ? void 0 : _a3.handleAskUserQuestion(input, signal))) != null ? _b2 : null;
      }
    );
    tab.service.setExitPlanModeCallback(
      async (input, signal) => {
        var _a3, _b2, _c;
        const decision = (_b2 = await ((_a3 = tab.controllers.inputController) == null ? void 0 : _a3.handleExitPlanMode(input, signal))) != null ? _b2 : null;
        if (decision !== null && decision.type !== "feedback") {
          if (getTabPermissionMode(tab, plugin) === "plan") {
            const restoreMode = (_c = tab.state.prePlanPermissionMode) != null ? _c : "normal";
            tab.state.prePlanPermissionMode = null;
            updatePlanModeUI(tab, plugin, restoreMode);
          }
          if (decision.type === "approve-new-session") {
            tab.state.pendingNewSessionPlan = decision.planContent;
            tab.state.cancelRequested = true;
          }
        }
        return decision;
      }
    );
    tab.service.setSubagentHookProvider(
      () => ({
        hasRunning: tab.services.subagentManager.hasRunningSubagents()
      })
    );
    tab.service.setAutoTurnCallback((result) => {
      renderAutoTriggeredTurn(tab, result);
    });
    tab.service.setPermissionModeSyncCallback((sdkMode) => {
      const mode = sdkMode === "bypassPermissions" || sdkMode === "yolo" ? "yolo" : sdkMode === "plan" ? "plan" : "normal";
      const currentMode = getTabPermissionMode(tab, plugin);
      if (currentMode !== mode) {
        if (mode === "plan" && tab.state.prePlanPermissionMode === null) {
          tab.state.prePlanPermissionMode = currentMode;
        }
        updatePlanModeUI(tab, plugin, mode);
      }
    });
  }
}
function generateMessageId() {
  return `msg-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
}
function renderAutoTriggeredTurn(tab, result) {
  var _a3, _b2, _c;
  if (!tab.dom.contentEl.isConnected) {
    return;
  }
  const { chunks, metadata } = result;
  const hasToolActivity = chunks.some(
    (chunk) => chunk.type === "tool_use" || chunk.type === "tool_result"
  );
  let textContent = "";
  for (const chunk of chunks) {
    if (chunk.type === "text") {
      textContent += chunk.content;
    }
  }
  if (!textContent.trim() && !hasToolActivity) return;
  const content = textContent.trim() || "(background task completed)";
  const assistantMsg = {
    id: (_a3 = metadata.assistantMessageId) != null ? _a3 : generateMessageId(),
    role: "assistant",
    content,
    timestamp: Date.now(),
    contentBlocks: [{ type: "text", content }],
    ...metadata.assistantMessageId && { assistantMessageId: metadata.assistantMessageId }
  };
  tab.state.addMessage(assistantMsg);
  (_b2 = tab.renderer) == null ? void 0 : _b2.renderStoredMessage(assistantMsg);
  (_c = tab.renderer) == null ? void 0 : _c.scrollToBottom();
}
function updatePlanModeUI(tab, plugin, mode) {
  var _a3;
  const providerId = getTabProviderId(tab, plugin);
  const snapshot = getTabSettingsSnapshot(tab, plugin);
  const uiConfig = ProviderRegistry.getChatUIConfig(providerId);
  if (uiConfig.applyPermissionMode) {
    uiConfig.applyPermissionMode(mode, snapshot);
  } else {
    snapshot.permissionMode = mode;
  }
  ProviderSettingsCoordinator.commitProviderSettingsSnapshot(
    plugin.settings,
    providerId,
    snapshot
  );
  void plugin.saveSettings();
  (_a3 = tab.ui.permissionToggle) == null ? void 0 : _a3.updateDisplay();
  tab.dom.inputWrapper.toggleClass(
    "claudian-input-plan-mode",
    mode === "plan" && getTabCapabilities(tab, plugin).supportsPlanMode
  );
}

// src/features/chat/tabs/TabBar.ts
var TabBar = class {
  constructor(containerEl, callbacks) {
    this.containerEl = containerEl;
    this.callbacks = callbacks;
    this.build();
  }
  /** Builds the tab bar UI. */
  build() {
    this.containerEl.addClass("claudian-tab-badges");
  }
  /**
   * Updates the tab bar with new tab data.
   * @param items Tab items to render.
   */
  update(items) {
    this.containerEl.empty();
    for (const item of items) {
      this.renderBadge(item);
    }
  }
  /** Renders a single tab badge. */
  renderBadge(item) {
    let stateClass = "claudian-tab-badge-idle";
    if (item.isActive) {
      stateClass = "claudian-tab-badge-active";
    } else if (item.needsAttention) {
      stateClass = "claudian-tab-badge-attention";
    } else if (item.isStreaming) {
      stateClass = "claudian-tab-badge-streaming";
    }
    const badgeEl = this.containerEl.createDiv({
      cls: `claudian-tab-badge ${stateClass}`,
      text: String(item.index)
    });
    badgeEl.setAttribute("aria-label", item.title);
    badgeEl.setAttribute("data-provider", item.providerId);
    badgeEl.addEventListener("click", () => {
      this.callbacks.onTabClick(item.id);
    });
    if (item.canClose) {
      badgeEl.addEventListener("contextmenu", (e2) => {
        e2.preventDefault();
        this.callbacks.onTabClose(item.id);
      });
    }
  }
  /** Destroys the tab bar. */
  destroy() {
    this.containerEl.empty();
    this.containerEl.removeClass("claudian-tab-badges");
  }
};

// src/features/chat/tabs/TabManager.ts
var import_obsidian43 = require("obsidian");

// src/shared/modals/ForkTargetModal.ts
var import_obsidian42 = require("obsidian");
function chooseForkTarget(app) {
  return new Promise((resolve8) => {
    new ForkTargetModal(app, resolve8).open();
  });
}
var ForkTargetModal = class extends import_obsidian42.Modal {
  constructor(app, resolve8) {
    super(app);
    this.resolved = false;
    this.resolve = resolve8;
  }
  onOpen() {
    this.setTitle(t("chat.fork.chooseTarget"));
    this.modalEl.addClass("claudian-fork-target-modal");
    const list = this.contentEl.createDiv({ cls: "claudian-fork-target-list" });
    this.createOption(list, "current-tab", t("chat.fork.targetCurrentTab"));
    this.createOption(list, "new-tab", t("chat.fork.targetNewTab"));
  }
  createOption(container, target, label) {
    const item = container.createDiv({ cls: "claudian-fork-target-option", text: label });
    item.addEventListener("click", () => {
      this.resolved = true;
      this.resolve(target);
      this.close();
    });
  }
  onClose() {
    if (!this.resolved) {
      this.resolve(null);
    }
    this.contentEl.empty();
  }
};

// src/features/chat/tabs/TabManager.ts
function isTabManagerViewHost(value) {
  return !!value && typeof value === "object" && "getTabManager" in value;
}
var TabManager = class {
  constructor(plugin, arg2, arg3, arg4, arg5 = {}) {
    this.tabs = /* @__PURE__ */ new Map();
    this.activeTabId = null;
    this.providerCommandWarmups = /* @__PURE__ */ new Map();
    this.providerCommandCache = /* @__PURE__ */ new Map();
    this.isRestoringState = false;
    /** Guard to prevent concurrent tab switches. */
    this.isSwitchingTab = false;
    this.plugin = plugin;
    if (isTabManagerViewHost(arg3)) {
      this.containerEl = arg2;
      this.view = arg3;
      this.callbacks = arg4 != null ? arg4 : {};
      return;
    }
    this.containerEl = arg3;
    this.view = arg4;
    this.callbacks = arg5;
  }
  /**
   * Gets the current max tabs limit from settings.
   * Clamps to MIN_TABS and MAX_TABS bounds.
   */
  getMaxTabs() {
    var _a3;
    const settingsValue = (_a3 = this.plugin.settings.maxTabs) != null ? _a3 : DEFAULT_MAX_TABS;
    return Math.max(MIN_TABS, Math.min(MAX_TABS, settingsValue));
  }
  // ============================================
  // Tab Lifecycle
  // ============================================
  /**
   * Creates a new tab.
   * @param conversationId Optional conversation to load into the tab.
   * @param tabId Optional tab ID (for restoration).
   * @param options Controls whether the new tab becomes active immediately.
   * @returns The created tab, or null if max tabs reached.
   */
  async createTab(conversationId, tabId, options = {}) {
    var _a3, _b2;
    const maxTabs = this.getMaxTabs();
    if (this.tabs.size >= maxTabs) {
      return null;
    }
    const { activate = true, draftModel } = options;
    const conversation = conversationId ? await this.plugin.getConversationById(conversationId) : void 0;
    const activeTab = this.getActiveTab();
    const defaultProviderId = conversation ? void 0 : activeTab ? getTabProviderId(activeTab, this.plugin) : void 0;
    const tab = createTab({
      plugin: this.plugin,
      containerEl: this.containerEl,
      conversation: conversation != null ? conversation : void 0,
      tabId,
      ...typeof draftModel === "string" ? { draftModel } : {},
      defaultProviderId,
      onStreamingChanged: (isStreaming) => {
        var _a4, _b3;
        (_b3 = (_a4 = this.callbacks).onTabStreamingChanged) == null ? void 0 : _b3.call(_a4, tab.id, isStreaming);
      },
      onTitleChanged: (title) => {
        var _a4, _b3;
        (_b3 = (_a4 = this.callbacks).onTabTitleChanged) == null ? void 0 : _b3.call(_a4, tab.id, title);
      },
      onAttentionChanged: (needsAttention) => {
        var _a4, _b3;
        (_b3 = (_a4 = this.callbacks).onTabAttentionChanged) == null ? void 0 : _b3.call(_a4, tab.id, needsAttention);
      },
      onConversationIdChanged: (conversationId2) => {
        var _a4, _b3;
        tab.conversationId = conversationId2;
        (_b3 = (_a4 = this.callbacks).onTabConversationChanged) == null ? void 0 : _b3.call(_a4, tab.id, conversationId2);
      }
    });
    initializeTabUI(tab, this.plugin, {
      getProviderCatalogConfig: () => this.getProviderCatalogConfig(tab),
      onProviderChanged: (providerId) => {
        var _a4, _b3;
        (_b3 = (_a4 = this.callbacks).onTabProviderChanged) == null ? void 0 : _b3.call(_a4, tab.id, providerId);
        void this.prewarmProviderTab(tab).catch(() => {
        });
      }
    });
    initializeTabControllers(
      tab,
      this.plugin,
      this.view,
      (forkContext) => this.handleForkRequest(forkContext),
      (conversationId2) => this.openConversation(conversationId2),
      () => this.getProviderCatalogConfig(tab)
    );
    wireTabInputEvents(tab, this.plugin);
    this.tabs.set(tab.id, tab);
    (_b2 = (_a3 = this.callbacks).onTabCreated) == null ? void 0 : _b2.call(_a3, tab);
    if (!this.isRestoringState && (activate || !this.activeTabId)) {
      await this.switchToTab(tab.id);
    } else if (!this.isRestoringState) {
      this.maybePrimeProviderRuntime(tab);
    }
    return tab;
  }
  /**
   * Switches to a different tab.
   * @param tabId The tab to switch to.
   */
  async switchToTab(tabId) {
    var _a3, _b2, _c, _d2;
    const tab = this.tabs.get(tabId);
    if (!tab) {
      return;
    }
    if (this.isSwitchingTab) {
      return;
    }
    this.isSwitchingTab = true;
    const previousTabId = this.activeTabId;
    try {
      if (previousTabId && previousTabId !== tabId) {
        const currentTab = this.tabs.get(previousTabId);
        if (currentTab) {
          deactivateTab(currentTab);
        }
      }
      this.activeTabId = tabId;
      activateTab(tab);
      if (tab.conversationId && tab.state.messages.length === 0) {
        await ((_a3 = tab.controllers.conversationController) == null ? void 0 : _a3.switchTo(tab.conversationId));
      } else if (tab.conversationId && tab.state.messages.length > 0 && tab.service && !tab.state.isStreaming && !tab.state.hasPendingConversationSave) {
        const conversation = this.plugin.getConversationSync(tab.conversationId);
        if (conversation) {
          const hasMessages = conversation.messages.length > 0;
          const externalContextPaths = hasMessages ? conversation.externalContextPaths || [] : this.plugin.settings.persistentExternalContextPaths || [];
          tab.service.syncConversationState(conversation, externalContextPaths);
        }
      } else if (!tab.conversationId && tab.state.messages.length === 0) {
        (_b2 = tab.controllers.conversationController) == null ? void 0 : _b2.initializeWelcome();
      }
      (_d2 = (_c = this.callbacks).onTabSwitched) == null ? void 0 : _d2.call(_c, previousTabId, tabId);
      this.maybePrimeProviderRuntime(tab);
    } finally {
      this.isSwitchingTab = false;
    }
  }
  /**
   * Closes a tab.
   * @param tabId The tab to close.
   * @param force If true, close even if streaming.
   * @returns True if the tab was closed.
   */
  async closeTab(tabId, force = false) {
    var _a3, _b2, _c;
    const tab = this.tabs.get(tabId);
    if (!tab) {
      return false;
    }
    if (tab.state.isStreaming && !force) {
      return false;
    }
    if (this.tabs.size === 1 && !tab.conversationId && tab.state.messages.length === 0) {
      return false;
    }
    await ((_a3 = tab.controllers.conversationController) == null ? void 0 : _a3.save());
    const tabIdsBefore = Array.from(this.tabs.keys());
    const closingIndex = tabIdsBefore.indexOf(tabId);
    await destroyTab(tab);
    this.providerCommandWarmups.delete(tabId);
    this.providerCommandCache.delete(tabId);
    this.tabs.delete(tabId);
    (_c = (_b2 = this.callbacks).onTabClosed) == null ? void 0 : _c.call(_b2, tabId);
    if (this.activeTabId === tabId) {
      this.activeTabId = null;
      if (this.tabs.size > 0) {
        const fallbackTabId = closingIndex === 0 ? tabIdsBefore[1] : tabIdsBefore[closingIndex - 1];
        if (fallbackTabId && this.tabs.has(fallbackTabId)) {
          await this.switchToTab(fallbackTabId);
        }
      } else {
        await this.createTab();
      }
    }
    return true;
  }
  // ============================================
  // Tab Queries
  // ============================================
  /** Gets the currently active tab. */
  getActiveTab() {
    var _a3;
    return this.activeTabId ? (_a3 = this.tabs.get(this.activeTabId)) != null ? _a3 : null : null;
  }
  /** Gets the active tab ID. */
  getActiveTabId() {
    return this.activeTabId;
  }
  /** Gets a tab by ID. */
  getTab(tabId) {
    var _a3;
    return (_a3 = this.tabs.get(tabId)) != null ? _a3 : null;
  }
  /** Gets all tabs. */
  getAllTabs() {
    return Array.from(this.tabs.values());
  }
  /** Gets the number of tabs. */
  getTabCount() {
    return this.tabs.size;
  }
  /** Checks if more tabs can be created. */
  canCreateTab() {
    return this.tabs.size < this.getMaxTabs();
  }
  // ============================================
  // Tab Bar Data
  // ============================================
  /** Gets data for rendering the tab bar. */
  getTabBarItems() {
    const items = [];
    let index = 1;
    for (const tab of this.tabs.values()) {
      items.push({
        id: tab.id,
        index: index++,
        title: getTabTitle(tab, this.plugin),
        providerId: getTabProviderId(tab, this.plugin),
        isActive: tab.id === this.activeTabId,
        isStreaming: tab.state.isStreaming,
        needsAttention: tab.state.needsAttention,
        canClose: this.tabs.size > 1 || !tab.state.isStreaming
      });
    }
    return items;
  }
  // ============================================
  // Conversation Management
  // ============================================
  /**
   * Opens a conversation in a new tab or existing tab.
   * @param conversationId The conversation to open.
   * @param options Controls tab creation behavior (backward-compatible with boolean).
   */
  async openConversation(conversationId, options = false) {
    var _a3, _b2, _c, _d2;
    const preferNewTab = typeof options === "boolean" ? options : (_a3 = options.preferNewTab) != null ? _a3 : false;
    const activate = typeof options === "boolean" ? true : (_b2 = options.activate) != null ? _b2 : true;
    for (const tab of this.tabs.values()) {
      if (tab.conversationId === conversationId) {
        await this.switchToTab(tab.id);
        return;
      }
    }
    const crossViewResult = this.plugin.findConversationAcrossViews(conversationId);
    const isSameView = (crossViewResult == null ? void 0 : crossViewResult.view) === this.view;
    if (crossViewResult && !isSameView) {
      this.plugin.app.workspace.revealLeaf(crossViewResult.view.leaf);
      await ((_c = crossViewResult.view.getTabManager()) == null ? void 0 : _c.switchToTab(crossViewResult.tabId));
      return;
    }
    if (preferNewTab && this.canCreateTab()) {
      await this.createTab(conversationId, void 0, { activate });
    } else {
      const activeTab = this.getActiveTab();
      if (activeTab) {
        await ((_d2 = activeTab.controllers.conversationController) == null ? void 0 : _d2.switchTo(conversationId));
      }
    }
  }
  /**
   * Creates a new conversation in the active tab.
   */
  async createNewConversation() {
    var _a3;
    const activeTab = this.getActiveTab();
    if (activeTab) {
      await ((_a3 = activeTab.controllers.conversationController) == null ? void 0 : _a3.createNew());
      activeTab.conversationId = activeTab.state.currentConversationId;
      this.maybePrimeProviderRuntime(activeTab);
    }
  }
  invalidateProviderCommandCaches(providerIds) {
    var _a3, _b2;
    for (const tab of this.filterTabsByProvider(providerIds, (tab2) => getTabProviderId(tab2, this.plugin))) {
      this.providerCommandWarmups.delete(tab.id);
      this.providerCommandCache.delete(tab.id);
      (_b2 = (_a3 = tab.ui) == null ? void 0 : _a3.slashCommandDropdown) == null ? void 0 : _b2.resetSdkSkillsCache();
    }
  }
  primeProviderRuntime(providerIds) {
    for (const tab of this.filterTabsByProvider(providerIds, (tab2) => {
      var _a3, _b2;
      return (_b2 = (_a3 = tab2.service) == null ? void 0 : _a3.providerId) != null ? _b2 : tab2.providerId;
    })) {
      this.maybePrimeProviderRuntime(tab);
    }
  }
  *filterTabsByProvider(providerIds, resolve8) {
    const filter = providerIds ? new Set(Array.isArray(providerIds) ? providerIds : [providerIds]) : null;
    for (const tab of this.tabs.values()) {
      if (filter && !filter.has(resolve8(tab))) {
        continue;
      }
      yield tab;
    }
  }
  // ============================================
  // Fork
  // ============================================
  async handleForkRequest(context) {
    const target = await chooseForkTarget(this.plugin.app);
    if (!target) return;
    if (target === "new-tab") {
      const tab = await this.forkToNewTab(context);
      if (!tab) {
        const maxTabs = this.getMaxTabs();
        new import_obsidian43.Notice(t("chat.fork.maxTabsReached", { count: String(maxTabs) }));
        return;
      }
      new import_obsidian43.Notice(t("chat.fork.notice"));
    } else {
      const success2 = await this.forkInCurrentTab(context);
      if (!success2) {
        new import_obsidian43.Notice(t("chat.fork.failed", { error: t("chat.fork.errorNoActiveTab") }));
        return;
      }
      new import_obsidian43.Notice(t("chat.fork.noticeCurrentTab"));
    }
  }
  async forkToNewTab(context) {
    const maxTabs = this.getMaxTabs();
    if (this.tabs.size >= maxTabs) {
      return null;
    }
    const conversationId = await this.createForkConversation(context);
    try {
      return await this.createTab(conversationId);
    } catch (error48) {
      await this.plugin.deleteConversation(conversationId).catch(() => {
      });
      throw error48;
    }
  }
  async forkInCurrentTab(context) {
    const activeTab = this.getActiveTab();
    if (!(activeTab == null ? void 0 : activeTab.controllers.conversationController)) return false;
    const conversationId = await this.createForkConversation(context);
    try {
      await activeTab.controllers.conversationController.switchTo(conversationId);
    } catch (error48) {
      await this.plugin.deleteConversation(conversationId).catch(() => {
      });
      throw error48;
    }
    return true;
  }
  async createForkConversation(context) {
    const conversation = await this.plugin.createConversation({
      providerId: context.providerId
    });
    const title = context.sourceTitle ? this.buildForkTitle(context.sourceTitle, context.forkAtUserMessage) : void 0;
    const forkProviderState = ProviderRegistry.getConversationHistoryService(conversation.providerId).buildForkProviderState(
      context.sourceSessionId,
      context.resumeAt,
      context.sourceProviderState
    );
    await this.plugin.updateConversation(conversation.id, {
      messages: context.messages,
      providerState: forkProviderState,
      ...title && { title },
      ...context.currentNote && { currentNote: context.currentNote }
    });
    return conversation.id;
  }
  buildForkTitle(sourceTitle, forkAtUserMessage) {
    const MAX_TITLE_LENGTH2 = 50;
    const forkSuffix = forkAtUserMessage ? ` (#${forkAtUserMessage})` : "";
    const forkPrefix = "Fork: ";
    const maxSourceLength = MAX_TITLE_LENGTH2 - forkPrefix.length - forkSuffix.length;
    const truncatedSource = sourceTitle.length > maxSourceLength ? sourceTitle.slice(0, maxSourceLength - 1) + "\u2026" : sourceTitle;
    let title = forkPrefix + truncatedSource + forkSuffix;
    const existingTitles = new Set(this.plugin.getConversationList().map((c) => c.title));
    if (existingTitles.has(title)) {
      let n = 2;
      while (existingTitles.has(`${title} ${n}`)) n++;
      title = `${title} ${n}`;
    }
    return title;
  }
  // ============================================
  // Persistence
  // ============================================
  /** Gets the state to persist. */
  getPersistedState() {
    const openTabs = [];
    for (const tab of this.tabs.values()) {
      openTabs.push({
        ...tab.lifecycleState === "blank" && tab.draftModel ? { draftModel: tab.draftModel } : {},
        tabId: tab.id,
        conversationId: tab.conversationId
      });
    }
    return {
      openTabs,
      activeTabId: this.activeTabId
    };
  }
  /** Restores state from persisted data. */
  async restoreState(state) {
    var _a3, _b2, _c;
    this.isRestoringState = true;
    try {
      for (const tabState of state.openTabs) {
        try {
          await this.createTab(tabState.conversationId, tabState.tabId, {
            activate: false,
            ...typeof tabState.draftModel === "string" ? { draftModel: tabState.draftModel } : {}
          });
        } catch (e2) {
        }
      }
    } finally {
      this.isRestoringState = false;
    }
    const fallbackTabId = (_c = (_b2 = (_a3 = state.openTabs.find((tabState) => this.tabs.has(tabState.tabId))) == null ? void 0 : _a3.tabId) != null ? _b2 : Array.from(this.tabs.keys())[0]) != null ? _c : null;
    const targetTabId = state.activeTabId && this.tabs.has(state.activeTabId) ? state.activeTabId : fallbackTabId;
    if (targetTabId) {
      try {
        await this.switchToTab(targetTabId);
      } catch (e2) {
      }
    }
    if (this.tabs.size === 0) {
      await this.createTab();
    }
  }
  // ============================================
  // SDK Commands (Shared)
  // ============================================
  /**
   * Gets provider-scoped SDK supported commands for a tab.
   * Reuses a ready runtime from the same provider when available to avoid
   * leaking commands across providers in mixed-provider workspaces.
   * @returns Array of SDK commands, or empty array if no service is ready.
   */
  async getSdkCommands(tabId) {
    var _a3, _b2;
    const targetTab = (_a3 = tabId ? this.tabs.get(tabId) : this.getActiveTab()) != null ? _a3 : null;
    if (!targetTab) {
      return [];
    }
    const providerId = getTabProviderId(targetTab, this.plugin);
    const staticCapabilities = ProviderRegistry.getCapabilities(providerId);
    if (!staticCapabilities.supportsProviderCommands) {
      return [];
    }
    const catalog = ProviderWorkspaceRegistry.getCommandCatalog(providerId);
    const runtimeCommandLoader = ProviderWorkspaceRegistry.getRuntimeCommandLoader(providerId);
    const context = await this.buildProviderWarmupContext(targetTab, providerId);
    if (targetTab.lifecycleState === "blank" && runtimeCommandLoader && (context.warmupMode !== "commands" || targetTab.id !== this.activeTabId)) {
      catalog == null ? void 0 : catalog.setRuntimeCommands([]);
      return [];
    }
    let sdkCommands = [];
    const targetService = targetTab.service;
    if ((targetService == null ? void 0 : targetService.providerId) === providerId && targetService.isReady()) {
      sdkCommands = await targetService.getSupportedCommands();
    } else if (!runtimeCommandLoader) {
      for (const tab of this.tabs.values()) {
        if (tab.id === targetTab.id) {
          continue;
        }
        if (((_b2 = tab.service) == null ? void 0 : _b2.providerId) === providerId && tab.service.isReady()) {
          sdkCommands = await tab.service.getSupportedCommands();
          break;
        }
      }
    }
    if (sdkCommands.length === 0) {
      sdkCommands = await this.ensureProviderCommandRuntime(targetTab, providerId, context);
    }
    catalog == null ? void 0 : catalog.setRuntimeCommands(sdkCommands);
    return sdkCommands;
  }
  async ensureProviderCommandRuntime(tab, providerId, warmupContext) {
    if (!this.isProviderCommandLoaderAvailable(providerId)) {
      return [];
    }
    const context = await this.buildProviderCommandContext(
      tab,
      providerId,
      warmupContext != null ? warmupContext : await this.buildProviderWarmupContext(tab, providerId)
    );
    const cached2 = this.providerCommandCache.get(tab.id);
    if ((!context.runtime || !context.runtime.isReady()) && cached2 && cached2.key === context.cacheKey) {
      return cached2.commands.map((command) => ({ ...command }));
    }
    const existing = this.providerCommandWarmups.get(tab.id);
    if ((existing == null ? void 0 : existing.key) === context.cacheKey) {
      return await existing.promise;
    }
    this.providerCommandWarmups.delete(tab.id);
    const warmup = this.warmProviderCommandRuntime(tab, providerId, context).finally(() => {
      var _a3;
      if (((_a3 = this.providerCommandWarmups.get(tab.id)) == null ? void 0 : _a3.promise) === warmup) {
        this.providerCommandWarmups.delete(tab.id);
      }
    });
    this.providerCommandWarmups.set(tab.id, {
      key: context.cacheKey,
      promise: warmup
    });
    return await warmup;
  }
  maybePrimeProviderRuntime(tab) {
    void this.prewarmProviderTab(tab).catch(() => {
    });
  }
  isProviderCommandLoaderAvailable(providerId) {
    const loader = ProviderWorkspaceRegistry.getRuntimeCommandLoader(providerId);
    if (!loader) return false;
    return loader.isAvailable(this.plugin.settings);
  }
  async prewarmProviderTab(tab) {
    var _a3, _b2, _c;
    const providerId = (_b2 = (_a3 = tab.service) == null ? void 0 : _a3.providerId) != null ? _b2 : tab.providerId;
    const context = await this.buildProviderWarmupContext(tab, providerId);
    const hasReadyRuntime = ((_c = tab.service) == null ? void 0 : _c.providerId) === providerId && tab.service.isReady();
    if (!hasReadyRuntime && tab.id !== this.activeTabId) {
      return;
    }
    switch (context.warmupMode) {
      case "commands":
        await this.getSdkCommands(tab.id);
        return;
      case "runtime":
        await this.ensureProviderTabRuntimeReady(tab, providerId, context);
        return;
      default:
        return;
    }
  }
  async ensureProviderTabRuntimeReady(tab, providerId, context) {
    var _a3;
    if (!context.runtime || context.runtime.providerId !== providerId || !tab.serviceInitialized) {
      await initializeTabService(tab, this.plugin, context.conversation);
      setupServiceCallbacks(tab, this.plugin);
    }
    const runtime = ((_a3 = tab.service) == null ? void 0 : _a3.providerId) === providerId ? tab.service : null;
    if (!runtime) {
      return;
    }
    runtime.syncConversationState(context.conversation, context.externalContextPaths);
    await runtime.ensureReady();
    if (ProviderRegistry.getCapabilities(providerId).supportsProviderCommands) {
      await this.getSdkCommands(tab.id);
    }
  }
  async buildProviderWarmupContext(tab, providerId) {
    var _a3, _b2, _c, _d2, _e, _f;
    const conversation = tab.conversationId ? await this.plugin.getConversationById(tab.conversationId) : null;
    const hasConversationContext = ((_a3 = conversation == null ? void 0 : conversation.messages.length) != null ? _a3 : 0) > 0;
    const externalContextPaths = (_e = (_b2 = tab.ui.externalContextSelector) == null ? void 0 : _b2.getExternalContexts()) != null ? _e : hasConversationContext ? (_c = conversation == null ? void 0 : conversation.externalContextPaths) != null ? _c : [] : (_d2 = this.plugin.settings.persistentExternalContextPaths) != null ? _d2 : [];
    const runtime = ((_f = tab.service) == null ? void 0 : _f.providerId) === providerId ? tab.service : null;
    const warmupMode = this.resolveProviderTabWarmupMode({
      conversation,
      externalContextPaths,
      plugin: this.plugin,
      runtime,
      tab: {
        conversationId: tab.conversationId,
        draftModel: tab.draftModel,
        lifecycleState: tab.lifecycleState,
        providerId
      }
    });
    return {
      conversation,
      externalContextPaths,
      runtime,
      tab: {
        conversationId: tab.conversationId,
        draftModel: tab.draftModel,
        lifecycleState: tab.lifecycleState,
        providerId
      },
      warmupMode
    };
  }
  resolveProviderTabWarmupMode(context) {
    var _a3, _b2;
    return (_b2 = (_a3 = ProviderWorkspaceRegistry.getTabWarmupPolicy(context.tab.providerId)) == null ? void 0 : _a3.resolveMode(context)) != null ? _b2 : "none";
  }
  buildProviderCommandContext(tab, providerId, warmupContext) {
    var _a3, _b2, _c, _d2, _e, _f, _g;
    const providerSettings = ProviderSettingsCoordinator.getProviderSettingsSnapshot(
      this.plugin.settings,
      providerId
    );
    return {
      ...warmupContext,
      cacheKey: JSON.stringify({
        allowSessionCreation: warmupContext.warmupMode === "commands" && tab.lifecycleState === "blank" && tab.id === this.activeTabId,
        conversationId: (_b2 = (_a3 = warmupContext.conversation) == null ? void 0 : _a3.id) != null ? _b2 : null,
        draftModel: (_c = tab.draftModel) != null ? _c : null,
        externalContextPaths: warmupContext.externalContextPaths,
        lifecycleState: tab.lifecycleState,
        providerId,
        providerSettings,
        providerState: (_e = (_d2 = warmupContext.conversation) == null ? void 0 : _d2.providerState) != null ? _e : null,
        sessionId: (_g = (_f = warmupContext.conversation) == null ? void 0 : _f.sessionId) != null ? _g : null,
        warmupMode: warmupContext.warmupMode
      })
    };
  }
  async warmProviderCommandRuntime(tab, providerId, context) {
    const catalog = ProviderWorkspaceRegistry.getCommandCatalog(providerId);
    const loader = ProviderWorkspaceRegistry.getRuntimeCommandLoader(providerId);
    if (!catalog || !loader) {
      return [];
    }
    const commands = await loader.loadCommands({
      allowSessionCreation: context.warmupMode === "commands" && tab.lifecycleState === "blank" && tab.id === this.activeTabId,
      conversation: context.conversation,
      externalContextPaths: context.externalContextPaths,
      plugin: this.plugin,
      runtime: context.runtime
    });
    if (!context.runtime || !context.runtime.isReady()) {
      this.providerCommandCache.set(tab.id, {
        key: context.cacheKey,
        commands: commands.map((command) => ({ ...command }))
      });
    } else {
      this.providerCommandCache.delete(tab.id);
    }
    catalog.setRuntimeCommands(commands);
    return commands;
  }
  // ============================================
  // Provider Command Catalog
  // ============================================
  getProviderCatalogConfig(tab) {
    const providerId = getTabProviderId(tab, this.plugin);
    const catalog = ProviderWorkspaceRegistry.getCommandCatalog(providerId);
    if (!catalog) return null;
    return {
      config: catalog.getDropdownConfig(),
      getEntries: async () => {
        await this.getSdkCommands(tab.id);
        return catalog.listDropdownEntries({ includeBuiltIns: false });
      }
    };
  }
  // ============================================
  // Broadcast
  // ============================================
  /**
   * Broadcasts a function call to all initialized tab runtimes.
   * Used by settings managers to apply configuration changes to all tabs.
   * @param fn Function to call on each runtime.
   */
  async broadcastToAllTabs(fn) {
    await this.broadcastToTabs(this.tabs.values(), fn);
  }
  async broadcastToProviderTabs(providerIds, fn) {
    await this.broadcastToTabs(
      this.filterTabsByProvider(providerIds, (tab) => {
        var _a3, _b2;
        return (_b2 = (_a3 = tab.service) == null ? void 0 : _a3.providerId) != null ? _b2 : tab.providerId;
      }),
      fn
    );
  }
  async broadcastToTabs(tabs, fn) {
    const promises2 = [];
    for (const tab of tabs) {
      if (tab.service && tab.serviceInitialized) {
        promises2.push(
          fn(tab.service).catch(() => {
          })
        );
      }
    }
    await Promise.all(promises2);
  }
  // ============================================
  // Cleanup
  // ============================================
  /** Destroys all tabs and cleans up resources. */
  async destroy() {
    await Promise.all(
      Array.from(this.tabs.values()).map(
        (tab) => {
          var _a3, _b2;
          return (_b2 = (_a3 = tab.controllers.conversationController) == null ? void 0 : _a3.save()) != null ? _b2 : Promise.resolve();
        }
      )
    );
    await Promise.all(Array.from(this.tabs.values()).map((tab) => destroyTab(tab)));
    this.tabs.clear();
    this.activeTabId = null;
  }
};

// src/features/chat/ClaudianView.ts
var ClaudianView = class extends import_obsidian44.ItemView {
  constructor(leaf, plugin) {
    super(leaf);
    // Tab management
    this.tabManager = null;
    this.tabBar = null;
    this.tabBarContainerEl = null;
    this.tabContentEl = null;
    this.navRowContent = null;
    // DOM Elements
    this.viewContainerEl = null;
    this.headerEl = null;
    this.titleSlotEl = null;
    this.logoEl = null;
    this.titleTextEl = null;
    this.headerActionsEl = null;
    this.headerActionsContent = null;
    // Header elements
    this.historyDropdown = null;
    // Event refs for cleanup
    this.eventRefs = [];
    // Debouncing for tab bar updates
    this.pendingTabBarUpdate = null;
    // Debouncing for tab state persistence
    this.pendingPersist = null;
    this.plugin = plugin;
    const originalLoad = Object.getPrototypeOf(this).load.bind(this);
    Object.defineProperty(this, "load", {
      value: async () => {
        if (!this.containerEl) {
          this.containerEl = createDiv({ cls: "view-content" });
        }
        try {
          return await originalLoad();
        } catch (e2) {
        }
      },
      writable: false,
      configurable: false
    });
  }
  getViewType() {
    return VIEW_TYPE_CLAUDIAN;
  }
  getDisplayText() {
    return "Claudian";
  }
  getIcon() {
    return "bot";
  }
  /** Refreshes model-dependent UI across all tabs (used after settings/env changes). */
  refreshModelSelector() {
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i, _j2;
    for (const tab of (_b2 = (_a3 = this.tabManager) == null ? void 0 : _a3.getAllTabs()) != null ? _b2 : []) {
      onProviderAvailabilityChanged(tab, this.plugin);
      const providerId = getTabProviderId(tab, this.plugin);
      const providerSettings = ProviderSettingsCoordinator.getProviderSettingsSnapshot(
        this.plugin.settings,
        providerId
      );
      const model = providerSettings.model;
      const uiConfig = ProviderRegistry.getChatUIConfig(providerId);
      const capabilities = ProviderRegistry.getCapabilities(providerId);
      const contextWindow = uiConfig.getContextWindowSize(
        model,
        providerSettings.customContextLimits
      );
      if (tab.state.usage) {
        tab.state.usage = recalculateUsageForModel(tab.state.usage, model, contextWindow);
      }
      (_c = tab.ui.modelSelector) == null ? void 0 : _c.updateDisplay();
      (_d2 = tab.ui.modelSelector) == null ? void 0 : _d2.renderOptions();
      (_e = tab.ui.modeSelector) == null ? void 0 : _e.updateDisplay();
      (_f = tab.ui.modeSelector) == null ? void 0 : _f.renderOptions();
      (_g = tab.ui.thinkingBudgetSelector) == null ? void 0 : _g.updateDisplay();
      (_h = tab.ui.permissionToggle) == null ? void 0 : _h.updateDisplay();
      (_i = tab.ui.serviceTierToggle) == null ? void 0 : _i.updateDisplay();
      tab.dom.inputWrapper.toggleClass(
        "claudian-input-plan-mode",
        providerSettings.permissionMode === "plan" && capabilities.supportsPlanMode
      );
    }
    (_j2 = this.tabManager) == null ? void 0 : _j2.primeProviderRuntime();
  }
  invalidateProviderCommandCaches(providerIds) {
    var _a3;
    (_a3 = this.tabManager) == null ? void 0 : _a3.invalidateProviderCommandCaches(providerIds);
  }
  /** Updates provider-scoped hidden commands on all tabs after settings changes. */
  updateHiddenProviderCommands() {
    var _a3, _b2, _c;
    for (const tab of (_b2 = (_a3 = this.tabManager) == null ? void 0 : _a3.getAllTabs()) != null ? _b2 : []) {
      (_c = tab.ui.slashCommandDropdown) == null ? void 0 : _c.setHiddenCommands(
        getHiddenProviderCommandSet(this.plugin.settings, getTabProviderId(tab, this.plugin))
      );
    }
  }
  async onOpen() {
    var _a3, _b2;
    if (!this.containerEl) {
      return;
    }
    let container = (_a3 = this.contentEl) != null ? _a3 : this.containerEl.children[1];
    if (!container) {
      container = this.containerEl.createDiv();
    }
    this.viewContainerEl = container;
    this.viewContainerEl.empty();
    this.viewContainerEl.addClass("claudian-container");
    const header = this.viewContainerEl.createDiv({ cls: "claudian-header" });
    this.buildHeader(header);
    this.navRowContent = this.buildNavRowContent();
    this.tabContentEl = this.viewContainerEl.createDiv({ cls: "claudian-tab-content-container" });
    this.tabManager = new TabManager(
      this.plugin,
      this.tabContentEl,
      this,
      {
        onTabCreated: () => {
          this.updateTabBar();
          this.updateNavRowLocation();
          this.persistTabState();
          this.syncProviderBrandColor();
        },
        onTabSwitched: () => {
          this.updateTabBar();
          this.updateHistoryDropdown();
          this.updateNavRowLocation();
          this.persistTabState();
          this.syncProviderBrandColor();
        },
        onTabClosed: () => {
          this.updateTabBar();
          this.persistTabState();
        },
        onTabStreamingChanged: () => this.updateTabBar(),
        onTabTitleChanged: () => this.updateTabBar(),
        onTabAttentionChanged: () => this.updateTabBar(),
        onTabConversationChanged: () => {
          this.updateTabBar();
          this.persistTabState();
          this.syncProviderBrandColor();
        },
        onTabProviderChanged: () => {
          this.updateTabBar();
          this.syncProviderBrandColor();
        }
      }
    );
    this.wireEventHandlers();
    await this.restoreOrCreateTabs();
    this.syncProviderBrandColor();
    this.updateLayoutForPosition();
    (_b2 = this.tabManager) == null ? void 0 : _b2.primeProviderRuntime();
  }
  async onClose() {
    var _a3, _b2;
    if (this.pendingTabBarUpdate !== null) {
      cancelAnimationFrame(this.pendingTabBarUpdate);
      this.pendingTabBarUpdate = null;
    }
    for (const ref of this.eventRefs) {
      this.plugin.app.vault.offref(ref);
    }
    this.eventRefs = [];
    await this.persistTabStateImmediate();
    await ((_a3 = this.tabManager) == null ? void 0 : _a3.destroy());
    this.tabManager = null;
    (_b2 = this.tabBar) == null ? void 0 : _b2.destroy();
    this.tabBar = null;
  }
  // ============================================
  // UI Building
  // ============================================
  buildHeader(header) {
    this.headerEl = header;
    this.titleSlotEl = header.createDiv({ cls: "claudian-title-slot" });
    this.logoEl = this.titleSlotEl.createSpan({ cls: "claudian-logo" });
    this.syncHeaderLogo(DEFAULT_CHAT_PROVIDER_ID);
    this.titleTextEl = this.titleSlotEl.createEl("h4", { text: "Claudian", cls: "claudian-title-text" });
    this.headerActionsEl = header.createDiv({ cls: "claudian-header-actions claudian-header-actions-slot" });
    this.headerActionsEl.style.display = "none";
  }
  /**
   * Builds the nav row content (tab badges + header actions).
   * This is called once and the content is moved between locations.
   */
  buildNavRowContent() {
    const fragment = document.createDocumentFragment();
    this.tabBarContainerEl = document.createElement("div");
    this.tabBarContainerEl.className = "claudian-tab-bar-container";
    this.tabBar = new TabBar(this.tabBarContainerEl, {
      onTabClick: (tabId) => this.handleTabClick(tabId),
      onTabClose: (tabId) => this.handleTabClose(tabId),
      onNewTab: () => this.createNewTab()
    });
    fragment.appendChild(this.tabBarContainerEl);
    this.headerActionsContent = document.createElement("div");
    this.headerActionsContent.className = "claudian-header-actions";
    const newTabBtn = this.headerActionsContent.createDiv({ cls: "claudian-header-btn claudian-new-tab-btn" });
    (0, import_obsidian44.setIcon)(newTabBtn, "square-plus");
    newTabBtn.setAttribute("aria-label", "New tab");
    newTabBtn.addEventListener("click", async () => {
      await this.createNewTab();
    });
    const newBtn = this.headerActionsContent.createDiv({ cls: "claudian-header-btn" });
    (0, import_obsidian44.setIcon)(newBtn, "square-pen");
    newBtn.setAttribute("aria-label", "New conversation");
    newBtn.addEventListener("click", async () => {
      var _a3;
      await ((_a3 = this.tabManager) == null ? void 0 : _a3.createNewConversation());
      this.updateHistoryDropdown();
    });
    const historyContainer = this.headerActionsContent.createDiv({ cls: "claudian-history-container" });
    const historyBtn = historyContainer.createDiv({ cls: "claudian-header-btn" });
    (0, import_obsidian44.setIcon)(historyBtn, "history");
    historyBtn.setAttribute("aria-label", "Chat history");
    this.historyDropdown = historyContainer.createDiv({ cls: "claudian-history-menu" });
    historyBtn.addEventListener("click", (e2) => {
      e2.stopPropagation();
      this.toggleHistoryDropdown();
    });
    fragment.appendChild(this.headerActionsContent);
    const wrapper = document.createElement("div");
    wrapper.style.display = "contents";
    wrapper.appendChild(fragment);
    return wrapper;
  }
  /**
   * Moves nav row content based on tabBarPosition setting.
   * - 'input' mode: Both tab badges and actions go to active tab's navRowEl
   * - 'header' mode: Tab badges go to title slot (after logo), actions go to header right side
   */
  updateNavRowLocation() {
    var _a3;
    if (!this.tabBarContainerEl || !this.headerActionsContent) return;
    const isHeaderMode = this.plugin.settings.tabBarPosition === "header";
    if (isHeaderMode) {
      if (this.titleSlotEl) {
        this.titleSlotEl.appendChild(this.tabBarContainerEl);
      }
      if (this.headerActionsEl) {
        this.headerActionsEl.appendChild(this.headerActionsContent);
        this.headerActionsEl.style.display = "flex";
      }
    } else {
      const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab();
      if (activeTab && this.navRowContent) {
        this.navRowContent.appendChild(this.tabBarContainerEl);
        this.navRowContent.appendChild(this.headerActionsContent);
        activeTab.dom.navRowEl.appendChild(this.navRowContent);
      }
      if (this.headerActionsEl) {
        this.headerActionsEl.style.display = "none";
      }
    }
  }
  /**
   * Updates layout when tabBarPosition setting changes.
   * Called from settings when user changes the tab bar position.
   */
  updateLayoutForPosition() {
    if (!this.viewContainerEl) return;
    const isHeaderMode = this.plugin.settings.tabBarPosition === "header";
    this.viewContainerEl.toggleClass("claudian-container--header-mode", isHeaderMode);
    this.updateNavRowLocation();
    this.updateTabBarVisibility();
  }
  // ============================================
  // Tab Management
  // ============================================
  handleTabClick(tabId) {
    var _a3;
    (_a3 = this.tabManager) == null ? void 0 : _a3.switchToTab(tabId);
  }
  async handleTabClose(tabId) {
    var _a3, _b2, _c;
    const tab = (_a3 = this.tabManager) == null ? void 0 : _a3.getTab(tabId);
    const force = (_b2 = tab == null ? void 0 : tab.state.isStreaming) != null ? _b2 : false;
    await ((_c = this.tabManager) == null ? void 0 : _c.closeTab(tabId, force));
    this.updateTabBarVisibility();
  }
  async createNewTab() {
    var _a3, _b2;
    const tab = await ((_a3 = this.tabManager) == null ? void 0 : _a3.createTab());
    if (!tab) {
      const maxTabs = (_b2 = this.plugin.settings.maxTabs) != null ? _b2 : 3;
      new import_obsidian44.Notice(`Maximum ${maxTabs} tabs allowed`);
      return;
    }
    this.updateTabBarVisibility();
  }
  updateTabBar() {
    if (!this.tabManager || !this.tabBar) return;
    if (this.pendingTabBarUpdate !== null) {
      cancelAnimationFrame(this.pendingTabBarUpdate);
    }
    this.pendingTabBarUpdate = requestAnimationFrame(() => {
      this.pendingTabBarUpdate = null;
      if (!this.tabManager || !this.tabBar) return;
      const items = this.tabManager.getTabBarItems();
      this.tabBar.update(items);
      this.updateTabBarVisibility();
    });
  }
  updateTabBarVisibility() {
    if (!this.tabBarContainerEl || !this.tabManager) return;
    const tabCount = this.tabManager.getTabCount();
    const showTabBar = tabCount >= 2;
    const isHeaderMode = this.plugin.settings.tabBarPosition === "header";
    this.tabBarContainerEl.style.display = showTabBar ? "flex" : "none";
    const hideBranding = showTabBar && isHeaderMode;
    if (this.logoEl) {
      this.logoEl.style.display = hideBranding ? "none" : "";
    }
    if (this.titleTextEl) {
      this.titleTextEl.style.display = hideBranding ? "none" : "";
    }
  }
  /** Sets `data-provider` on the root container so CSS brand color follows the active provider. */
  syncProviderBrandColor() {
    var _a3;
    if (!this.viewContainerEl) return;
    const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab();
    const providerId = activeTab ? getTabProviderId(activeTab, this.plugin) : DEFAULT_CHAT_PROVIDER_ID;
    this.viewContainerEl.dataset.provider = providerId;
    this.syncHeaderLogo(providerId);
  }
  /** Rebuilds the header logo SVG to match the given provider. */
  syncHeaderLogo(providerId) {
    var _a3, _b2;
    if (!this.logoEl) return;
    const icon = (_b2 = (_a3 = ProviderRegistry.getChatUIConfig(providerId)).getProviderIcon) == null ? void 0 : _b2.call(_a3);
    if (!icon) return;
    const existing = this.logoEl.querySelector("svg");
    if ((existing == null ? void 0 : existing.getAttribute("data-provider")) === providerId) return;
    this.logoEl.empty();
    const svg = createProviderIconSvg(icon, {
      dataProvider: providerId,
      height: 18,
      width: 18
    });
    this.logoEl.appendChild(svg);
  }
  // ============================================
  // History Dropdown
  // ============================================
  toggleHistoryDropdown() {
    if (!this.historyDropdown) return;
    const isVisible = this.historyDropdown.hasClass("visible");
    if (isVisible) {
      this.historyDropdown.removeClass("visible");
    } else {
      this.updateHistoryDropdown();
      this.historyDropdown.addClass("visible");
    }
  }
  updateHistoryDropdown() {
    var _a3;
    if (!this.historyDropdown) return;
    this.historyDropdown.empty();
    const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab();
    const conversationController = activeTab == null ? void 0 : activeTab.controllers.conversationController;
    if (conversationController) {
      conversationController.renderHistoryDropdown(this.historyDropdown, {
        onSelectConversation: (id) => this.openHistoryConversation(id),
        onOpenConversationInNewTab: (id, activate) => this.openHistoryConversationInNewTab(id, activate),
        getConversationOpenState: (id) => this.getHistoryConversationOpenState(id)
      });
    }
  }
  async openHistoryConversation(conversationId) {
    var _a3, _b2;
    await ((_a3 = this.tabManager) == null ? void 0 : _a3.openConversation(conversationId));
    (_b2 = this.historyDropdown) == null ? void 0 : _b2.removeClass("visible");
  }
  async openHistoryConversationInNewTab(conversationId, activate = true) {
    var _a3, _b2;
    await ((_a3 = this.tabManager) == null ? void 0 : _a3.openConversation(conversationId, {
      preferNewTab: true,
      activate
    }));
    (_b2 = this.historyDropdown) == null ? void 0 : _b2.removeClass("visible");
  }
  getHistoryConversationOpenState(conversationId) {
    var _a3;
    const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab();
    if ((activeTab == null ? void 0 : activeTab.conversationId) === conversationId) {
      return "current";
    }
    if (this.findTabWithConversation(conversationId)) {
      return "open";
    }
    const crossViewResult = this.plugin.findConversationAcrossViews(conversationId);
    if (crossViewResult && crossViewResult.view !== this) {
      return "open";
    }
    return "closed";
  }
  findTabWithConversation(conversationId) {
    var _a3, _b2, _c;
    const tabs = (_b2 = (_a3 = this.tabManager) == null ? void 0 : _a3.getAllTabs()) != null ? _b2 : [];
    return (_c = tabs.find((tab) => tab.conversationId === conversationId)) != null ? _c : null;
  }
  // ============================================
  // Event Wiring
  // ============================================
  wireEventHandlers() {
    this.registerDomEvent(document, "click", () => {
      var _a3;
      (_a3 = this.historyDropdown) == null ? void 0 : _a3.removeClass("visible");
    });
    this.registerDomEvent(this.containerEl, "keydown", (e2) => {
      var _a3, _b2;
      if (e2.key === "Tab" && e2.shiftKey && !e2.isComposing) {
        e2.preventDefault();
        const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab();
        if (!activeTab) return;
        const providerId = getTabProviderId(activeTab, this.plugin);
        if (!ProviderRegistry.getCapabilities(providerId).supportsPlanMode) return;
        const current = ProviderSettingsCoordinator.getProviderSettingsSnapshot(
          this.plugin.settings,
          providerId
        ).permissionMode;
        if (current === "plan") {
          const restoreMode = (_b2 = activeTab.state.prePlanPermissionMode) != null ? _b2 : "normal";
          activeTab.state.prePlanPermissionMode = null;
          updatePlanModeUI(activeTab, this.plugin, restoreMode);
        } else {
          activeTab.state.prePlanPermissionMode = current;
          updatePlanModeUI(activeTab, this.plugin, "plan");
        }
      }
    });
    this.scope = new import_obsidian44.Scope(this.app.scope);
    this.scope.register([], "Escape", () => {
      var _a3, _b2;
      const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab();
      if (activeTab == null ? void 0 : activeTab.state.isStreaming) {
        (_b2 = activeTab.controllers.inputController) == null ? void 0 : _b2.cancelStreaming();
      }
      return false;
    });
    const markCacheDirty = (includesFolders) => {
      var _a3, _b2;
      const mgr = (_b2 = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab()) == null ? void 0 : _b2.ui.fileContextManager;
      if (!mgr) return;
      mgr.markFileCacheDirty();
      if (includesFolders) mgr.markFolderCacheDirty();
    };
    this.eventRefs.push(
      this.plugin.app.vault.on("create", () => markCacheDirty(true)),
      this.plugin.app.vault.on("delete", () => markCacheDirty(true)),
      this.plugin.app.vault.on("rename", () => markCacheDirty(true)),
      this.plugin.app.vault.on("modify", () => markCacheDirty(false))
    );
    this.registerEvent(
      this.plugin.app.workspace.on("file-open", (file2) => {
        var _a3, _b2, _c;
        if (file2) {
          (_c = (_b2 = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab()) == null ? void 0 : _b2.ui.fileContextManager) == null ? void 0 : _c.handleFileOpen(file2);
        }
      })
    );
    this.registerDomEvent(document, "click", (e2) => {
      var _a3;
      const activeTab = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab();
      if (activeTab) {
        const fcm = activeTab.ui.fileContextManager;
        if (fcm && !fcm.containsElement(e2.target) && e2.target !== activeTab.dom.inputEl) {
          fcm.hideMentionDropdown();
        }
      }
    });
  }
  // ============================================
  // Persistence
  // ============================================
  async restoreOrCreateTabs() {
    if (!this.tabManager) return;
    const persistedState = await this.plugin.storage.getTabManagerState();
    if (persistedState && persistedState.openTabs.length > 0) {
      await this.tabManager.restoreState(persistedState);
      return;
    }
    await this.tabManager.createTab();
  }
  persistTabState() {
    if (this.pendingPersist !== null) {
      clearTimeout(this.pendingPersist);
    }
    this.pendingPersist = setTimeout(() => {
      this.pendingPersist = null;
      if (!this.tabManager) return;
      const state = this.tabManager.getPersistedState();
      this.plugin.persistTabManagerState(state).catch(() => {
      });
    }, 300);
  }
  /** Force immediate persistence (for onClose/onunload). */
  async persistTabStateImmediate() {
    if (this.pendingPersist !== null) {
      clearTimeout(this.pendingPersist);
      this.pendingPersist = null;
    }
    if (!this.tabManager) return;
    const state = this.tabManager.getPersistedState();
    await this.plugin.persistTabManagerState(state);
  }
  // ============================================
  // Public API
  // ============================================
  /** Gets the currently active tab. */
  getActiveTab() {
    var _a3, _b2;
    return (_b2 = (_a3 = this.tabManager) == null ? void 0 : _a3.getActiveTab()) != null ? _b2 : null;
  }
  /** Gets the tab manager. */
  getTabManager() {
    return this.tabManager;
  }
};

// src/features/inline-edit/ui/InlineEditModal.ts
var import_state2 = require("@codemirror/state");
var import_view2 = require("@codemirror/view");
var import_obsidian45 = require("obsidian");
init_path();
var showInlineEdit = import_state2.StateEffect.define();
var showDiff = import_state2.StateEffect.define();
var showInsertion = import_state2.StateEffect.define();
var hideInlineEdit = import_state2.StateEffect.define();
var activeController = null;
var DiffWidget = class extends import_view2.WidgetType {
  constructor(diffHtml, controller) {
    super();
    this.diffHtml = diffHtml;
    this.controller = controller;
  }
  toDOM() {
    const span = document.createElement("span");
    span.className = "claudian-inline-diff-replace";
    span.innerHTML = this.diffHtml;
    const btns = document.createElement("span");
    btns.className = "claudian-inline-diff-buttons";
    const rejectBtn = document.createElement("button");
    rejectBtn.className = "claudian-inline-diff-btn reject";
    rejectBtn.textContent = "\u2715";
    rejectBtn.title = "Reject (Esc)";
    rejectBtn.onclick = () => this.controller.reject();
    const acceptBtn = document.createElement("button");
    acceptBtn.className = "claudian-inline-diff-btn accept";
    acceptBtn.textContent = "\u2713";
    acceptBtn.title = "Accept (Enter)";
    acceptBtn.onclick = () => this.controller.accept();
    btns.appendChild(rejectBtn);
    btns.appendChild(acceptBtn);
    span.appendChild(btns);
    return span;
  }
  eq(other) {
    return this.diffHtml === other.diffHtml;
  }
  ignoreEvent() {
    return true;
  }
};
var InputWidget = class extends import_view2.WidgetType {
  constructor(controller) {
    super();
    this.controller = controller;
  }
  toDOM() {
    return this.controller.createInputDOM();
  }
  eq() {
    return false;
  }
  ignoreEvent() {
    return true;
  }
};
var inlineEditField = import_state2.StateField.define({
  create: () => import_view2.Decoration.none,
  update: (deco, tr) => {
    var _a3;
    deco = deco.map(tr.changes);
    for (const e2 of tr.effects) {
      if (e2.is(showInlineEdit)) {
        const builder = new import_state2.RangeSetBuilder();
        const isInbetween = (_a3 = e2.value.isInbetween) != null ? _a3 : false;
        builder.add(e2.value.inputPos, e2.value.inputPos, import_view2.Decoration.widget({
          widget: new InputWidget(e2.value.widget),
          block: !isInbetween,
          side: isInbetween ? 1 : -1
        }));
        deco = builder.finish();
      } else if (e2.is(showDiff)) {
        const builder = new import_state2.RangeSetBuilder();
        builder.add(e2.value.from, e2.value.to, import_view2.Decoration.replace({
          widget: new DiffWidget(e2.value.diffHtml, e2.value.widget)
        }));
        deco = builder.finish();
      } else if (e2.is(showInsertion)) {
        const builder = new import_state2.RangeSetBuilder();
        builder.add(e2.value.pos, e2.value.pos, import_view2.Decoration.widget({
          widget: new DiffWidget(e2.value.diffHtml, e2.value.widget),
          side: 1
          // After the position
        }));
        deco = builder.finish();
      } else if (e2.is(hideInlineEdit)) {
        deco = import_view2.Decoration.none;
      }
    }
    return deco;
  },
  provide: (f2) => import_view2.EditorView.decorations.from(f2)
});
var installedEditors = /* @__PURE__ */ new WeakSet();
function computeDiff(oldText, newText) {
  const oldWords = oldText.split(/(\s+)/);
  const newWords = newText.split(/(\s+)/);
  const m2 = oldWords.length, n = newWords.length;
  const dp = Array(m2 + 1).fill(null).map(() => Array(n + 1).fill(0));
  for (let i7 = 1; i7 <= m2; i7++) {
    for (let j5 = 1; j5 <= n; j5++) {
      dp[i7][j5] = oldWords[i7 - 1] === newWords[j5 - 1] ? dp[i7 - 1][j5 - 1] + 1 : Math.max(dp[i7 - 1][j5], dp[i7][j5 - 1]);
    }
  }
  const ops = [];
  let i2 = m2, j = n;
  const temp = [];
  while (i2 > 0 || j > 0) {
    if (i2 > 0 && j > 0 && oldWords[i2 - 1] === newWords[j - 1]) {
      temp.push({ type: "equal", text: oldWords[i2 - 1] });
      i2--;
      j--;
    } else if (j > 0 && (i2 === 0 || dp[i2][j - 1] >= dp[i2 - 1][j])) {
      temp.push({ type: "insert", text: newWords[j - 1] });
      j--;
    } else {
      temp.push({ type: "delete", text: oldWords[i2 - 1] });
      i2--;
    }
  }
  temp.reverse();
  for (const op of temp) {
    if (ops.length > 0 && ops[ops.length - 1].type === op.type) {
      ops[ops.length - 1].text += op.text;
    } else {
      ops.push({ ...op });
    }
  }
  return ops;
}
function diffToHtml(ops) {
  return ops.map((op) => {
    const escaped = escapeHtml(op.text);
    switch (op.type) {
      case "delete":
        return `<span class="claudian-diff-del">${escaped}</span>`;
      case "insert":
        return `<span class="claudian-diff-ins">${escaped}</span>`;
      default:
        return escaped;
    }
  }).join("");
}
var InlineEditModal = class {
  constructor(app, plugin, editor, view, editContext, notePath, getExternalContexts = () => []) {
    this.app = app;
    this.plugin = plugin;
    this.editor = editor;
    this.view = view;
    this.editContext = editContext;
    this.notePath = notePath;
    this.getExternalContexts = getExternalContexts;
    this.controller = null;
  }
  async openAndWait() {
    if (activeController) {
      activeController.reject();
      return { decision: "reject" };
    }
    let editor = this.editor;
    let editorView = getEditorView(editor);
    if (!editorView) {
      editor = this.view.editor;
      editorView = getEditorView(editor);
    }
    if (!editorView) {
      new import_obsidian45.Notice("Inline edit unavailable: could not access the active editor. Try reopening the note.");
      return { decision: "reject" };
    }
    return new Promise((resolve8) => {
      this.controller = new InlineEditController(
        this.app,
        this.plugin,
        editorView,
        editor,
        this.editContext,
        this.notePath,
        this.getExternalContexts,
        resolve8
      );
      activeController = this.controller;
      this.controller.show();
    });
  }
};
var InlineEditController = class {
  constructor(app, plugin, editorView, editor, editContext, notePath, getExternalContexts, resolve8) {
    this.app = app;
    this.plugin = plugin;
    this.editorView = editorView;
    this.editor = editor;
    this.notePath = notePath;
    this.getExternalContexts = getExternalContexts;
    this.resolve = resolve8;
    this.inputEl = null;
    this.spinnerEl = null;
    this.agentReplyEl = null;
    this.containerEl = null;
    this.editedText = null;
    this.insertedText = null;
    this.selFrom = 0;
    this.selTo = 0;
    this.startLine = 0;
    this.cursorContext = null;
    this.escHandler = null;
    this.selectionListener = null;
    this.isConversing = false;
    this.slashCommandDropdown = null;
    this.mentionDropdown = null;
    var _a3, _b2, _c, _d2, _e, _f, _g, _h, _i;
    const activeView = typeof plugin.getView === "function" ? plugin.getView() : null;
    const activeTab = activeView == null ? void 0 : activeView.getActiveTab();
    const conversation = (activeTab == null ? void 0 : activeTab.conversationId) ? plugin.getConversationSync(activeTab.conversationId) : null;
    const providerId = (_d2 = (_c = (_b2 = conversation == null ? void 0 : conversation.providerId) != null ? _b2 : (_a3 = activeTab == null ? void 0 : activeTab.service) == null ? void 0 : _a3.providerId) != null ? _c : activeTab == null ? void 0 : activeTab.providerId) != null ? _d2 : DEFAULT_CHAT_PROVIDER_ID;
    this.inlineEditService = ProviderRegistry.createInlineEditService(plugin, providerId);
    const auxiliaryModel = ((_e = activeTab == null ? void 0 : activeTab.service) == null ? void 0 : _e.providerId) === providerId ? (_g = (_f = activeTab.service).getAuxiliaryModel) == null ? void 0 : _g.call(_f) : (activeTab == null ? void 0 : activeTab.providerId) === providerId ? activeTab == null ? void 0 : activeTab.draftModel : null;
    (_i = (_h = this.inlineEditService).setModelOverride) == null ? void 0 : _i.call(_h, auxiliaryModel != null ? auxiliaryModel : void 0);
    this.resolvedProviderId = providerId;
    this.mentionDataProvider = new VaultMentionDataProvider(this.app, {
      onFileLoadError: () => {
        new import_obsidian45.Notice("Failed to load vault files. Vault @-mentions may be unavailable.");
      }
    });
    this.mentionDataProvider.initializeInBackground();
    this.mode = editContext.mode;
    if (editContext.mode === "cursor") {
      this.cursorContext = editContext.cursorContext;
      this.selectedText = "";
    } else {
      this.selectedText = editContext.selectedText;
    }
    this.updatePositionsFromEditor();
  }
  updatePositionsFromEditor() {
    const doc = this.editorView.state.doc;
    if (this.mode === "cursor") {
      const ctx = this.cursorContext;
      const line = doc.line(ctx.line + 1);
      this.selFrom = line.from + ctx.column;
      this.selTo = this.selFrom;
    } else {
      const from = this.editor.getCursor("from");
      const to = this.editor.getCursor("to");
      const fromLine = doc.line(from.line + 1);
      const toLine = doc.line(to.line + 1);
      this.selFrom = fromLine.from + from.ch;
      this.selTo = toLine.from + to.ch;
      this.selectedText = this.editor.getSelection() || this.selectedText;
      this.startLine = from.line + 1;
    }
  }
  show() {
    if (!installedEditors.has(this.editorView)) {
      this.editorView.dispatch({
        effects: import_state2.StateEffect.appendConfig.of(inlineEditField)
      });
      installedEditors.add(this.editorView);
    }
    this.updateHighlight();
    if (this.mode === "selection") {
      this.attachSelectionListeners();
    }
    this.escHandler = (e2) => {
      if (e2.key === "Escape" && !e2.isComposing) {
        this.reject();
      }
    };
    document.addEventListener("keydown", this.escHandler);
  }
  updateHighlight() {
    var _a3;
    const doc = this.editorView.state.doc;
    const line = doc.lineAt(this.selFrom);
    const isInbetween = this.mode === "cursor" && ((_a3 = this.cursorContext) == null ? void 0 : _a3.isInbetween);
    this.editorView.dispatch({
      effects: showInlineEdit.of({
        inputPos: isInbetween ? this.selFrom : line.from,
        selFrom: this.selFrom,
        selTo: this.selTo,
        widget: this,
        isInbetween
      })
    });
    this.updateSelectionHighlight();
  }
  updateSelectionHighlight() {
    if (this.mode === "selection" && this.selFrom !== this.selTo) {
      showSelectionHighlight(this.editorView, this.selFrom, this.selTo);
    } else {
      hideSelectionHighlight(this.editorView);
    }
  }
  attachSelectionListeners() {
    this.removeSelectionListeners();
    this.selectionListener = (e2) => {
      const target = e2.target;
      if (target && this.inputEl && (target === this.inputEl || this.inputEl.contains(target))) {
        return;
      }
      const prevFrom = this.selFrom;
      const prevTo = this.selTo;
      const newSelection = this.editor.getSelection();
      if (newSelection && newSelection.length > 0) {
        this.updatePositionsFromEditor();
        if (prevFrom !== this.selFrom || prevTo !== this.selTo) {
          this.updateHighlight();
        }
      }
    };
    this.editorView.dom.addEventListener("mouseup", this.selectionListener);
    this.editorView.dom.addEventListener("keyup", this.selectionListener);
  }
  createInputDOM() {
    const container = document.createElement("div");
    container.className = "claudian-inline-input-container";
    this.containerEl = container;
    this.agentReplyEl = document.createElement("div");
    this.agentReplyEl.className = "claudian-inline-agent-reply";
    this.agentReplyEl.style.display = "none";
    container.appendChild(this.agentReplyEl);
    const inputWrap = document.createElement("div");
    inputWrap.className = "claudian-inline-input-wrap";
    container.appendChild(inputWrap);
    this.inputEl = document.createElement("input");
    this.inputEl.type = "text";
    this.inputEl.className = "claudian-inline-input";
    this.inputEl.placeholder = this.mode === "cursor" ? "Insert instructions..." : "Edit instructions...";
    this.inputEl.spellcheck = false;
    inputWrap.appendChild(this.inputEl);
    this.spinnerEl = document.createElement("div");
    this.spinnerEl.className = "claudian-inline-spinner";
    this.spinnerEl.style.display = "none";
    inputWrap.appendChild(this.spinnerEl);
    const inlineCatalog = ProviderWorkspaceRegistry.getCommandCatalog(this.resolvedProviderId);
    this.slashCommandDropdown = new SlashCommandDropdown(
      document.body,
      this.inputEl,
      {
        onSelect: () => {
        },
        onHide: () => {
        }
      },
      {
        fixed: true,
        hiddenCommands: getHiddenProviderCommandSet(this.plugin.settings, this.resolvedProviderId),
        ...inlineCatalog ? {
          providerConfig: inlineCatalog.getDropdownConfig(),
          getProviderEntries: () => inlineCatalog.listDropdownEntries({ includeBuiltIns: false })
        } : {}
      }
    );
    this.mentionDropdown = new MentionDropdownController(
      document.body,
      this.inputEl,
      {
        // Inline-edit resolves @mentions at send time from input text.
        onAttachFile: () => {
        },
        onMcpMentionChange: () => {
        },
        getMentionedMcpServers: () => /* @__PURE__ */ new Set(),
        setMentionedMcpServers: () => false,
        addMentionedMcpServer: () => {
        },
        getExternalContexts: this.getExternalContexts,
        getCachedVaultFolders: () => this.mentionDataProvider.getCachedVaultFolders(),
        getCachedVaultFiles: () => this.mentionDataProvider.getCachedVaultFiles(),
        normalizePathForVault: (rawPath) => this.normalizePathForVault(rawPath)
      },
      { fixed: true }
    );
    this.inputEl.addEventListener("keydown", (e2) => this.handleKeydown(e2));
    this.inputEl.addEventListener("input", () => {
      var _a3;
      return (_a3 = this.mentionDropdown) == null ? void 0 : _a3.handleInputChange();
    });
    setTimeout(() => {
      var _a3;
      return (_a3 = this.inputEl) == null ? void 0 : _a3.focus();
    }, 50);
    return container;
  }
  async generate() {
    if (!this.inputEl || !this.spinnerEl) return;
    const userMessage = this.inputEl.value.trim();
    if (!userMessage) return;
    this.removeSelectionListeners();
    this.inputEl.disabled = true;
    this.spinnerEl.style.display = "block";
    const contextFiles = this.resolveContextFilesFromMessage(userMessage);
    let result;
    if (this.isConversing) {
      result = await this.inlineEditService.continueConversation(userMessage, contextFiles);
    } else {
      if (this.mode === "cursor") {
        result = await this.inlineEditService.editText({
          mode: "cursor",
          instruction: userMessage,
          notePath: this.notePath,
          cursorContext: this.cursorContext,
          contextFiles
        });
      } else {
        const lineCount = this.selectedText.split(/\r?\n/).length;
        result = await this.inlineEditService.editText({
          mode: "selection",
          instruction: userMessage,
          notePath: this.notePath,
          selectedText: this.selectedText,
          startLine: this.startLine,
          lineCount,
          contextFiles
        });
      }
    }
    this.spinnerEl.style.display = "none";
    if (result.success) {
      if (result.editedText !== void 0) {
        this.editedText = result.editedText;
        this.showDiffInPlace();
      } else if (result.insertedText !== void 0) {
        this.insertedText = result.insertedText;
        this.showInsertionInPlace();
      } else if (result.clarification) {
        this.showAgentReply(result.clarification);
        this.isConversing = true;
        this.inputEl.disabled = false;
        this.inputEl.value = "";
        this.inputEl.placeholder = "Reply to continue...";
        this.inputEl.focus();
      } else {
        this.handleError("No response from agent");
      }
    } else {
      this.handleError(result.error || "Error - try again");
    }
  }
  showAgentReply(message) {
    if (!this.agentReplyEl || !this.containerEl) return;
    this.agentReplyEl.style.display = "block";
    this.agentReplyEl.textContent = message;
    this.containerEl.classList.add("has-agent-reply");
  }
  handleError(errorMessage) {
    if (!this.inputEl) return;
    this.inputEl.disabled = false;
    this.inputEl.placeholder = errorMessage;
    this.updatePositionsFromEditor();
    this.updateHighlight();
    this.attachSelectionListeners();
    this.inputEl.focus();
  }
  showDiffInPlace() {
    if (this.editedText === null) return;
    hideSelectionHighlight(this.editorView);
    const diffOps = computeDiff(this.selectedText, this.editedText);
    const diffHtml = diffToHtml(diffOps);
    this.editorView.dispatch({
      effects: showDiff.of({
        from: this.selFrom,
        to: this.selTo,
        diffHtml,
        widget: this
      })
    });
    this.installAcceptRejectHandler();
  }
  showInsertionInPlace() {
    if (this.insertedText === null) return;
    hideSelectionHighlight(this.editorView);
    const trimmedText = normalizeInsertionText(this.insertedText);
    this.insertedText = trimmedText;
    const escaped = escapeHtml(trimmedText);
    const diffHtml = `<span class="claudian-diff-ins">${escaped}</span>`;
    this.editorView.dispatch({
      effects: showInsertion.of({
        pos: this.selFrom,
        diffHtml,
        widget: this
      })
    });
    this.installAcceptRejectHandler();
  }
  installAcceptRejectHandler() {
    if (this.escHandler) {
      document.removeEventListener("keydown", this.escHandler);
    }
    this.escHandler = (e2) => {
      if (e2.key === "Escape" && !e2.isComposing) {
        this.reject();
      } else if (e2.key === "Enter" && !e2.isComposing) {
        this.accept();
      }
    };
    document.addEventListener("keydown", this.escHandler);
  }
  accept() {
    var _a3;
    const textToInsert = (_a3 = this.editedText) != null ? _a3 : this.insertedText;
    if (textToInsert !== null) {
      const doc = this.editorView.state.doc;
      const fromLine = doc.lineAt(this.selFrom);
      const toLine = doc.lineAt(this.selTo);
      const from = { line: fromLine.number - 1, ch: this.selFrom - fromLine.from };
      const to = { line: toLine.number - 1, ch: this.selTo - toLine.from };
      this.cleanup();
      this.editor.replaceRange(textToInsert, from, to);
      this.resolve({ decision: "accept", editedText: textToInsert });
    } else {
      this.cleanup();
      this.resolve({ decision: "reject" });
    }
  }
  reject() {
    this.cleanup({ keepSelectionHighlight: true });
    this.restoreSelectionHighlight();
    this.resolve({ decision: "reject" });
  }
  removeSelectionListeners() {
    if (this.selectionListener) {
      this.editorView.dom.removeEventListener("mouseup", this.selectionListener);
      this.editorView.dom.removeEventListener("keyup", this.selectionListener);
      this.selectionListener = null;
    }
  }
  cleanup(options) {
    var _a3, _b2;
    this.inlineEditService.cancel();
    this.inlineEditService.resetConversation();
    this.isConversing = false;
    this.removeSelectionListeners();
    if (this.escHandler) {
      document.removeEventListener("keydown", this.escHandler);
    }
    (_a3 = this.slashCommandDropdown) == null ? void 0 : _a3.destroy();
    this.slashCommandDropdown = null;
    (_b2 = this.mentionDropdown) == null ? void 0 : _b2.destroy();
    this.mentionDropdown = null;
    if (activeController === this) {
      activeController = null;
    }
    this.editorView.dispatch({
      effects: hideInlineEdit.of(null)
    });
    if (!(options == null ? void 0 : options.keepSelectionHighlight)) {
      hideSelectionHighlight(this.editorView);
    }
  }
  restoreSelectionHighlight() {
    if (this.mode !== "selection" || this.selFrom === this.selTo) {
      return;
    }
    showSelectionHighlight(this.editorView, this.selFrom, this.selTo);
  }
  handleKeydown(e2) {
    var _a3, _b2;
    if ((_a3 = this.mentionDropdown) == null ? void 0 : _a3.handleKeydown(e2)) {
      return;
    }
    if ((_b2 = this.slashCommandDropdown) == null ? void 0 : _b2.handleKeydown(e2)) {
      return;
    }
    if (e2.key === "Enter" && !e2.isComposing) {
      e2.preventDefault();
      this.generate();
    }
  }
  normalizePathForVault(rawPath) {
    try {
      const vaultPath = getVaultPath(this.app);
      return normalizePathForVault(rawPath, vaultPath);
    } catch (e2) {
      new import_obsidian45.Notice("Failed to attach file: invalid path");
      return null;
    }
  }
  resolveContextFilesFromMessage(message) {
    if (!message.includes("@")) return [];
    const vaultFiles = this.mentionDataProvider.getCachedVaultFiles();
    const pathLookup = /* @__PURE__ */ new Map();
    for (const file2 of vaultFiles) {
      const normalized = this.normalizePathForVault(file2.path);
      if (!normalized) continue;
      const lookupKey = normalizeForPlatformLookup(normalizeMentionPath(normalized));
      if (!pathLookup.has(lookupKey)) {
        pathLookup.set(lookupKey, normalized);
      }
    }
    const resolved = /* @__PURE__ */ new Set();
    const externalEntries = buildExternalContextDisplayEntries(this.getExternalContexts()).sort((a2, b10) => b10.displayNameLower.length - a2.displayNameLower.length);
    const getExternalLookup = createExternalContextLookupGetter(
      (contextRoot) => externalContextScanner.scanPaths([contextRoot])
    );
    for (let index = 0; index < message.length; index++) {
      if (!isMentionStart(message, index)) continue;
      const externalMatch = resolveExternalMentionAtIndex(
        message,
        index,
        externalEntries,
        getExternalLookup
      );
      if (externalMatch) {
        resolved.add(externalMatch.resolvedPath);
        index = externalMatch.endIndex - 1;
        continue;
      }
      const vaultMatch = findBestMentionLookupMatch(
        message,
        index + 1,
        pathLookup,
        normalizeMentionPath,
        normalizeForPlatformLookup
      );
      if (vaultMatch) {
        resolved.add(vaultMatch.resolvedPath);
        index = vaultMatch.endIndex - 1;
      }
    }
    return [...resolved];
  }
};

// src/features/settings/ClaudianSettings.ts
var import_obsidian46 = require("obsidian");
init_env();

// src/features/settings/keyboardNavigation.ts
var NAV_ACTIONS = ["scrollUp", "scrollDown", "focusInput"];
var buildNavMappingText = (settings11) => {
  return [
    `map ${settings11.scrollUpKey} scrollUp`,
    `map ${settings11.scrollDownKey} scrollDown`,
    `map ${settings11.focusInputKey} focusInput`
  ].join("\n");
};
var parseNavMappings = (value) => {
  const parsed = {};
  const usedKeys = /* @__PURE__ */ new Map();
  const lines = value.split("\n");
  for (const rawLine of lines) {
    const line = rawLine.trim();
    if (!line) continue;
    const parts = line.split(/\s+/);
    if (parts.length !== 3 || parts[0] !== "map") {
      return { error: 'Each line must follow "map <key> <action>"' };
    }
    const key = parts[1];
    const action = parts[2];
    if (!NAV_ACTIONS.includes(action)) {
      return { error: `Unknown action: ${parts[2]}` };
    }
    if (key.length !== 1) {
      return { error: `Key must be a single character for ${action}` };
    }
    const normalizedKey = key.toLowerCase();
    if (usedKeys.has(normalizedKey)) {
      return { error: "Navigation keys must be unique" };
    }
    if (parsed[action]) {
      return { error: `Duplicate mapping for ${action}` };
    }
    usedKeys.set(normalizedKey, action);
    parsed[action] = key;
  }
  const missing = NAV_ACTIONS.filter((action) => !parsed[action]);
  if (missing.length > 0) {
    return { error: `Missing mapping for ${missing.join(", ")}` };
  }
  return { settings: parsed };
};

// src/features/settings/ClaudianSettings.ts
function formatHotkey(hotkey) {
  const isMac = navigator.platform.includes("Mac");
  const modMap = isMac ? { Mod: "\u2318", Ctrl: "\u2303", Alt: "\u2325", Shift: "\u21E7", Meta: "\u2318" } : { Mod: "Ctrl", Ctrl: "Ctrl", Alt: "Alt", Shift: "Shift", Meta: "Win" };
  const mods = hotkey.modifiers.map((modifier) => modMap[modifier] || modifier);
  const key = hotkey.key.length === 1 ? hotkey.key.toUpperCase() : hotkey.key;
  return isMac ? [...mods, key].join("") : [...mods, key].join("+");
}
function openHotkeySettings(app) {
  const setting = app.setting;
  setting.open();
  setting.openTabById("hotkeys");
  setTimeout(() => {
    var _a3, _b2, _c;
    const tab = setting.activeTab;
    if (!tab) {
      return;
    }
    const searchEl = (_b2 = tab.searchInputEl) != null ? _b2 : (_a3 = tab.searchComponent) == null ? void 0 : _a3.inputEl;
    if (!searchEl) {
      return;
    }
    searchEl.value = "Claudian";
    (_c = tab.updateHotkeyVisibility) == null ? void 0 : _c.call(tab);
  }, 100);
}
function getHotkeyForCommand(app, commandId) {
  var _a3, _b2;
  const hotkeyManager = app.hotkeyManager;
  if (!hotkeyManager) return null;
  const customHotkeys = (_a3 = hotkeyManager.customKeys) == null ? void 0 : _a3[commandId];
  const defaultHotkeys = (_b2 = hotkeyManager.defaultKeys) == null ? void 0 : _b2[commandId];
  const hotkeys = (customHotkeys == null ? void 0 : customHotkeys.length) > 0 ? customHotkeys : defaultHotkeys;
  if (!hotkeys || hotkeys.length === 0) return null;
  return hotkeys.map(formatHotkey).join(", ");
}
function addHotkeySettingRow(containerEl, app, commandId, translationPrefix) {
  const hotkey = getHotkeyForCommand(app, commandId);
  const item = containerEl.createDiv({ cls: "claudian-hotkey-item" });
  item.createSpan({
    cls: "claudian-hotkey-name",
    text: t(`${translationPrefix}.name`)
  });
  if (hotkey) {
    item.createSpan({ cls: "claudian-hotkey-badge", text: hotkey });
  }
  item.addEventListener("click", () => openHotkeySettings(app));
}
var ClaudianSettingTab = class extends import_obsidian46.PluginSettingTab {
  constructor(app, plugin) {
    super(app, plugin);
    this.activeTab = "general";
    this.plugin = plugin;
  }
  display() {
    var _a3;
    const { containerEl } = this;
    containerEl.empty();
    containerEl.addClass("claudian-settings");
    setLocale(this.plugin.settings.locale);
    const providerTabs = ProviderRegistry.getRegisteredProviderIds();
    const tabIds = ["general", ...providerTabs];
    if (!tabIds.includes(this.activeTab)) {
      this.activeTab = "general";
    }
    const tabBar = containerEl.createDiv({ cls: "claudian-settings-tabs" });
    const tabButtons = /* @__PURE__ */ new Map();
    const tabContents = /* @__PURE__ */ new Map();
    for (const id of tabIds) {
      const label = id === "general" ? t("settings.tabs.general") : ProviderRegistry.getProviderDisplayName(id);
      const button = tabBar.createEl("button", {
        cls: `claudian-settings-tab${id === this.activeTab ? " claudian-settings-tab--active" : ""}`,
        text: label
      });
      button.addEventListener("click", () => {
        var _a4, _b2;
        this.activeTab = id;
        for (const tabId of tabIds) {
          (_a4 = tabButtons.get(tabId)) == null ? void 0 : _a4.toggleClass("claudian-settings-tab--active", tabId === id);
          (_b2 = tabContents.get(tabId)) == null ? void 0 : _b2.toggleClass("claudian-settings-tab-content--active", tabId === id);
        }
      });
      tabButtons.set(id, button);
    }
    for (const id of tabIds) {
      const content = containerEl.createDiv({
        cls: `claudian-settings-tab-content${id === this.activeTab ? " claudian-settings-tab-content--active" : ""}`
      });
      tabContents.set(id, content);
    }
    this.renderGeneralTab(tabContents.get("general"));
    for (const providerId of providerTabs) {
      const content = tabContents.get(providerId);
      if (!content) {
        continue;
      }
      (_a3 = ProviderWorkspaceRegistry.getSettingsTabRenderer(providerId)) == null ? void 0 : _a3.render(content, {
        plugin: this.plugin,
        renderHiddenProviderCommandSetting: (target, targetProviderId, copy) => this.renderHiddenProviderCommandSetting(target, targetProviderId, copy),
        refreshModelSelectors: () => {
          for (const view of this.plugin.getAllViews()) {
            view.refreshModelSelector();
          }
        },
        renderCustomContextLimits: (target, providerId2) => this.renderCustomContextLimits(target, providerId2)
      });
    }
  }
  renderGeneralTab(container) {
    new import_obsidian46.Setting(container).setName(t("settings.language.name")).setDesc(t("settings.language.desc")).addDropdown((dropdown) => {
      const locales = getAvailableLocales();
      for (const locale of locales) {
        dropdown.addOption(locale, getLocaleDisplayName(locale));
      }
      dropdown.setValue(this.plugin.settings.locale).onChange(async (value) => {
        const locale = value;
        if (!setLocale(locale)) {
          dropdown.setValue(this.plugin.settings.locale);
          return;
        }
        this.plugin.settings.locale = locale;
        await this.plugin.saveSettings();
        this.display();
      });
    });
    new import_obsidian46.Setting(container).setName(t("settings.display")).setHeading();
    new import_obsidian46.Setting(container).setName(t("settings.tabBarPosition.name")).setDesc(t("settings.tabBarPosition.desc")).addDropdown((dropdown) => {
      var _a3;
      dropdown.addOption("input", t("settings.tabBarPosition.input")).addOption("header", t("settings.tabBarPosition.header")).setValue((_a3 = this.plugin.settings.tabBarPosition) != null ? _a3 : "input").onChange(async (value) => {
        this.plugin.settings.tabBarPosition = value;
        await this.plugin.saveSettings();
        for (const view of this.plugin.getAllViews()) {
          view.updateLayoutForPosition();
        }
      });
    });
    const maxTabsSetting = new import_obsidian46.Setting(container).setName(t("settings.maxTabs.name")).setDesc(t("settings.maxTabs.desc"));
    const maxTabsWarningEl = container.createDiv({ cls: "claudian-max-tabs-warning" });
    maxTabsWarningEl.style.color = "var(--text-warning)";
    maxTabsWarningEl.style.fontSize = "0.85em";
    maxTabsWarningEl.style.marginTop = "-0.5em";
    maxTabsWarningEl.style.marginBottom = "0.5em";
    maxTabsWarningEl.style.display = "none";
    maxTabsWarningEl.setText(t("settings.maxTabs.warning"));
    const updateMaxTabsWarning = (value) => {
      maxTabsWarningEl.style.display = value > 5 ? "block" : "none";
    };
    maxTabsSetting.addSlider((slider) => {
      var _a3, _b2;
      slider.setLimits(3, 10, 1).setValue((_a3 = this.plugin.settings.maxTabs) != null ? _a3 : 3).setDynamicTooltip().onChange(async (value) => {
        this.plugin.settings.maxTabs = value;
        await this.plugin.saveSettings();
        updateMaxTabsWarning(value);
      });
      updateMaxTabsWarning((_b2 = this.plugin.settings.maxTabs) != null ? _b2 : 3);
    });
    new import_obsidian46.Setting(container).setName(t("settings.openInMainTab.name")).setDesc(t("settings.openInMainTab.desc")).addToggle(
      (toggle) => toggle.setValue(this.plugin.settings.openInMainTab).onChange(async (value) => {
        this.plugin.settings.openInMainTab = value;
        await this.plugin.saveSettings();
      })
    );
    new import_obsidian46.Setting(container).setName(t("settings.enableAutoScroll.name")).setDesc(t("settings.enableAutoScroll.desc")).addToggle(
      (toggle) => {
        var _a3;
        return toggle.setValue((_a3 = this.plugin.settings.enableAutoScroll) != null ? _a3 : true).onChange(async (value) => {
          this.plugin.settings.enableAutoScroll = value;
          await this.plugin.saveSettings();
        });
      }
    );
    new import_obsidian46.Setting(container).setName(t("settings.conversations")).setHeading();
    new import_obsidian46.Setting(container).setName(t("settings.autoTitle.name")).setDesc(t("settings.autoTitle.desc")).addToggle(
      (toggle) => toggle.setValue(this.plugin.settings.enableAutoTitleGeneration).onChange(async (value) => {
        this.plugin.settings.enableAutoTitleGeneration = value;
        await this.plugin.saveSettings();
        this.display();
      })
    );
    if (this.plugin.settings.enableAutoTitleGeneration) {
      new import_obsidian46.Setting(container).setName(t("settings.titleModel.name")).setDesc(t("settings.titleModel.desc")).addDropdown((dropdown) => {
        dropdown.addOption("", t("settings.titleModel.auto"));
        const settingsBag = this.plugin.settings;
        const seenValues = /* @__PURE__ */ new Set();
        for (const providerId of ProviderRegistry.getRegisteredProviderIds()) {
          const uiConfig = ProviderRegistry.getChatUIConfig(providerId);
          for (const model of uiConfig.getModelOptions(settingsBag)) {
            if (!seenValues.has(model.value)) {
              seenValues.add(model.value);
              dropdown.addOption(model.value, model.label);
            }
          }
        }
        dropdown.setValue(this.plugin.settings.titleGenerationModel || "").onChange(async (value) => {
          this.plugin.settings.titleGenerationModel = value;
          await this.plugin.saveSettings();
        });
      });
    }
    new import_obsidian46.Setting(container).setName(t("settings.content")).setHeading();
    new import_obsidian46.Setting(container).setName(t("settings.userName.name")).setDesc(t("settings.userName.desc")).addText((text) => {
      text.setPlaceholder(t("settings.userName.name")).setValue(this.plugin.settings.userName).onChange(async (value) => {
        this.plugin.settings.userName = value;
        await this.plugin.saveSettings();
      });
      text.inputEl.addEventListener("blur", () => this.restartServiceForPromptChange());
    });
    new import_obsidian46.Setting(container).setName(t("settings.systemPrompt.name")).setDesc(t("settings.systemPrompt.desc")).addTextArea((text) => {
      text.setPlaceholder(t("settings.systemPrompt.name")).setValue(this.plugin.settings.systemPrompt).onChange(async (value) => {
        this.plugin.settings.systemPrompt = value;
        await this.plugin.saveSettings();
      });
      text.inputEl.rows = 6;
      text.inputEl.cols = 50;
      text.inputEl.addEventListener("blur", () => this.restartServiceForPromptChange());
    });
    new import_obsidian46.Setting(container).setName(t("settings.excludedTags.name")).setDesc(t("settings.excludedTags.desc")).addTextArea((text) => {
      text.setPlaceholder("system\nprivate\ndraft").setValue(this.plugin.settings.excludedTags.join("\n")).onChange(async (value) => {
        this.plugin.settings.excludedTags = value.split(/\r?\n/).map((entry) => entry.trim().replace(/^#/, "")).filter((entry) => entry.length > 0);
        await this.plugin.saveSettings();
      });
      text.inputEl.rows = 4;
      text.inputEl.cols = 30;
    });
    new import_obsidian46.Setting(container).setName(t("settings.mediaFolder.name")).setDesc(t("settings.mediaFolder.desc")).addText((text) => {
      text.setPlaceholder("attachments").setValue(this.plugin.settings.mediaFolder).onChange(async (value) => {
        this.plugin.settings.mediaFolder = value.trim();
        await this.plugin.saveSettings();
      });
      text.inputEl.addClass("claudian-settings-media-input");
      text.inputEl.addEventListener("blur", () => this.restartServiceForPromptChange());
    });
    new import_obsidian46.Setting(container).setName(t("settings.input")).setHeading();
    new import_obsidian46.Setting(container).setName(t("settings.navMappings.name")).setDesc(t("settings.navMappings.desc")).addTextArea((text) => {
      let pendingValue = buildNavMappingText(this.plugin.settings.keyboardNavigation);
      let saveTimeout = null;
      const commitValue = async (showError) => {
        if (saveTimeout !== null) {
          window.clearTimeout(saveTimeout);
          saveTimeout = null;
        }
        const result = parseNavMappings(pendingValue);
        if (!result.settings) {
          if (showError) {
            new import_obsidian46.Notice(`${t("common.error")}: ${result.error}`);
            pendingValue = buildNavMappingText(this.plugin.settings.keyboardNavigation);
            text.setValue(pendingValue);
          }
          return;
        }
        this.plugin.settings.keyboardNavigation.scrollUpKey = result.settings.scrollUp;
        this.plugin.settings.keyboardNavigation.scrollDownKey = result.settings.scrollDown;
        this.plugin.settings.keyboardNavigation.focusInputKey = result.settings.focusInput;
        await this.plugin.saveSettings();
        pendingValue = buildNavMappingText(this.plugin.settings.keyboardNavigation);
        text.setValue(pendingValue);
      };
      const scheduleSave = () => {
        if (saveTimeout !== null) {
          window.clearTimeout(saveTimeout);
        }
        saveTimeout = window.setTimeout(() => {
          void commitValue(false);
        }, 500);
      };
      text.setPlaceholder("map w scrollUp\nmap s scrollDown\nmap i focusInput").setValue(pendingValue).onChange((value) => {
        pendingValue = value;
        scheduleSave();
      });
      text.inputEl.rows = 3;
      text.inputEl.addEventListener("blur", async () => {
        await commitValue(true);
      });
    });
    new import_obsidian46.Setting(container).setName(t("settings.hotkeys")).setHeading();
    const hotkeyGrid = container.createDiv({ cls: "claudian-hotkey-grid" });
    addHotkeySettingRow(hotkeyGrid, this.app, "claudian:inline-edit", "settings.inlineEditHotkey");
    addHotkeySettingRow(hotkeyGrid, this.app, "claudian:open-view", "settings.openChatHotkey");
    addHotkeySettingRow(hotkeyGrid, this.app, "claudian:new-session", "settings.newSessionHotkey");
    addHotkeySettingRow(hotkeyGrid, this.app, "claudian:new-tab", "settings.newTabHotkey");
    addHotkeySettingRow(hotkeyGrid, this.app, "claudian:close-current-tab", "settings.closeTabHotkey");
    renderEnvironmentSettingsSection({
      container,
      plugin: this.plugin,
      scope: "shared",
      heading: t("settings.environment"),
      name: "Shared environment",
      desc: "Provider-neutral runtime variables shared across all providers. Use this for PATH, proxy, cert, and temp variables.",
      placeholder: "PATH=/opt/homebrew/bin:/usr/local/bin\nHTTPS_PROXY=http://proxy.example.com:8080\nSSL_CERT_FILE=/path/to/cert.pem",
      renderCustomContextLimits: (target) => this.renderCustomContextLimits(target)
    });
  }
  renderHiddenProviderCommandSetting(container, providerId, copy) {
    new import_obsidian46.Setting(container).setName(copy.name).setDesc(copy.desc).addTextArea((text) => {
      text.setPlaceholder(copy.placeholder).setValue(getHiddenProviderCommands(this.plugin.settings, providerId).join("\n")).onChange(async (value) => {
        var _a3;
        this.plugin.settings.hiddenProviderCommands = {
          ...this.plugin.settings.hiddenProviderCommands,
          [providerId]: normalizeHiddenCommandList(value.split(/\r?\n/))
        };
        await this.plugin.saveSettings();
        (_a3 = this.plugin.getView()) == null ? void 0 : _a3.updateHiddenProviderCommands();
      });
      text.inputEl.rows = 4;
      text.inputEl.cols = 30;
    });
  }
  renderCustomContextLimits(container, providerId) {
    var _a3;
    container.empty();
    const uniqueModelIds = /* @__PURE__ */ new Set();
    const providerIds = providerId ? [providerId] : ProviderRegistry.getRegisteredProviderIds();
    for (const targetProviderId of providerIds) {
      const envVars = parseEnvironmentVariables(
        this.plugin.getActiveEnvironmentVariables(targetProviderId)
      );
      for (const modelId of ProviderRegistry.getChatUIConfig(targetProviderId).getCustomModelIds(envVars)) {
        uniqueModelIds.add(modelId);
      }
    }
    if (uniqueModelIds.size === 0) {
      return;
    }
    const headerEl = container.createDiv({ cls: "claudian-context-limits-header" });
    headerEl.createSpan({
      text: t("settings.customContextLimits.name"),
      cls: "claudian-context-limits-label"
    });
    const descEl = container.createDiv({ cls: "claudian-context-limits-desc" });
    descEl.setText(t("settings.customContextLimits.desc"));
    const listEl = container.createDiv({ cls: "claudian-context-limits-list" });
    for (const modelId of uniqueModelIds) {
      const currentValue = (_a3 = this.plugin.settings.customContextLimits) == null ? void 0 : _a3[modelId];
      const itemEl = listEl.createDiv({ cls: "claudian-context-limits-item" });
      const nameEl = itemEl.createDiv({ cls: "claudian-context-limits-model" });
      nameEl.setText(modelId);
      const inputWrapper = itemEl.createDiv({ cls: "claudian-context-limits-input-wrapper" });
      const inputEl = inputWrapper.createEl("input", {
        type: "text",
        placeholder: "200k",
        cls: "claudian-context-limits-input",
        value: currentValue ? formatContextLimit(currentValue) : ""
      });
      const validationEl = inputWrapper.createDiv({ cls: "claudian-context-limit-validation" });
      inputEl.addEventListener("input", async () => {
        const trimmed = inputEl.value.trim();
        if (!this.plugin.settings.customContextLimits) {
          this.plugin.settings.customContextLimits = {};
        }
        if (!trimmed) {
          delete this.plugin.settings.customContextLimits[modelId];
          validationEl.style.display = "none";
          inputEl.classList.remove("claudian-input-error");
        } else {
          const parsed = parseContextLimit(trimmed);
          if (parsed === null) {
            validationEl.setText(t("settings.customContextLimits.invalid"));
            validationEl.style.display = "block";
            inputEl.classList.add("claudian-input-error");
            return;
          }
          this.plugin.settings.customContextLimits[modelId] = parsed;
          validationEl.style.display = "none";
          inputEl.classList.remove("claudian-input-error");
        }
        await this.plugin.saveSettings();
      });
    }
  }
  async restartServiceForPromptChange() {
    const view = this.plugin.getView();
    const tabManager = view == null ? void 0 : view.getTabManager();
    if (!tabManager) return;
    try {
      await tabManager.broadcastToAllTabs(
        async (service) => {
          await service.ensureReady({ force: true });
        }
      );
    } catch (e2) {
    }
  }
};

// src/main.ts
init_path();
patchSetMaxListenersForElectron();
var ClaudianPlugin = class extends import_obsidian47.Plugin {
  constructor() {
    super(...arguments);
    this.conversations = [];
    this.lastKnownTabManagerState = null;
  }
  async onload() {
    await this.loadSettings();
    await ProviderWorkspaceRegistry.initializeAll(this);
    this.registerView(
      VIEW_TYPE_CLAUDIAN,
      (leaf) => new ClaudianView(leaf, this)
    );
    this.addRibbonIcon("bot", "Open Claudian", () => {
      this.activateView();
    });
    this.addCommand({
      id: "open-view",
      name: "Open chat view",
      callback: () => {
        this.activateView();
      }
    });
    this.addCommand({
      id: "inline-edit",
      name: "Inline edit",
      editorCallback: async (editor, ctx) => {
        var _a3;
        const view = ctx instanceof import_obsidian47.MarkdownView ? ctx : this.app.workspace.getActiveViewOfType(import_obsidian47.MarkdownView);
        if (!view) {
          new import_obsidian47.Notice("Inline edit unavailable: could not access the active markdown view.");
          return;
        }
        const selectedText = editor.getSelection();
        const notePath = ((_a3 = view.file) == null ? void 0 : _a3.path) || "unknown";
        let editContext;
        if (selectedText.trim()) {
          editContext = { mode: "selection", selectedText };
        } else {
          const cursor = editor.getCursor();
          const cursorContext = buildCursorContext(
            (line) => editor.getLine(line),
            editor.lineCount(),
            cursor.line,
            cursor.ch
          );
          editContext = { mode: "cursor", cursorContext };
        }
        const modal = new InlineEditModal(
          this.app,
          this,
          editor,
          view,
          editContext,
          notePath,
          () => {
            var _a4, _b2, _c, _d2;
            return (_d2 = (_c = (_b2 = (_a4 = this.getView()) == null ? void 0 : _a4.getActiveTab()) == null ? void 0 : _b2.ui.externalContextSelector) == null ? void 0 : _c.getExternalContexts()) != null ? _d2 : [];
          }
        );
        const result = await modal.openAndWait();
        if (result.decision === "accept" && result.editedText !== void 0) {
          new import_obsidian47.Notice(editContext.mode === "cursor" ? "Inserted" : "Edit applied");
        }
      }
    });
    this.addCommand({
      id: "new-tab",
      name: "New tab",
      checkCallback: (checking) => {
        if (!this.canCreateNewTab()) return false;
        if (!checking) {
          void this.openNewTab();
        }
        return true;
      }
    });
    this.addCommand({
      id: "new-session",
      name: "New session (in current tab)",
      checkCallback: (checking) => {
        const leaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN)[0];
        if (!leaf) return false;
        const view = leaf.view;
        const tabManager = view.getTabManager();
        if (!tabManager) return false;
        const activeTab = tabManager.getActiveTab();
        if (!activeTab) return false;
        if (activeTab.state.isStreaming) return false;
        if (!checking) {
          tabManager.createNewConversation();
        }
        return true;
      }
    });
    this.addCommand({
      id: "close-current-tab",
      name: "Close current tab",
      checkCallback: (checking) => {
        const leaf = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN)[0];
        if (!leaf) return false;
        const view = leaf.view;
        const tabManager = view.getTabManager();
        if (!tabManager) return false;
        if (!checking) {
          const activeTabId = tabManager.getActiveTabId();
          if (activeTabId) {
            tabManager.closeTab(activeTabId);
          }
        }
        return true;
      }
    });
    this.addSettingTab(new ClaudianSettingTab(this.app, this));
  }
  async onunload() {
    for (const view of this.getAllViews()) {
      const tabManager = view.getTabManager();
      if (tabManager) {
        const state = tabManager.getPersistedState();
        await this.persistTabManagerState(state);
      }
    }
  }
  async activateView() {
    const { workspace } = this.app;
    let leaf = workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN)[0];
    if (!leaf) {
      const newLeaf = this.settings.openInMainTab ? workspace.getLeaf("tab") : workspace.getRightLeaf(false);
      if (newLeaf) {
        await newLeaf.setViewState({
          type: VIEW_TYPE_CLAUDIAN,
          active: true
        });
        leaf = newLeaf;
      }
    }
    if (leaf) {
      workspace.revealLeaf(leaf);
    }
  }
  canCreateNewTab() {
    const view = this.getView();
    const tabManager = view == null ? void 0 : view.getTabManager();
    if (tabManager) {
      return tabManager.canCreateTab();
    }
    if (view) {
      return false;
    }
    return this.getLastKnownOpenTabCount() < this.getMaxTabsLimit();
  }
  async ensureViewOpen() {
    const existingView = this.getView();
    if (existingView) {
      return existingView;
    }
    await this.activateView();
    return this.getView();
  }
  async openNewTab() {
    const existingView = this.getView();
    if (existingView) {
      await existingView.createNewTab();
      return;
    }
    const restoredTabCount = this.getLastKnownOpenTabCount();
    const view = await this.ensureViewOpen();
    if (!view) {
      return;
    }
    if (restoredTabCount === 0) {
      return;
    }
    await view.createNewTab();
  }
  async loadSettings() {
    var _a3;
    this.storage = new SharedStorageService(this);
    const { claudian } = await this.storage.initialize();
    this.lastKnownTabManagerState = await this.storage.getTabManagerState();
    this.settings = {
      ...DEFAULT_CLAUDIAN_SETTINGS,
      ...claudian
    };
    if (this.settings.permissionMode === "plan") {
      this.settings.permissionMode = "normal";
    }
    if (this.settings.savedProviderPermissionMode && typeof this.settings.savedProviderPermissionMode === "object" && !Array.isArray(this.settings.savedProviderPermissionMode)) {
      for (const [providerId, mode] of Object.entries(this.settings.savedProviderPermissionMode)) {
        if (mode === "plan") {
          this.settings.savedProviderPermissionMode[providerId] = "normal";
        }
      }
    }
    const opencodeConfig = (_a3 = this.settings.providerConfigs) == null ? void 0 : _a3.opencode;
    if (opencodeConfig && typeof opencodeConfig === "object" && !Array.isArray(opencodeConfig) && opencodeConfig.selectedMode === OPENCODE_PLAN_MODE_ID) {
      opencodeConfig.selectedMode = OPENCODE_SAFE_MODE_ID;
    }
    const didNormalizeProviderSelection = ProviderSettingsCoordinator.normalizeProviderSelection(
      this.settings
    );
    const didNormalizeModelVariants = this.normalizeModelVariantSettings();
    const allMetadata = await this.storage.sessions.listMetadata();
    this.conversations = allMetadata.map((meta3) => {
      var _a4;
      const resumeSessionId = meta3.sessionId !== void 0 ? meta3.sessionId : meta3.id;
      return {
        id: meta3.id,
        providerId: (_a4 = meta3.providerId) != null ? _a4 : DEFAULT_CHAT_PROVIDER_ID,
        title: meta3.title,
        createdAt: meta3.createdAt,
        updatedAt: meta3.updatedAt,
        lastResponseAt: meta3.lastResponseAt,
        sessionId: resumeSessionId,
        providerState: meta3.providerState,
        messages: [],
        currentNote: meta3.currentNote,
        externalContextPaths: meta3.externalContextPaths,
        enabledMcpServers: meta3.enabledMcpServers,
        usage: meta3.usage,
        titleGenerationStatus: meta3.titleGenerationStatus,
        resumeAtMessageId: meta3.resumeAtMessageId
      };
    }).sort(
      (a2, b10) => {
        var _a4, _b2;
        return ((_a4 = b10.lastResponseAt) != null ? _a4 : b10.updatedAt) - ((_b2 = a2.lastResponseAt) != null ? _b2 : a2.updatedAt);
      }
    );
    setLocale(this.settings.locale);
    const backfilledConversations = this.backfillConversationResponseTimestamps();
    const { changed, invalidatedConversations } = this.reconcileModelWithEnvironment();
    ProviderSettingsCoordinator.projectActiveProviderState(
      this.settings
    );
    if (changed || didNormalizeModelVariants || didNormalizeProviderSelection) {
      await this.saveSettings();
    }
    const conversationsToSave = /* @__PURE__ */ new Set([...backfilledConversations, ...invalidatedConversations]);
    for (const conv of conversationsToSave) {
      await this.storage.sessions.saveMetadata(
        this.storage.sessions.toSessionMetadata(conv)
      );
    }
  }
  backfillConversationResponseTimestamps() {
    const updated = [];
    for (const conv of this.conversations) {
      if (conv.lastResponseAt != null) continue;
      if (!conv.messages || conv.messages.length === 0) continue;
      for (let i2 = conv.messages.length - 1; i2 >= 0; i2--) {
        const msg = conv.messages[i2];
        if (msg.role === "assistant") {
          conv.lastResponseAt = msg.timestamp;
          updated.push(conv);
          break;
        }
      }
    }
    return updated;
  }
  normalizeModelVariantSettings() {
    return ProviderSettingsCoordinator.normalizeAllModelVariants(
      this.settings
    );
  }
  async saveSettings() {
    ProviderSettingsCoordinator.normalizeProviderSelection(
      this.settings
    );
    ProviderSettingsCoordinator.persistProjectedProviderState(
      this.settings
    );
    await this.storage.saveClaudianSettings(this.settings);
  }
  /** Updates and persists environment variables, restarting processes to apply changes. */
  async applyEnvironmentVariables(scope, envText) {
    await this.applyEnvironmentVariablesBatch([{ scope, envText }]);
  }
  async applyEnvironmentVariablesBatch(updates) {
    var _a3;
    const settingsBag = this.settings;
    const nextEnvironmentByScope = /* @__PURE__ */ new Map();
    for (const update of updates) {
      nextEnvironmentByScope.set(update.scope, update.envText);
    }
    const changedScopes = [];
    for (const [scope, envText] of nextEnvironmentByScope) {
      const currentValue = getEnvironmentVariablesForScope(settingsBag, scope);
      if (currentValue !== envText) {
        changedScopes.push(scope);
      }
      setEnvironmentVariablesForScope(settingsBag, scope, envText);
    }
    if (changedScopes.length === 0) {
      await this.saveSettings();
      return;
    }
    const affectedProviderIds = this.getAffectedEnvironmentProviders(changedScopes);
    ProviderSettingsCoordinator.handleEnvironmentChange(settingsBag, affectedProviderIds);
    const { changed, invalidatedConversations } = this.reconcileModelWithEnvironment(affectedProviderIds);
    await this.saveSettings();
    if (invalidatedConversations.length > 0) {
      for (const conv of invalidatedConversations) {
        await this.storage.sessions.saveMetadata(
          this.storage.sessions.toSessionMetadata(conv)
        );
      }
    }
    const view = this.getView();
    const tabManager = view == null ? void 0 : view.getTabManager();
    if (tabManager) {
      const affectedTabs = tabManager.getAllTabs().filter((tab) => {
        var _a4;
        return affectedProviderIds.includes((_a4 = tab.providerId) != null ? _a4 : DEFAULT_CHAT_PROVIDER_ID);
      });
      const syncTabRuntimeState = (tab) => {
        var _a4, _b2, _c, _d2, _e;
        if (!tab.service || !tab.serviceInitialized) {
          return;
        }
        const conversation = tab.conversationId ? this.getConversationSync(tab.conversationId) : null;
        const hasConversationContext = ((_a4 = conversation == null ? void 0 : conversation.messages.length) != null ? _a4 : 0) > 0;
        const externalContextPaths = (_e = (_b2 = tab.ui.externalContextSelector) == null ? void 0 : _b2.getExternalContexts()) != null ? _e : hasConversationContext ? (_c = conversation == null ? void 0 : conversation.externalContextPaths) != null ? _c : [] : (_d2 = this.settings.persistentExternalContextPaths) != null ? _d2 : [];
        tab.service.syncConversationState(conversation, externalContextPaths);
      };
      for (const tab of affectedTabs) {
        if (tab.state.isStreaming) {
          (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.cancelStreaming();
        }
      }
      let failedTabs = 0;
      if (changed) {
        for (const tab of affectedTabs) {
          if (!tab.service || !tab.serviceInitialized) {
            continue;
          }
          try {
            syncTabRuntimeState(tab);
            tab.service.resetSession();
            await tab.service.ensureReady();
          } catch (e2) {
            failedTabs++;
          }
        }
      } else {
        for (const tab of affectedTabs) {
          if (!tab.service || !tab.serviceInitialized) {
            continue;
          }
          try {
            syncTabRuntimeState(tab);
            await tab.service.ensureReady({ force: true });
          } catch (e2) {
            failedTabs++;
          }
        }
      }
      if (failedTabs > 0) {
        new import_obsidian47.Notice(`Environment changes applied, but ${failedTabs} affected tab(s) failed to restart.`);
      }
    }
    for (const openView of this.getAllViews()) {
      openView.invalidateProviderCommandCaches(affectedProviderIds);
      openView.refreshModelSelector();
    }
    const noticeText = changed ? "Environment variables applied. Sessions will be rebuilt on next message." : "Environment variables applied.";
    new import_obsidian47.Notice(noticeText);
  }
  /** Returns the runtime environment variables (fixed at plugin load). */
  getActiveEnvironmentVariables(providerId = ProviderRegistry.resolveSettingsProviderId(
    this.settings
  )) {
    return getRuntimeEnvironmentText(
      this.settings,
      providerId
    );
  }
  getEnvironmentVariablesForScope(scope) {
    return getEnvironmentVariablesForScope(
      this.settings,
      scope
    );
  }
  getResolvedProviderCliPath(providerId) {
    const cliResolver = ProviderWorkspaceRegistry.getCliResolver(providerId);
    if (!cliResolver) {
      return null;
    }
    return cliResolver.resolveFromSettings(this.settings);
  }
  reconcileModelWithEnvironment(providerIds = ProviderRegistry.getRegisteredProviderIds()) {
    return ProviderSettingsCoordinator.reconcileProviders(
      this.settings,
      this.conversations,
      providerIds
    );
  }
  getAffectedEnvironmentProviders(scopes) {
    const registeredProviderIds = new Set(ProviderRegistry.getRegisteredProviderIds());
    const affectedProviderIds = /* @__PURE__ */ new Set();
    for (const scope of scopes) {
      if (scope === "shared") {
        for (const providerId2 of registeredProviderIds) {
          affectedProviderIds.add(providerId2);
        }
        continue;
      }
      const providerId = scope.slice("provider:".length);
      if (registeredProviderIds.has(providerId)) {
        affectedProviderIds.add(providerId);
      }
    }
    return Array.from(affectedProviderIds);
  }
  generateConversationId() {
    return `conv-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
  }
  generateDefaultTitle() {
    const now = /* @__PURE__ */ new Date();
    return now.toLocaleString(void 0, {
      month: "short",
      day: "numeric",
      hour: "2-digit",
      minute: "2-digit"
    });
  }
  getConversationPreview(conv) {
    const firstUserMsg = conv.messages.find((m2) => m2.role === "user");
    if (!firstUserMsg) {
      return "New conversation";
    }
    return firstUserMsg.content.substring(0, 50) + (firstUserMsg.content.length > 50 ? "..." : "");
  }
  async loadSdkMessagesForConversation(conversation) {
    await ProviderRegistry.getConversationHistoryService(conversation.providerId).hydrateConversationHistory(conversation, getVaultPath(this.app));
  }
  async createConversation(options) {
    var _a3;
    const providerId = (_a3 = options == null ? void 0 : options.providerId) != null ? _a3 : DEFAULT_CHAT_PROVIDER_ID;
    const sessionId = options == null ? void 0 : options.sessionId;
    const conversationId = sessionId != null ? sessionId : this.generateConversationId();
    const conversation = {
      id: conversationId,
      providerId,
      title: this.generateDefaultTitle(),
      createdAt: Date.now(),
      updatedAt: Date.now(),
      sessionId: sessionId != null ? sessionId : null,
      messages: []
    };
    this.conversations.unshift(conversation);
    await this.storage.sessions.saveMetadata(
      this.storage.sessions.toSessionMetadata(conversation)
    );
    return conversation;
  }
  async switchConversation(id) {
    const conversation = this.conversations.find((c) => c.id === id);
    if (!conversation) return null;
    await this.loadSdkMessagesForConversation(conversation);
    return conversation;
  }
  async deleteConversation(id) {
    var _a3, _b2;
    const index = this.conversations.findIndex((c) => c.id === id);
    if (index === -1) return;
    const conversation = this.conversations[index];
    this.conversations.splice(index, 1);
    await ProviderRegistry.getConversationHistoryService(conversation.providerId).deleteConversationSession(conversation, getVaultPath(this.app));
    await this.storage.sessions.deleteMetadata(id);
    for (const view of this.getAllViews()) {
      const tabManager = view.getTabManager();
      if (!tabManager) continue;
      for (const tab of tabManager.getAllTabs()) {
        if (tab.conversationId === id) {
          (_a3 = tab.controllers.inputController) == null ? void 0 : _a3.cancelStreaming();
          await ((_b2 = tab.controllers.conversationController) == null ? void 0 : _b2.createNew({ force: true }));
        }
      }
    }
  }
  async renameConversation(id, title) {
    const conversation = this.conversations.find((c) => c.id === id);
    if (!conversation) return;
    conversation.title = title.trim() || this.generateDefaultTitle();
    conversation.updatedAt = Date.now();
    await this.storage.sessions.saveMetadata(
      this.storage.sessions.toSessionMetadata(conversation)
    );
  }
  async updateConversation(id, updates) {
    const conversation = this.conversations.find((c) => c.id === id);
    if (!conversation) return;
    const { providerId: _10, ...safeUpdates } = updates;
    Object.assign(conversation, safeUpdates, { updatedAt: Date.now() });
    await this.storage.sessions.saveMetadata(
      this.storage.sessions.toSessionMetadata(conversation)
    );
    if (!ProviderRegistry.getConversationHistoryService(conversation.providerId).isPendingForkConversation(conversation)) {
      for (const msg of conversation.messages) {
        if (msg.images) {
          for (const img of msg.images) {
            img.data = "";
          }
        }
      }
    }
  }
  async getConversationById(id) {
    const conversation = this.conversations.find((c) => c.id === id) || null;
    if (conversation) {
      await this.loadSdkMessagesForConversation(conversation);
    }
    return conversation;
  }
  getConversationSync(id) {
    return this.conversations.find((c) => c.id === id) || null;
  }
  findEmptyConversation() {
    return this.conversations.find((c) => c.messages.length === 0) || null;
  }
  getConversationList() {
    return this.conversations.map((c) => ({
      id: c.id,
      providerId: c.providerId,
      title: c.title,
      createdAt: c.createdAt,
      updatedAt: c.updatedAt,
      lastResponseAt: c.lastResponseAt,
      messageCount: c.messages.length,
      preview: this.getConversationPreview(c),
      titleGenerationStatus: c.titleGenerationStatus
    }));
  }
  async persistTabManagerState(state) {
    this.lastKnownTabManagerState = state;
    await this.storage.setTabManagerState(state);
  }
  getView() {
    const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN);
    if (leaves.length > 0) {
      return leaves[0].view;
    }
    return null;
  }
  getAllViews() {
    const leaves = this.app.workspace.getLeavesOfType(VIEW_TYPE_CLAUDIAN);
    return leaves.map((leaf) => leaf.view);
  }
  findConversationAcrossViews(conversationId) {
    for (const view of this.getAllViews()) {
      const tabManager = view.getTabManager();
      if (!tabManager) continue;
      const tabs = tabManager.getAllTabs();
      for (const tab of tabs) {
        if (tab.conversationId === conversationId) {
          return { view, tabId: tab.id };
        }
      }
    }
    return null;
  }
  getLastKnownOpenTabCount() {
    var _a3, _b2;
    return (_b2 = (_a3 = this.lastKnownTabManagerState) == null ? void 0 : _a3.openTabs.length) != null ? _b2 : 0;
  }
  getMaxTabsLimit() {
    var _a3;
    const maxTabs = (_a3 = this.settings.maxTabs) != null ? _a3 : 3;
    return Math.max(3, Math.min(10, maxTabs));
  }
};
/*! Bundled license information:

smol-toml/dist/error.js:
smol-toml/dist/util.js:
smol-toml/dist/date.js:
smol-toml/dist/primitive.js:
smol-toml/dist/extract.js:
smol-toml/dist/struct.js:
smol-toml/dist/parse.js:
smol-toml/dist/stringify.js:
smol-toml/dist/index.js:
  (*!
   * Copyright (c) Squirrel Chat et al., All rights reserved.
   * SPDX-License-Identifier: BSD-3-Clause
   *
   * Redistribution and use in source and binary forms, with or without
   * modification, are permitted provided that the following conditions are met:
   *
   * 1. Redistributions of source code must retain the above copyright notice, this
   *    list of conditions and the following disclaimer.
   * 2. Redistributions in binary form must reproduce the above copyright notice,
   *    this list of conditions and the following disclaimer in the
   *    documentation and/or other materials provided with the distribution.
   * 3. Neither the name of the copyright holder nor the names of its contributors
   *    may be used to endorse or promote products derived from this software without
   *    specific prior written permission.
   *
   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
   *)
*/
