const require = (await import('node:module')).createRequire(import.meta.url); const __chunk_filename = (await import('node:url')).fileURLToPath(import.meta.url); const __chunk_dirname = (await import('node:path')).dirname(__chunk_filename);
import {
  BuiltinCommandLoader,
  CommandService,
  ConsolePatcher,
  DEFAULT_THEME,
  ExtensionManager,
  FileCommandLoader,
  INSTALL_WARNING_MESSAGE,
  McpPromptLoader,
  McpServerEnablementManager,
  canLoadServer,
  checkForAllExtensionUpdates,
  checkForExtensionUpdate,
  configureAllExtensions,
  configureExtension,
  configureSpecificSetting,
  disableSkill,
  enableSkill,
  getExtensionManager,
  handleAtCommand,
  inferInstallMetadata,
  initializeApp,
  installSkill,
  isRecord,
  isSlashCommand,
  linkSkill,
  normalizeServerId,
  parseSlashCommand,
  promptForConsentNonInteractive,
  promptForSetting,
  renderSkillActionFeedback,
  requestConsentNonInteractive,
  require_semver,
  skillsConsentString,
  startAutoMemoryIfEnabled,
  statusCommand,
  terminalCapabilityManager,
  themeManager,
  uninstallSkill,
  updateAllUpdatableExtensions,
  updateExtension,
  validateAuthMethod
} from "./chunk-RZEC4FDZ.js";
import {
  appEvents
} from "./chunk-5PS3AYFU.js";
import {
  startCommand,
  startServer
} from "./chunk-FCU7PHHL.js";
import {
  exitCli,
  require_source
} from "./chunk-VAPFTYBA.js";
import {
  DEFAULT_PORT,
  GEMMA_MODEL_NAME,
  PLATFORM_BINARY_SHA256,
  RESUME_LATEST,
  SessionError,
  SessionSelector,
  SettingScope,
  USER_SETTINGS_PATH,
  cleanupExpiredSessions,
  cleanupToolOutputFiles,
  detectPlatform,
  formatRelativeTime,
  getBinaryDownloadUrl,
  getBinaryPath,
  getLogFilePath,
  getPidFilePath,
  getThemeTypeFromBackgroundColor,
  isBinaryInstalled,
  isExpectedLiteRtServerProcess,
  isFolderTrustEnabled,
  isModelDownloaded,
  isProcessRunning,
  isServerRunning,
  isWorkspaceTrusted,
  isWorktreeEnabled,
  loadSettings,
  loadTrustedFolders,
  pickDefaultThemeName,
  readServerPid,
  readServerProcessInfo,
  resolveGemmaConfig,
  saveModelChange,
  stripAnsi
} from "./chunk-BFHMA4XD.js";
import {
  RELAUNCH_EXIT_CODE
} from "./chunk-Y47KA5O4.js";
import "./chunk-THFVADMR.js";
import {
  cleanupCheckpoints,
  registerCleanup,
  registerSyncCleanup,
  registerTelemetryConfig,
  runExitCleanup,
  runSyncCleanup,
  setupSignalHandlers
} from "./chunk-O7YZXVZW.js";
import {
  ASK_USER_TOOL_NAME,
  AuthType,
  Config,
  DEFAULT_CONTEXT_FILENAME,
  DEFAULT_FILE_FILTERING_OPTIONS,
  DEFAULT_GEMINI_EMBEDDING_MODEL,
  DEFAULT_GEMINI_FLASH_LITE_MODEL,
  DEFAULT_GEMINI_FLASH_MODEL,
  DEFAULT_GEMINI_MODEL,
  DiscoveredMCPTool,
  ExitCodes,
  FatalAuthenticationError,
  FatalCancellationError,
  FatalConfigError,
  FatalError,
  FatalInputError,
  FatalSandboxError,
  FatalToolExecutionError,
  FatalTurnLimitedError,
  FatalUntrustedWorkspaceError,
  FileDiscoveryService,
  FolderTrustDiscoveryService,
  GEMINI_DIR,
  GEMINI_MODEL_ALIAS_AUTO,
  IdeClient,
  InvalidStreamError,
  JsonFormatter,
  LegacyAgentSession,
  Logger,
  MCPServerConfig,
  PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL,
  PREVIEW_GEMINI_3_1_MODEL,
  PREVIEW_GEMINI_FLASH_LITE_MODEL,
  PREVIEW_GEMINI_FLASH_MODEL,
  PREVIEW_GEMINI_MODEL,
  PolicyIntegrityManager,
  REFERENCE_CONTENT_START,
  ROOT_SCHEDULER_ID,
  ReadManyFilesTool,
  Scheduler,
  ShellExecutionService,
  SimpleExtensionLoader,
  Storage,
  StreamJsonFormatter,
  ToolCallEvent,
  ToolConfirmationOutcome,
  UserAccountManager,
  UserPromptEvent,
  ValidationCancelledError,
  ValidationRequiredError,
  applyAdminAllowlist,
  applyRequiredServers,
  clearCachedCredentialFile,
  convertSessionToClientHistory,
  convertToFunctionResponse,
  coreEvents,
  createPolicyEngineConfig,
  createPolicyUpdater,
  createSessionId,
  createTransport,
  createWorkingStdio,
  createWorktreeService,
  debugLogger,
  deleteStoredSession,
  detectIdeFromEnv,
  displayContentToString,
  execa,
  external_exports,
  external_exports2,
  geminiPartsToContentParts,
  generateSummary,
  getAdminBlockedMcpServersMessage,
  getAdminErrorMessage,
  getAuthTypeFromEnv,
  getAutoModelDescription,
  getCheckpointInfoList,
  getCompatibilityWarnings,
  getDisplayString,
  getErrorMessage,
  getErrorStatus,
  getErrorType,
  getOauthClient,
  getPackageJson,
  getProjectHash,
  getProjectRootForWorktree,
  getPty,
  getRealPath,
  getToolCallDataSchema,
  getVersion,
  homedir,
  isFatalToolError,
  isGeminiWorktree,
  isHeadlessMode,
  isNodeError,
  isTextPart,
  isWithinRoot,
  listExtensions,
  listInboxMemoryPatches,
  listInboxPatches,
  listInboxSkills,
  listMemoryFiles,
  loadConversationRecord,
  logToolCall,
  logUserPrompt,
  parseAndFormatApiError,
  partListUnionToString,
  patchStdio,
  performInit,
  performRestore,
  processSingleFileContent,
  promptIdContext,
  recordToolCallInteractions,
  refreshMemory,
  require_command_exists,
  require_dist,
  require_fast_deep_equal,
  require_fast_uri,
  require_shell_quote,
  require_strip_json_comments,
  resetGeminiMdFilename,
  resolveAtCommandPath,
  resolveTelemetrySettings,
  resolveToRealPath,
  setGeminiMdFilename,
  shouldEnterAlternateScreen,
  showMemory,
  startupProfiler,
  uiTelemetryService,
  updatePolicy,
  writeToStderr,
  writeToStdout
} from "./chunk-LIIMVZVT.js";
import "./chunk-664ZODQF.js";
import "./chunk-TUDYL3X4.js";
import "./chunk-IUUIT4SU.js";
import {
  __commonJS,
  __export,
  __require,
  __toESM
} from "./chunk-34MYV7JD.js";

// packages/cli/node_modules/ajv/dist/compile/codegen/code.js
var require_code = __commonJS({
  "packages/cli/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(s) {
        super();
        if (!exports.IDENTIFIER.test(s))
          throw new Error("CodeGen: name must be a valid identifier");
        this.str = s;
      }
      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 _a4;
        return (_a4 = this._str) !== null && _a4 !== void 0 ? _a4 : this._str = this._items.reduce((s, c) => `${s}${c}`, "");
      }
      get names() {
        var _a4;
        return (_a4 = this._names) !== null && _a4 !== void 0 ? _a4 : 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 _(strs, ...args) {
      const code = [strs[0]];
      let i = 0;
      while (i < args.length) {
        addCodeArg(code, args[i]);
        code.push(strs[++i]);
      }
      return new _Code(code);
    }
    exports._ = _;
    var plus = new _Code("+");
    function str(strs, ...args) {
      const expr = [safeStringify(strs[0])];
      let i = 0;
      while (i < args.length) {
        expr.push(plus);
        addCodeArg(expr, args[i]);
        expr.push(plus, safeStringify(strs[++i]));
      }
      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 i = 1;
      while (i < expr.length - 1) {
        if (expr[i] === plus) {
          const res = mergeExprItems(expr[i - 1], expr[i + 1]);
          if (res !== void 0) {
            expr.splice(i - 1, 3, res);
            continue;
          }
          expr[i++] = "+";
        }
        i++;
      }
    }
    function mergeExprItems(a, b) {
      if (b === '""')
        return a;
      if (a === '""')
        return b;
      if (typeof a == "string") {
        if (b instanceof Name || a[a.length - 1] !== '"')
          return;
        if (typeof b != "string")
          return `${a.slice(0, -1)}${b}"`;
        if (b[0] === '"')
          return a.slice(0, -1) + b.slice(1);
        return;
      }
      if (typeof b == "string" && b[0] === '"' && !(a instanceof Name))
        return `"${a}${b.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 stringify(x) {
      return new _Code(safeStringify(x));
    }
    exports.stringify = stringify;
    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}`) : _`[${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;
  }
});

// packages/cli/node_modules/ajv/dist/compile/codegen/scope.js
var require_scope = __commonJS({
  "packages/cli/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 Scope = 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 _a4, _b2;
        if (((_b2 = (_a4 = this._parent) === null || _a4 === void 0 ? void 0 : _a4._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 = Scope;
    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 Scope {
      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 _a4;
        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 = (_a4 = value.key) !== null && _a4 !== void 0 ? _a4 : 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 s = this._scope[prefix] || (this._scope[prefix] = []);
        const itemIndex = s.length;
        s[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;
  }
});

// packages/cli/node_modules/ajv/dist/compile/codegen/index.js
var require_codegen = __commonJS({
  "packages/cli/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(error) {
        super();
        this.error = error;
      }
      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 i = nodes.length;
        while (i--) {
          const n = nodes[i].optimizeNodes();
          if (Array.isArray(n))
            nodes.splice(i, 1, ...n);
          else if (n)
            nodes[i] = n;
          else
            nodes.splice(i, 1);
        }
        return nodes.length > 0 ? this : void 0;
      }
      optimizeNames(names, constants) {
        const { nodes } = this;
        let i = nodes.length;
        while (i--) {
          const n = nodes[i];
          if (n.optimizeNames(names, constants))
            continue;
          subtractNames(names, n.names);
          nodes.splice(i, 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 e = this.else;
        if (e) {
          const ns = e.optimizeNodes();
          e = this.else = Array.isArray(ns) ? new Else(ns) : ns;
        }
        if (e) {
          if (cond === false)
            return e instanceof _If ? e : e.nodes;
          if (this.nodes.length)
            return this;
          return new _If(not(cond), e instanceof _If ? [e] : e.nodes);
        }
        if (cond === false || !this.nodes.length)
          return void 0;
        return this;
      }
      optimizeNames(names, constants) {
        var _a4;
        this.else = (_a4 = this.else) === null || _a4 === void 0 ? void 0 : _a4.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 _a4, _b2;
        super.optimizeNodes();
        (_a4 = this.catch) === null || _a4 === void 0 ? void 0 : _a4.optimizeNodes();
        (_b2 = this.finally) === null || _b2 === void 0 ? void 0 : _b2.optimizeNodes();
        return this;
      }
      optimizeNames(names, constants) {
        var _a4, _b2;
        super.optimizeNames(names, constants);
        (_a4 = this.catch) === null || _a4 === void 0 ? void 0 : _a4.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(error) {
        super();
        this.error = error;
      }
      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`, (i) => {
            this.var(name, (0, code_1._)`${arr}[${i}]`);
            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 error = this.name("e");
          this._currNode = node.catch = new Catch(error);
          catchCode(error);
        }
        if (finallyCode) {
          this._currNode = node.finally = new Finally();
          this.code(finallyCode);
        }
        return this._endBlockNode(Catch, Finally);
      }
      // `throw` statement
      throw(error) {
        return this._leafNode(new Throw(error));
      }
      // 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(N1, N2) {
        const n = this._currNode;
        if (n instanceof N1 || N2 && n instanceof N2) {
          this._nodes.pop();
          return this;
        }
        throw new Error(`CodeGen: not in block "${N2 ? `${N1.kind}/${N2.kind}` : N1.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(e) {
        return e instanceof code_1._Code && e._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, y) => x === code_1.nil ? y : y === code_1.nil ? x : (0, code_1._)`${par(x)} ${op} ${par(y)}`;
    }
    function par(x) {
      return x instanceof code_1.Name ? x : (0, code_1._)`(${x})`;
    }
  }
});

// packages/cli/node_modules/ajv/dist/compile/util.js
var require_util = __commonJS({
  "packages/cli/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 hash = {};
      for (const item of arr)
        hash[item] = true;
      return hash;
    }
    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 } = it;
      if (!opts.strictSchema)
        return;
      if (typeof schema === "boolean")
        return;
      const rules = self.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, f) {
      if (Array.isArray(xs)) {
        for (const x of xs)
          f(x);
      } else {
        f(xs);
      }
    }
    exports.eachItem = eachItem;
    function makeMergeEvaluated({ mergeNames, mergeToName, mergeValues: mergeValues2, 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) : mergeValues2(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, f) {
      return gen.scopeValue("func", {
        ref: f,
        code: snippets[f.code] || (snippets[f.code] = new code_1._Code(f.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;
  }
});

// packages/cli/node_modules/ajv/dist/compile/names.js
var require_names = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/compile/errors.js
var require_errors = __commonJS({
  "packages/cli/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, error = exports.keywordError, errorPaths, overrideAllErrors) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error, 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, error = exports.keywordError, errorPaths) {
      const { it } = cxt;
      const { gen, compositeRule, allErrors } = it;
      const errObj = errorObjectCode(cxt, error, 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, (i) => {
        gen.const(err, (0, codegen_1._)`${names_1.default.vErrors}[${i}]`);
        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 E = {
      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, error, errorPaths) {
      const { createErrors } = cxt.it;
      if (createErrors === false)
        return (0, codegen_1._)`{}`;
      return errorObject(cxt, error, errorPaths);
    }
    function errorObject(cxt, error, errorPaths = {}) {
      const { gen, it } = cxt;
      const keyValues = [
        errorInstancePath(it, errorPaths),
        errorSchemaPath(cxt, errorPaths)
      ];
      extraErrorProps(cxt, error, 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 [E.schemaPath, schPath];
    }
    function extraErrorProps(cxt, { params, message }, keyValues) {
      const { keyword, data, schemaValue, it } = cxt;
      const { opts, propertyName, topSchemaRef, schemaPath } = it;
      keyValues.push([E.keyword, keyword], [E.params, typeof params == "function" ? params(cxt) : params || (0, codegen_1._)`{}`]);
      if (opts.messages) {
        keyValues.push([E.message, typeof message == "function" ? message(cxt) : message]);
      }
      if (opts.verbose) {
        keyValues.push([E.schema, schemaValue], [E.parentSchema, (0, codegen_1._)`${topSchemaRef}${schemaPath}`], [names_1.default.data, data]);
      }
      if (propertyName)
        keyValues.push([E.propertyName, propertyName]);
    }
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/boolSchema.js
var require_boolSchema = __commonJS({
  "packages/cli/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);
    }
  }
});

// packages/cli/node_modules/ajv/dist/compile/rules.js
var require_rules = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/applicability.js
var require_applicability = __commonJS({
  "packages/cli/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 }, type) {
      const group = self.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 _a4;
      return schema[rule.keyword] !== void 0 || ((_a4 = rule.definition.implements) === null || _a4 === void 0 ? void 0 : _a4.some((kwd) => schema[kwd] !== void 0));
    }
    exports.shouldUseRule = shouldUseRule;
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/dataType.js
var require_dataType = __commonJS({
  "packages/cli/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((t) => COERCIBLE.has(t) || coerceTypes === "array" && t === "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 t of coerceTo) {
        if (COERCIBLE.has(t) || t === "array" && opts.coerceTypes === "array") {
          coerceSpecificType(t);
        }
      }
      gen.else();
      reportTypeError(it);
      gen.endIf();
      gen.if((0, codegen_1._)`${coerced} !== undefined`, () => {
        gen.assign(data, coerced);
        assignParentData(it, coerced);
      });
      function coerceSpecificType(t) {
        switch (t) {
          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 EQ = correct === DataType.Correct ? codegen_1.operators.EQ : codegen_1.operators.NEQ;
      let cond;
      switch (dataType) {
        case "null":
          return (0, codegen_1._)`${data} ${EQ} 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} ${EQ} ${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 t in types)
        cond = (0, codegen_1.and)(cond, checkDataType(t, 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
      };
    }
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/defaults.js
var require_defaults = __commonJS({
  "packages/cli/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, i) => assignDefault(it, i, 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)}`);
    }
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/code.js
var require_code2 = __commonJS({
  "packages/cli/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, (i) => {
          cxt.subschema({
            keyword,
            dataProp: i,
            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, i) => {
        const schCxt = cxt.subschema({
          keyword,
          schemaProp: i,
          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;
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/keyword.js
var require_keyword = __commonJS({
  "packages/cli/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 _a4;
      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((_a4 = def.valid) !== null && _a4 !== void 0 ? _a4 : 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 `), (e) => gen.assign(valid, false).if((0, codegen_1._)`${e} instanceof ${it.ValidationError}`, () => gen.assign(ruleErrs, (0, codegen_1._)`${e}.errors`), () => gen.throw(e)));
        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 _a5;
        gen.if((0, codegen_1.not)((_a5 = def.valid) !== null && _a5 !== void 0 ? _a5 : 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, 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}": ` + self.errorsText(def.validateSchema.errors);
          if (opts.validateSchema === "log")
            self.logger.error(msg);
          else
            throw new Error(msg);
        }
      }
    }
    exports.validateKeywordUsage = validateKeywordUsage;
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/subschema.js
var require_subschema = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/json-schema-traverse/index.js
var require_json_schema_traverse = __commonJS({
  "packages/cli/node_modules/json-schema-traverse/index.js"(exports, module) {
    "use strict";
    var traverse = module.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 i = 0; i < sch.length; i++)
                _traverse(opts, pre, post, sch[i], jsonPtr + "/" + key + "/" + i, rootSchema, jsonPtr, key, schema, i);
            }
          } 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");
    }
  }
});

// packages/cli/node_modules/ajv/dist/compile/resolve.js
var require_resolve = __commonJS({
  "packages/cli/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, _, 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;
  }
});

// packages/cli/node_modules/ajv/dist/compile/validate/index.js
var require_validate = __commonJS({
  "packages/cli/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 }) {
      if (typeof schema == "boolean")
        return !schema;
      for (const key in schema)
        if (self.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 } = it;
      if (schema.$ref && opts.ignoreKeywordsWithRef && (0, util_1.schemaHasRulesButRef)(schema, self.RULES)) {
        self.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 } = it;
      const { RULES } = self;
      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((t) => {
        if (!includesType(it.dataTypes, t)) {
          strictTypesError(it, `type "${t}" 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((t) => hasApplicableType(ts, t))) {
            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, t) {
      return ts.includes(t) || t === "integer" && ts.includes("number");
    }
    function narrowSchemaTypes(it, withTypes) {
      const ts = [];
      for (const t of it.dataTypes) {
        if (includesType(withTypes, t))
          ts.push(t);
        else if (withTypes.includes("integer") && t === "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;
  }
});

// packages/cli/node_modules/ajv/dist/runtime/validation_error.js
var require_validation_error = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/compile/ref_error.js
var require_ref_error = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/compile/index.js
var require_compile = __commonJS({
  "packages/cli/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(env2) {
        var _a4;
        this.refs = {};
        this.dynamicAnchors = {};
        let schema;
        if (typeof env2.schema == "object")
          schema = env2.schema;
        this.schema = env2.schema;
        this.schemaId = env2.schemaId;
        this.root = env2.root || this;
        this.baseId = (_a4 = env2.baseId) !== null && _a4 !== void 0 ? _a4 : (0, resolve_1.normalizeId)(schema === null || schema === void 0 ? void 0 : schema[env2.schemaId || "$id"]);
        this.schemaPath = env2.schemaPath;
        this.localRefs = env2.localRefs;
        this.meta = env2.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 (e) {
        delete sch.validate;
        delete sch.validateName;
        if (sourceCode)
          this.logger.error("Error compiling schema, function code:", sourceCode);
        throw e;
      } finally {
        this._compilations.delete(sch);
      }
    }
    exports.compileSchema = compileSchema;
    function resolveRef(root, baseId, ref) {
      var _a4;
      ref = (0, resolve_1.resolveUrl)(this.opts.uriResolver, baseId, ref);
      const schOrFunc = root.refs[ref];
      if (schOrFunc)
        return schOrFunc;
      let _sch = resolve9.call(this, root, ref);
      if (_sch === void 0) {
        const schema = (_a4 = root.localRefs) === null || _a4 === void 0 ? void 0 : _a4[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(s1, s2) {
      return s1.schema === s2.schema && s1.root === s2.root && s1.baseId === s2.baseId;
    }
    function resolve9(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 _a4;
      if (((_a4 = parsedRef.fragment) === null || _a4 === void 0 ? void 0 : _a4[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 env2;
      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);
        env2 = resolveSchema.call(this, root, $ref);
      }
      const { schemaId } = this.opts;
      env2 = env2 || new SchemaEnv({ schema, schemaId, root, baseId });
      if (env2.schema !== env2.root.schema)
        return env2;
      return void 0;
    }
  }
});

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

// packages/cli/node_modules/ajv/dist/runtime/uri.js
var require_uri = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/core.js
var require_core = __commonJS({
  "packages/cli/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(o) {
      var _a4, _b2, _c2, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0;
      const s = o.strict;
      const _optz = (_a4 = o.code) === null || _a4 === void 0 ? void 0 : _a4.optimize;
      const optimize = _optz === true || _optz === void 0 ? 1 : _optz || 0;
      const regExp = (_c2 = (_b2 = o.code) === null || _b2 === void 0 ? void 0 : _b2.regExp) !== null && _c2 !== void 0 ? _c2 : defaultRegExp;
      const uriResolver = (_d = o.uriResolver) !== null && _d !== void 0 ? _d : uri_1.default;
      return {
        strictSchema: (_f = (_e = o.strictSchema) !== null && _e !== void 0 ? _e : s) !== null && _f !== void 0 ? _f : true,
        strictNumbers: (_h = (_g = o.strictNumbers) !== null && _g !== void 0 ? _g : s) !== null && _h !== void 0 ? _h : true,
        strictTypes: (_k = (_j = o.strictTypes) !== null && _j !== void 0 ? _j : s) !== null && _k !== void 0 ? _k : "log",
        strictTuples: (_m = (_l = o.strictTuples) !== null && _l !== void 0 ? _l : s) !== null && _m !== void 0 ? _m : "log",
        strictRequired: (_p = (_o = o.strictRequired) !== null && _o !== void 0 ? _o : s) !== null && _p !== void 0 ? _p : false,
        code: o.code ? { ...o.code, optimize, regExp } : { optimize, regExp },
        loopRequired: (_q = o.loopRequired) !== null && _q !== void 0 ? _q : MAX_EXPRESSION,
        loopEnum: (_r = o.loopEnum) !== null && _r !== void 0 ? _r : MAX_EXPRESSION,
        meta: (_s = o.meta) !== null && _s !== void 0 ? _s : true,
        messages: (_t = o.messages) !== null && _t !== void 0 ? _t : true,
        inlineRefs: (_u = o.inlineRefs) !== null && _u !== void 0 ? _u : true,
        schemaId: (_v = o.schemaId) !== null && _v !== void 0 ? _v : "$id",
        addUsedSchema: (_w = o.addUsedSchema) !== null && _w !== void 0 ? _w : true,
        validateSchema: (_x = o.validateSchema) !== null && _x !== void 0 ? _x : true,
        validateFormats: (_y = o.validateFormats) !== null && _y !== void 0 ? _y : true,
        unicodeRegExp: (_z = o.unicodeRegExp) !== null && _z !== void 0 ? _z : true,
        int32range: (_0 = o.int32range) !== null && _0 !== void 0 ? _0 : true,
        uriResolver
      };
    }
    var Ajv2 = class {
      constructor(opts = {}) {
        this.schemas = {};
        this.refs = {};
        this.formats = /* @__PURE__ */ Object.create(null);
        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: meta2, schemaId } = this.opts;
        let _dataRefSchema = $dataRefSchema;
        if (schemaId === "id") {
          _dataRefSchema = { ...$dataRefSchema };
          _dataRefSchema.id = _dataRefSchema.$id;
          delete _dataRefSchema.$id;
        }
        if (meta2 && $data)
          this.addMetaSchema(_dataRefSchema, _dataRefSchema[schemaId], false);
      }
      defaultMeta() {
        const { meta: meta2, schemaId } = this.opts;
        return this.opts.defaultMeta = typeof meta2 == "object" ? meta2[schemaId] || meta2 : void 0;
      }
      validate(schemaKeyRef, data) {
        let v;
        if (typeof schemaKeyRef == "string") {
          v = this.getSchema(schemaKeyRef);
          if (!v)
            throw new Error(`no schema with key or ref "${schemaKeyRef}"`);
        } else {
          v = this.compile(schemaKeyRef);
        }
        const valid = v(data);
        if (!("$async" in v))
          this.errors = v.errors;
        return valid;
      }
      compile(schema, _meta) {
        const sch = this._addSchema(schema, _meta);
        return sch.validate || this._compileSchemaEnv(sch);
      }
      compileAsync(schema, meta2) {
        if (typeof this.opts.loadSchema != "function") {
          throw new Error("options.loadSchema should be a function");
        }
        const { loadSchema } = this.opts;
        return runCompileAsync.call(this, schema, meta2);
        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 (e) {
            if (!(e instanceof ref_error_1.default))
              throw e;
            checkLoaded.call(this, e);
            await loadMissingSchema.call(this, e.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, meta2);
        }
        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 ? (k) => addRule.call(this, k, definition) : (k) => definition.type.forEach((t) => addRule.call(this, k, definition, t)));
        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 i = group.rules.findIndex((rule) => rule.keyword === keyword);
          if (i >= 0)
            group.rules.splice(i, 1);
        }
        return this;
      }
      // Add format
      addFormat(name, format3) {
        if (typeof format3 == "string")
          format3 = new RegExp(format3);
        this.formats[name] = format3;
        return this;
      }
      errorsText(errors = this.errors, { separator = ", ", dataVar = "data" } = {}) {
        if (!errors || errors.length === 0)
          return "No errors";
        return errors.map((e) => `${dataVar}${e.instancePath} ${e.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, meta2, 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: meta2, 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, log2 = "error") {
      for (const key in checkOpts) {
        const opt = key;
        if (opt in options)
          this.logger[log2](`${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 format3 = this.opts.formats[name];
        if (format3)
          this.addFormat(name, format3);
      }
    }
    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 _a4;
      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: t }) => t === 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;
      (_a4 = definition.implements) === null || _a4 === void 0 ? void 0 : _a4.forEach((kwd) => this.addKeyword(kwd));
    }
    function addBeforeRule(ruleGroup, rule, before) {
      const i = ruleGroup.rules.findIndex((_rule) => _rule.keyword === before);
      if (i >= 0) {
        ruleGroup.rules.splice(i, 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] };
    }
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/core/id.js
var require_id = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/core/ref.js
var require_ref = __commonJS({
  "packages/cli/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: env2, validateName, opts, self } = it;
        const { root } = env2;
        if (($ref === "#" || $ref === "#/") && baseId === root.baseId)
          return callRootRef();
        const schOrEnv = compile_1.resolveRef.call(self, 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 (env2 === root)
            return callRef(cxt, validateName, env2, env2.$async);
          const rootName = gen.scopeValue("root", { ref: root });
          return callRef(cxt, (0, codegen_1._)`${rootName}.validate`, root, root.$async);
        }
        function callValidate(sch) {
          const v = getValidate(cxt, sch);
          callRef(cxt, v, 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, v, sch, $async) {
      const { gen, it } = cxt;
      const { allErrors, schemaEnv: env2, opts } = it;
      const passCxt = opts.passContext ? names_1.default.this : codegen_1.nil;
      if ($async)
        callAsyncRef();
      else
        callSyncRef();
      function callAsyncRef() {
        if (!env2.$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, v, passCxt)}`);
          addEvaluatedFrom(v);
          if (!allErrors)
            gen.assign(valid, true);
        }, (e) => {
          gen.if((0, codegen_1._)`!(${e} instanceof ${it.ValidationError})`, () => gen.throw(e));
          addErrorsFrom(e);
          if (!allErrors)
            gen.assign(valid, false);
        });
        cxt.ok(valid);
      }
      function callSyncRef() {
        cxt.result((0, code_1.callValidateCode)(cxt, v, passCxt), () => addEvaluatedFrom(v), () => addErrorsFrom(v));
      }
      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 _a4;
        if (!it.opts.unevaluated)
          return;
        const schEvaluated = (_a4 = sch === null || sch === void 0 ? void 0 : sch.validate) === null || _a4 === void 0 ? void 0 : _a4.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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/core/index.js
var require_core2 = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/limitNumber.js
var require_limitNumber = __commonJS({
  "packages/cli/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 error = {
      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,
      code(cxt) {
        const { keyword, data, schemaCode } = cxt;
        cxt.fail$data((0, codegen_1._)`${data} ${KWDs[keyword].fail} ${schemaCode} || isNaN(${data})`);
      }
    };
    exports.default = def;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/multipleOf.js
var require_multipleOf = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/multipleOf.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      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,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/runtime/ucs2length.js
var require_ucs2length = __commonJS({
  "packages/cli/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';
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/limitLength.js
var require_limitLength = __commonJS({
  "packages/cli/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 error = {
      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,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/pattern.js
var require_pattern = __commonJS({
  "packages/cli/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 error = {
      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,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/limitProperties.js
var require_limitProperties = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/limitProperties.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      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,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/required.js
var require_required = __commonJS({
  "packages/cli/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 error = {
      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,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/limitItems.js
var require_limitItems = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/validation/limitItems.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      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,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/runtime/equal.js
var require_equal = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/uniqueItems.js
var require_uniqueItems = __commonJS({
  "packages/cli/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 error = {
      message: ({ params: { i, j } }) => (0, codegen_1.str)`must NOT have duplicate items (items ## ${j} and ${i} are identical)`,
      params: ({ params: { i, j } }) => (0, codegen_1._)`{i: ${i}, j: ${j}}`
    };
    var def = {
      keyword: "uniqueItems",
      type: "array",
      schemaType: "boolean",
      $data: true,
      error,
      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 i = gen.let("i", (0, codegen_1._)`${data}.length`);
          const j = gen.let("j");
          cxt.setParams({ i, j });
          gen.assign(valid, true);
          gen.if((0, codegen_1._)`${i} > 1`, () => (canOptimize() ? loopN : loopN2)(i, j));
        }
        function canOptimize() {
          return itemTypes.length > 0 && !itemTypes.some((t) => t === "object" || t === "array");
        }
        function loopN(i, 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._)`;${i}--;`, () => {
            gen.let(item, (0, codegen_1._)`${data}[${i}]`);
            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}] = ${i}`);
          });
        }
        function loopN2(i, j) {
          const eql = (0, util_1.useFunc)(gen, equal_1.default);
          const outer = gen.name("outer");
          gen.label(outer).for((0, codegen_1._)`;${i}--;`, () => gen.for((0, codegen_1._)`${j} = ${i}; ${j}--;`, () => gen.if((0, codegen_1._)`${eql}(${data}[${i}], ${data}[${j}])`, () => {
            cxt.error();
            gen.assign(valid, false).break(outer);
          })));
        }
      }
    };
    exports.default = def;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/const.js
var require_const = __commonJS({
  "packages/cli/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 error = {
      message: "must be equal to constant",
      params: ({ schemaCode }) => (0, codegen_1._)`{allowedValue: ${schemaCode}}`
    };
    var def = {
      keyword: "const",
      $data: true,
      error,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/enum.js
var require_enum = __commonJS({
  "packages/cli/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 error = {
      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,
      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, i) => equalCode(vSchema, i)));
        }
        cxt.pass(valid);
        function loopEnum() {
          gen.assign(valid, false);
          gen.forOf("v", schemaCode, (v) => gen.if((0, codegen_1._)`${getEql()}(${data}, ${v})`, () => gen.assign(valid, true).break()));
        }
        function equalCode(vSchema, i) {
          const sch = schema[i];
          return typeof sch === "object" && sch !== null ? (0, codegen_1._)`${getEql()}(${data}, ${vSchema}[${i}])` : (0, codegen_1._)`${data} === ${sch}`;
        }
      }
    };
    exports.default = def;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/validation/index.js
var require_validation = __commonJS({
  "packages/cli/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 validation2 = [
      // 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 = validation2;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/additionalItems.js
var require_additionalItems = __commonJS({
  "packages/cli/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 error = {
      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,
      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, (i) => {
          cxt.subschema({ keyword, dataProp: i, dataPropType: util_1.Type.Num }, valid);
          if (!it.allErrors)
            gen.if((0, codegen_1.not)(valid), () => gen.break());
        });
      }
    }
    exports.validateAdditionalItems = validateAdditionalItems;
    exports.default = def;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/items.js
var require_items = __commonJS({
  "packages/cli/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, i) => {
        if ((0, util_1.alwaysValidSchema)(it, sch))
          return;
        gen.if((0, codegen_1._)`${len} > ${i}`, () => cxt.subschema({
          keyword,
          schemaProp: i,
          dataProp: i
        }, valid));
        cxt.ok(valid);
      });
      function checkStrictTuple(sch) {
        const { opts, errSchemaPath } = it;
        const l = schArr.length;
        const fullTuple = l === sch.minItems && (l === sch.maxItems || sch[extraItems] === false);
        if (opts.strictTuples && !fullTuple) {
          const msg = `"${keyword}" is ${l}-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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/prefixItems.js
var require_prefixItems = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/items2020.js
var require_items2020 = __commonJS({
  "packages/cli/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 error = {
      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,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/contains.js
var require_contains = __commonJS({
  "packages/cli/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 error = {
      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,
      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, (i) => {
            cxt.subschema({
              keyword: "contains",
              dataProp: i,
              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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/dependencies.js
var require_dependencies = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/propertyNames.js
var require_propertyNames = __commonJS({
  "packages/cli/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 error = {
      message: "property name must be valid",
      params: ({ params }) => (0, codegen_1._)`{propertyName: ${params.propertyName}}`
    };
    var def = {
      keyword: "propertyNames",
      type: "object",
      schemaType: ["object", "boolean"],
      error,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/additionalProperties.js
var require_additionalProperties = __commonJS({
  "packages/cli/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 error = {
      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,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/properties.js
var require_properties = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/patternProperties.js
var require_patternProperties = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/not.js
var require_not = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/anyOf.js
var require_anyOf = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/oneOf.js
var require_oneOf = __commonJS({
  "packages/cli/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 error = {
      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,
      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, i) => {
            let schCxt;
            if ((0, util_1.alwaysValidSchema)(it, sch)) {
              gen.var(schValid, true);
            } else {
              schCxt = cxt.subschema({
                keyword: "oneOf",
                schemaProp: i,
                compositeRule: true
              }, schValid);
            }
            if (i > 0) {
              gen.if((0, codegen_1._)`${schValid} && ${valid}`).assign(valid, false).assign(passing, (0, codegen_1._)`[${passing}, ${i}]`).else();
            }
            gen.if(schValid, () => {
              gen.assign(valid, true);
              gen.assign(passing, i);
              if (schCxt)
                cxt.mergeEvaluated(schCxt, codegen_1.Name);
            });
          });
        }
      }
    };
    exports.default = def;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/allOf.js
var require_allOf = __commonJS({
  "packages/cli/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, i) => {
          if ((0, util_1.alwaysValidSchema)(it, sch))
            return;
          const schCxt = cxt.subschema({ keyword: "allOf", schemaProp: i }, valid);
          cxt.ok(valid);
          cxt.mergeEvaluated(schCxt);
        });
      }
    };
    exports.default = def;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/if.js
var require_if = __commonJS({
  "packages/cli/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 error = {
      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,
      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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/thenElse.js
var require_thenElse = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/applicator/index.js
var require_applicator = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/format/format.js
var require_format = __commonJS({
  "packages/cli/node_modules/ajv/dist/vocabularies/format/format.js"(exports) {
    "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });
    var codegen_1 = require_codegen();
    var error = {
      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,
      code(cxt, ruleType) {
        const { gen, data, $data, schema, schemaCode, it } = cxt;
        const { opts, errSchemaPath, schemaEnv, self } = it;
        if (!opts.validateFormats)
          return;
        if ($data)
          validate$DataFormat();
        else
          validateFormat();
        function validate$DataFormat() {
          const fmts = gen.scopeValue("formats", {
            ref: self.formats,
            code: opts.code.formats
          });
          const fDef = gen.const("fDef", (0, codegen_1._)`${fmts}[${schemaCode}]`);
          const fType = gen.let("fType");
          const format3 = gen.let("format");
          gen.if((0, codegen_1._)`typeof ${fDef} == "object" && !(${fDef} instanceof RegExp)`, () => gen.assign(fType, (0, codegen_1._)`${fDef}.type || "string"`).assign(format3, (0, codegen_1._)`${fDef}.validate`), () => gen.assign(fType, (0, codegen_1._)`"string"`).assign(format3, 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} && !${format3}`;
          }
          function invalidFmt() {
            const callFormat = schemaEnv.$async ? (0, codegen_1._)`(${fDef}.async ? await ${format3}(${data}) : ${format3}(${data}))` : (0, codegen_1._)`${format3}(${data})`;
            const validData = (0, codegen_1._)`(typeof ${format3} == "function" ? ${callFormat} : ${format3}.test(${data}))`;
            return (0, codegen_1._)`${format3} && ${format3} !== true && ${fType} === ${ruleType} && !${validData}`;
          }
        }
        function validateFormat() {
          const formatDef = self.formats[schema];
          if (!formatDef) {
            unknownFormat();
            return;
          }
          if (formatDef === true)
            return;
          const [fmtType, format3, fmtRef] = getFormat(formatDef);
          if (fmtType === ruleType)
            cxt.pass(validCondition());
          function unknownFormat() {
            if (opts.strictSchema === false) {
              self.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 format3 == "function" ? (0, codegen_1._)`${fmtRef}(${data})` : (0, codegen_1._)`${fmtRef}.test(${data})`;
          }
        }
      }
    };
    exports.default = def;
  }
});

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

// packages/cli/node_modules/ajv/dist/vocabularies/metadata.js
var require_metadata = __commonJS({
  "packages/cli/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"
    ];
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/draft7.js
var require_draft7 = __commonJS({
  "packages/cli/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;
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/discriminator/types.js
var require_types = __commonJS({
  "packages/cli/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 = {}));
  }
});

// packages/cli/node_modules/ajv/dist/vocabularies/discriminator/index.js
var require_discriminator = __commonJS({
  "packages/cli/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 error = {
      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,
      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 _a4;
          const oneOfMapping = {};
          const topRequired = hasRequired(parentSchema);
          let tagRequired = true;
          for (let i = 0; i < oneOf.length; i++) {
            let sch = oneOf[i];
            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 = (_a4 = sch === null || sch === void 0 ? void 0 : sch.properties) === null || _a4 === void 0 ? void 0 : _a4[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, i);
          }
          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, i) {
            if (sch.const) {
              addMapping(sch.const, i);
            } else if (sch.enum) {
              for (const tagValue of sch.enum) {
                addMapping(tagValue, i);
              }
            } else {
              throw new Error(`discriminator: "properties/${tagName}" must have "const" or "enum"`);
            }
          }
          function addMapping(tagValue, i) {
            if (typeof tagValue != "string" || tagValue in oneOfMapping) {
              throw new Error(`discriminator: "${tagName}" values must be unique strings`);
            }
            oneOfMapping[tagValue] = i;
          }
        }
      }
    };
    exports.default = def;
  }
});

// packages/cli/node_modules/ajv/dist/refs/json-schema-draft-07.json
var require_json_schema_draft_07 = __commonJS({
  "packages/cli/node_modules/ajv/dist/refs/json-schema-draft-07.json"(exports, module) {
    module.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
    };
  }
});

// packages/cli/node_modules/ajv/dist/ajv.js
var require_ajv = __commonJS({
  "packages/cli/node_modules/ajv/dist/ajv.js"(exports, module) {
    "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((v) => this.addVocabulary(v));
        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;
    module.exports = exports = Ajv2;
    module.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/yargs/lib/platform-shims/esm.mjs
import { notStrictEqual, strictEqual } from "assert";

// node_modules/cliui/build/lib/index.js
var align = {
  right: alignRight,
  center: alignCenter
};
var top = 0;
var right = 1;
var bottom = 2;
var left = 3;
var UI = class {
  constructor(opts) {
    var _a4;
    this.width = opts.width;
    this.wrap = (_a4 = opts.wrap) !== null && _a4 !== void 0 ? _a4 : true;
    this.rows = [];
  }
  span(...args) {
    const cols = this.div(...args);
    cols.span = true;
  }
  resetOutput() {
    this.rows = [];
  }
  div(...args) {
    if (args.length === 0) {
      this.div("");
    }
    if (this.wrap && this.shouldApplyLayoutDSL(...args) && typeof args[0] === "string") {
      return this.applyLayoutDSL(args[0]);
    }
    const cols = args.map((arg) => {
      if (typeof arg === "string") {
        return this.colFromString(arg);
      }
      return arg;
    });
    this.rows.push(cols);
    return cols;
  }
  shouldApplyLayoutDSL(...args) {
    return args.length === 1 && typeof args[0] === "string" && /[\t\n]/.test(args[0]);
  }
  applyLayoutDSL(str) {
    const rows = str.split("\n").map((row) => row.split("	"));
    let leftColumnWidth = 0;
    rows.forEach((columns) => {
      if (columns.length > 1 && mixin.stringWidth(columns[0]) > leftColumnWidth) {
        leftColumnWidth = Math.min(Math.floor(this.width * 0.5), mixin.stringWidth(columns[0]));
      }
    });
    rows.forEach((columns) => {
      this.div(...columns.map((r, i) => {
        return {
          text: r.trim(),
          padding: this.measurePadding(r),
          width: i === 0 && columns.length > 1 ? leftColumnWidth : void 0
        };
      }));
    });
    return this.rows[this.rows.length - 1];
  }
  colFromString(text) {
    return {
      text,
      padding: this.measurePadding(text)
    };
  }
  measurePadding(str) {
    const noAnsi = mixin.stripAnsi(str);
    return [0, noAnsi.match(/\s*$/)[0].length, 0, noAnsi.match(/^\s*/)[0].length];
  }
  toString() {
    const lines = [];
    this.rows.forEach((row) => {
      this.rowToString(row, lines);
    });
    return lines.filter((line) => !line.hidden).map((line) => line.text).join("\n");
  }
  rowToString(row, lines) {
    this.rasterize(row).forEach((rrow, r) => {
      let str = "";
      rrow.forEach((col, c) => {
        const { width } = row[c];
        const wrapWidth = this.negatePadding(row[c]);
        let ts = col;
        if (wrapWidth > mixin.stringWidth(col)) {
          ts += " ".repeat(wrapWidth - mixin.stringWidth(col));
        }
        if (row[c].align && row[c].align !== "left" && this.wrap) {
          const fn = align[row[c].align];
          ts = fn(ts, wrapWidth);
          if (mixin.stringWidth(ts) < wrapWidth) {
            ts += " ".repeat((width || 0) - mixin.stringWidth(ts) - 1);
          }
        }
        const padding = row[c].padding || [0, 0, 0, 0];
        if (padding[left]) {
          str += " ".repeat(padding[left]);
        }
        str += addBorder(row[c], ts, "| ");
        str += ts;
        str += addBorder(row[c], ts, " |");
        if (padding[right]) {
          str += " ".repeat(padding[right]);
        }
        if (r === 0 && lines.length > 0) {
          str = this.renderInline(str, lines[lines.length - 1]);
        }
      });
      lines.push({
        text: str.replace(/ +$/, ""),
        span: row.span
      });
    });
    return lines;
  }
  // if the full 'source' can render in
  // the target line, do so.
  renderInline(source, previousLine) {
    const match = source.match(/^ */);
    const leadingWhitespace = match ? match[0].length : 0;
    const target = previousLine.text;
    const targetTextWidth = mixin.stringWidth(target.trimRight());
    if (!previousLine.span) {
      return source;
    }
    if (!this.wrap) {
      previousLine.hidden = true;
      return target + source;
    }
    if (leadingWhitespace < targetTextWidth) {
      return source;
    }
    previousLine.hidden = true;
    return target.trimRight() + " ".repeat(leadingWhitespace - targetTextWidth) + source.trimLeft();
  }
  rasterize(row) {
    const rrows = [];
    const widths = this.columnWidths(row);
    let wrapped;
    row.forEach((col, c) => {
      col.width = widths[c];
      if (this.wrap) {
        wrapped = mixin.wrap(col.text, this.negatePadding(col), { hard: true }).split("\n");
      } else {
        wrapped = col.text.split("\n");
      }
      if (col.border) {
        wrapped.unshift("." + "-".repeat(this.negatePadding(col) + 2) + ".");
        wrapped.push("'" + "-".repeat(this.negatePadding(col) + 2) + "'");
      }
      if (col.padding) {
        wrapped.unshift(...new Array(col.padding[top] || 0).fill(""));
        wrapped.push(...new Array(col.padding[bottom] || 0).fill(""));
      }
      wrapped.forEach((str, r) => {
        if (!rrows[r]) {
          rrows.push([]);
        }
        const rrow = rrows[r];
        for (let i = 0; i < c; i++) {
          if (rrow[i] === void 0) {
            rrow.push("");
          }
        }
        rrow.push(str);
      });
    });
    return rrows;
  }
  negatePadding(col) {
    let wrapWidth = col.width || 0;
    if (col.padding) {
      wrapWidth -= (col.padding[left] || 0) + (col.padding[right] || 0);
    }
    if (col.border) {
      wrapWidth -= 4;
    }
    return wrapWidth;
  }
  columnWidths(row) {
    if (!this.wrap) {
      return row.map((col) => {
        return col.width || mixin.stringWidth(col.text);
      });
    }
    let unset = row.length;
    let remainingWidth = this.width;
    const widths = row.map((col) => {
      if (col.width) {
        unset--;
        remainingWidth -= col.width;
        return col.width;
      }
      return void 0;
    });
    const unsetWidth = unset ? Math.floor(remainingWidth / unset) : 0;
    return widths.map((w, i) => {
      if (w === void 0) {
        return Math.max(unsetWidth, _minWidth(row[i]));
      }
      return w;
    });
  }
};
function addBorder(col, ts, style) {
  if (col.border) {
    if (/[.']-+[.']/.test(ts)) {
      return "";
    }
    if (ts.trim().length !== 0) {
      return style;
    }
    return "  ";
  }
  return "";
}
function _minWidth(col) {
  const padding = col.padding || [];
  const minWidth = 1 + (padding[left] || 0) + (padding[right] || 0);
  if (col.border) {
    return minWidth + 4;
  }
  return minWidth;
}
function getWindowWidth() {
  if (typeof process === "object" && process.stdout && process.stdout.columns) {
    return process.stdout.columns;
  }
  return 80;
}
function alignRight(str, width) {
  str = str.trim();
  const strWidth = mixin.stringWidth(str);
  if (strWidth < width) {
    return " ".repeat(width - strWidth) + str;
  }
  return str;
}
function alignCenter(str, width) {
  str = str.trim();
  const strWidth = mixin.stringWidth(str);
  if (strWidth >= width) {
    return str;
  }
  return " ".repeat(width - strWidth >> 1) + str;
}
var mixin;
function cliui(opts, _mixin) {
  mixin = _mixin;
  return new UI({
    width: (opts === null || opts === void 0 ? void 0 : opts.width) || getWindowWidth(),
    wrap: opts === null || opts === void 0 ? void 0 : opts.wrap
  });
}

// node_modules/cliui/build/lib/string-utils.js
var ansi = new RegExp("\x1B(?:\\[(?:\\d+[ABCDEFGJKSTm]|\\d+;\\d+[Hfm]|\\d+;\\d+;\\d+m|6n|s|u|\\?25[lh])|\\w)", "g");
function stripAnsi2(str) {
  return str.replace(ansi, "");
}
function wrap(str, width) {
  const [start, end] = str.match(ansi) || ["", ""];
  str = stripAnsi2(str);
  let wrapped = "";
  for (let i = 0; i < str.length; i++) {
    if (i !== 0 && i % width === 0) {
      wrapped += "\n";
    }
    wrapped += str.charAt(i);
  }
  if (start && end) {
    wrapped = `${start}${wrapped}${end}`;
  }
  return wrapped;
}

// node_modules/cliui/index.mjs
function ui(opts) {
  return cliui(opts, {
    stringWidth: (str) => {
      return [...str].length;
    },
    stripAnsi: stripAnsi2,
    wrap
  });
}

// node_modules/escalade/sync/index.mjs
import { dirname, resolve } from "path";
import { readdirSync, statSync } from "fs";
function sync_default(start, callback) {
  let dir = resolve(".", start);
  let tmp, stats = statSync(dir);
  if (!stats.isDirectory()) {
    dir = dirname(dir);
  }
  while (true) {
    tmp = callback(dir, readdirSync(dir));
    if (tmp) return resolve(dir, tmp);
    dir = dirname(tmp = dir);
    if (tmp === dir) break;
  }
}

// node_modules/yargs/lib/platform-shims/esm.mjs
import { inspect } from "util";
import { readFileSync as readFileSync3 } from "fs";
import { fileURLToPath } from "url";

// node_modules/yargs-parser/build/lib/index.js
import { format } from "util";
import { normalize, resolve as resolve2 } from "path";

// node_modules/yargs-parser/build/lib/string-utils.js
function camelCase(str) {
  const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase();
  if (!isCamelCase) {
    str = str.toLowerCase();
  }
  if (str.indexOf("-") === -1 && str.indexOf("_") === -1) {
    return str;
  } else {
    let camelcase = "";
    let nextChrUpper = false;
    const leadingHyphens = str.match(/^-+/);
    for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) {
      let chr = str.charAt(i);
      if (nextChrUpper) {
        nextChrUpper = false;
        chr = chr.toUpperCase();
      }
      if (i !== 0 && (chr === "-" || chr === "_")) {
        nextChrUpper = true;
      } else if (chr !== "-" && chr !== "_") {
        camelcase += chr;
      }
    }
    return camelcase;
  }
}
function decamelize(str, joinString) {
  const lowercase2 = str.toLowerCase();
  joinString = joinString || "-";
  let notCamelcase = "";
  for (let i = 0; i < str.length; i++) {
    const chrLower = lowercase2.charAt(i);
    const chrString = str.charAt(i);
    if (chrLower !== chrString && i > 0) {
      notCamelcase += `${joinString}${lowercase2.charAt(i)}`;
    } else {
      notCamelcase += chrString;
    }
  }
  return notCamelcase;
}
function looksLikeNumber(x) {
  if (x === null || x === void 0)
    return false;
  if (typeof x === "number")
    return true;
  if (/^0x[0-9a-f]+$/i.test(x))
    return true;
  if (/^0[^.]/.test(x))
    return false;
  return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}

// node_modules/yargs-parser/build/lib/tokenize-arg-string.js
function tokenizeArgString(argString) {
  if (Array.isArray(argString)) {
    return argString.map((e) => typeof e !== "string" ? e + "" : e);
  }
  argString = argString.trim();
  let i = 0;
  let prevC = null;
  let c = null;
  let opening = null;
  const args = [];
  for (let ii = 0; ii < argString.length; ii++) {
    prevC = c;
    c = argString.charAt(ii);
    if (c === " " && !opening) {
      if (!(prevC === " ")) {
        i++;
      }
      continue;
    }
    if (c === opening) {
      opening = null;
    } else if ((c === "'" || c === '"') && !opening) {
      opening = c;
    }
    if (!args[i])
      args[i] = "";
    args[i] += c;
  }
  return args;
}

// node_modules/yargs-parser/build/lib/yargs-parser-types.js
var DefaultValuesForTypeKey;
(function(DefaultValuesForTypeKey2) {
  DefaultValuesForTypeKey2["BOOLEAN"] = "boolean";
  DefaultValuesForTypeKey2["STRING"] = "string";
  DefaultValuesForTypeKey2["NUMBER"] = "number";
  DefaultValuesForTypeKey2["ARRAY"] = "array";
})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {}));

// node_modules/yargs-parser/build/lib/yargs-parser.js
var mixin2;
var YargsParser = class {
  constructor(_mixin) {
    mixin2 = _mixin;
  }
  parse(argsInput, options) {
    const opts = Object.assign({
      alias: void 0,
      array: void 0,
      boolean: void 0,
      config: void 0,
      configObjects: void 0,
      configuration: void 0,
      coerce: void 0,
      count: void 0,
      default: void 0,
      envPrefix: void 0,
      narg: void 0,
      normalize: void 0,
      string: void 0,
      number: void 0,
      __: void 0,
      key: void 0
    }, options);
    const args = tokenizeArgString(argsInput);
    const inputIsString = typeof argsInput === "string";
    const aliases = combineAliases(Object.assign(/* @__PURE__ */ Object.create(null), opts.alias));
    const configuration = Object.assign({
      "boolean-negation": true,
      "camel-case-expansion": true,
      "combine-arrays": false,
      "dot-notation": true,
      "duplicate-arguments-array": true,
      "flatten-duplicate-arrays": true,
      "greedy-arrays": true,
      "halt-at-non-option": false,
      "nargs-eats-options": false,
      "negation-prefix": "no-",
      "parse-numbers": true,
      "parse-positional-numbers": true,
      "populate--": false,
      "set-placeholder-key": false,
      "short-option-groups": true,
      "strip-aliased": false,
      "strip-dashed": false,
      "unknown-options-as-args": false
    }, opts.configuration);
    const defaults = Object.assign(/* @__PURE__ */ Object.create(null), opts.default);
    const configObjects = opts.configObjects || [];
    const envPrefix = opts.envPrefix;
    const notFlagsOption = configuration["populate--"];
    const notFlagsArgv = notFlagsOption ? "--" : "_";
    const newAliases = /* @__PURE__ */ Object.create(null);
    const defaulted = /* @__PURE__ */ Object.create(null);
    const __ = opts.__ || mixin2.format;
    const flags = {
      aliases: /* @__PURE__ */ Object.create(null),
      arrays: /* @__PURE__ */ Object.create(null),
      bools: /* @__PURE__ */ Object.create(null),
      strings: /* @__PURE__ */ Object.create(null),
      numbers: /* @__PURE__ */ Object.create(null),
      counts: /* @__PURE__ */ Object.create(null),
      normalize: /* @__PURE__ */ Object.create(null),
      configs: /* @__PURE__ */ Object.create(null),
      nargs: /* @__PURE__ */ Object.create(null),
      coercions: /* @__PURE__ */ Object.create(null),
      keys: []
    };
    const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/;
    const negatedBoolean = new RegExp("^--" + configuration["negation-prefix"] + "(.+)");
    [].concat(opts.array || []).filter(Boolean).forEach(function(opt) {
      const key = typeof opt === "object" ? opt.key : opt;
      const assignment = Object.keys(opt).map(function(key2) {
        const arrayFlagKeys = {
          boolean: "bools",
          string: "strings",
          number: "numbers"
        };
        return arrayFlagKeys[key2];
      }).filter(Boolean).pop();
      if (assignment) {
        flags[assignment][key] = true;
      }
      flags.arrays[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.boolean || []).filter(Boolean).forEach(function(key) {
      flags.bools[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.string || []).filter(Boolean).forEach(function(key) {
      flags.strings[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.number || []).filter(Boolean).forEach(function(key) {
      flags.numbers[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.count || []).filter(Boolean).forEach(function(key) {
      flags.counts[key] = true;
      flags.keys.push(key);
    });
    [].concat(opts.normalize || []).filter(Boolean).forEach(function(key) {
      flags.normalize[key] = true;
      flags.keys.push(key);
    });
    if (typeof opts.narg === "object") {
      Object.entries(opts.narg).forEach(([key, value]) => {
        if (typeof value === "number") {
          flags.nargs[key] = value;
          flags.keys.push(key);
        }
      });
    }
    if (typeof opts.coerce === "object") {
      Object.entries(opts.coerce).forEach(([key, value]) => {
        if (typeof value === "function") {
          flags.coercions[key] = value;
          flags.keys.push(key);
        }
      });
    }
    if (typeof opts.config !== "undefined") {
      if (Array.isArray(opts.config) || typeof opts.config === "string") {
        ;
        [].concat(opts.config).filter(Boolean).forEach(function(key) {
          flags.configs[key] = true;
        });
      } else if (typeof opts.config === "object") {
        Object.entries(opts.config).forEach(([key, value]) => {
          if (typeof value === "boolean" || typeof value === "function") {
            flags.configs[key] = value;
          }
        });
      }
    }
    extendAliases(opts.key, aliases, opts.default, flags.arrays);
    Object.keys(defaults).forEach(function(key) {
      (flags.aliases[key] || []).forEach(function(alias) {
        defaults[alias] = defaults[key];
      });
    });
    let error = null;
    checkConfiguration();
    let notFlags = [];
    const argv = Object.assign(/* @__PURE__ */ Object.create(null), { _: [] });
    const argvReturn = {};
    for (let i = 0; i < args.length; i++) {
      const arg = args[i];
      const truncatedArg = arg.replace(/^-{3,}/, "---");
      let broken;
      let key;
      let letters;
      let m;
      let next;
      let value;
      if (arg !== "--" && /^-/.test(arg) && isUnknownOptionAsArg(arg)) {
        pushPositional(arg);
      } else if (truncatedArg.match(/^---+(=|$)/)) {
        pushPositional(arg);
        continue;
      } else if (arg.match(/^--.+=/) || !configuration["short-option-groups"] && arg.match(/^-.+=/)) {
        m = arg.match(/^--?([^=]+)=([\s\S]*)$/);
        if (m !== null && Array.isArray(m) && m.length >= 3) {
          if (checkAllAliases(m[1], flags.arrays)) {
            i = eatArray(i, m[1], args, m[2]);
          } else if (checkAllAliases(m[1], flags.nargs) !== false) {
            i = eatNargs(i, m[1], args, m[2]);
          } else {
            setArg(m[1], m[2], true);
          }
        }
      } else if (arg.match(negatedBoolean) && configuration["boolean-negation"]) {
        m = arg.match(negatedBoolean);
        if (m !== null && Array.isArray(m) && m.length >= 2) {
          key = m[1];
          setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false);
        }
      } else if (arg.match(/^--.+/) || !configuration["short-option-groups"] && arg.match(/^-[^-]+/)) {
        m = arg.match(/^--?(.+)/);
        if (m !== null && Array.isArray(m) && m.length >= 2) {
          key = m[1];
          if (checkAllAliases(key, flags.arrays)) {
            i = eatArray(i, key, args);
          } else if (checkAllAliases(key, flags.nargs) !== false) {
            i = eatNargs(i, key, args);
          } else {
            next = args[i + 1];
            if (next !== void 0 && (!next.match(/^-/) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
              setArg(key, next);
              i++;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next);
              i++;
            } else {
              setArg(key, defaultValue(key));
            }
          }
        }
      } else if (arg.match(/^-.\..+=/)) {
        m = arg.match(/^-([^=]+)=([\s\S]*)$/);
        if (m !== null && Array.isArray(m) && m.length >= 3) {
          setArg(m[1], m[2]);
        }
      } else if (arg.match(/^-.\..+/) && !arg.match(negative)) {
        next = args[i + 1];
        m = arg.match(/^-(.\..+)/);
        if (m !== null && Array.isArray(m) && m.length >= 2) {
          key = m[1];
          if (next !== void 0 && !next.match(/^-/) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
            setArg(key, next);
            i++;
          } else {
            setArg(key, defaultValue(key));
          }
        }
      } else if (arg.match(/^-[^-]+/) && !arg.match(negative)) {
        letters = arg.slice(1, -1).split("");
        broken = false;
        for (let j = 0; j < letters.length; j++) {
          next = arg.slice(j + 2);
          if (letters[j + 1] && letters[j + 1] === "=") {
            value = arg.slice(j + 3);
            key = letters[j];
            if (checkAllAliases(key, flags.arrays)) {
              i = eatArray(i, key, args, value);
            } else if (checkAllAliases(key, flags.nargs) !== false) {
              i = eatNargs(i, key, args, value);
            } else {
              setArg(key, value);
            }
            broken = true;
            break;
          }
          if (next === "-") {
            setArg(letters[j], next);
            continue;
          }
          if (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && checkAllAliases(next, flags.bools) === false) {
            setArg(letters[j], next);
            broken = true;
            break;
          }
          if (letters[j + 1] && letters[j + 1].match(/\W/)) {
            setArg(letters[j], next);
            broken = true;
            break;
          } else {
            setArg(letters[j], defaultValue(letters[j]));
          }
        }
        key = arg.slice(-1)[0];
        if (!broken && key !== "-") {
          if (checkAllAliases(key, flags.arrays)) {
            i = eatArray(i, key, args);
          } else if (checkAllAliases(key, flags.nargs) !== false) {
            i = eatNargs(i, key, args);
          } else {
            next = args[i + 1];
            if (next !== void 0 && (!/^(-|--)[^-]/.test(next) || next.match(negative)) && !checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts)) {
              setArg(key, next);
              i++;
            } else if (/^(true|false)$/.test(next)) {
              setArg(key, next);
              i++;
            } else {
              setArg(key, defaultValue(key));
            }
          }
        }
      } else if (arg.match(/^-[0-9]$/) && arg.match(negative) && checkAllAliases(arg.slice(1), flags.bools)) {
        key = arg.slice(1);
        setArg(key, defaultValue(key));
      } else if (arg === "--") {
        notFlags = args.slice(i + 1);
        break;
      } else if (configuration["halt-at-non-option"]) {
        notFlags = args.slice(i);
        break;
      } else {
        pushPositional(arg);
      }
    }
    applyEnvVars(argv, true);
    applyEnvVars(argv, false);
    setConfig(argv);
    setConfigObjects();
    applyDefaultsAndAliases(argv, flags.aliases, defaults, true);
    applyCoercions(argv);
    if (configuration["set-placeholder-key"])
      setPlaceholderKeys(argv);
    Object.keys(flags.counts).forEach(function(key) {
      if (!hasKey(argv, key.split(".")))
        setArg(key, 0);
    });
    if (notFlagsOption && notFlags.length)
      argv[notFlagsArgv] = [];
    notFlags.forEach(function(key) {
      argv[notFlagsArgv].push(key);
    });
    if (configuration["camel-case-expansion"] && configuration["strip-dashed"]) {
      Object.keys(argv).filter((key) => key !== "--" && key.includes("-")).forEach((key) => {
        delete argv[key];
      });
    }
    if (configuration["strip-aliased"]) {
      ;
      [].concat(...Object.keys(aliases).map((k) => aliases[k])).forEach((alias) => {
        if (configuration["camel-case-expansion"] && alias.includes("-")) {
          delete argv[alias.split(".").map((prop) => camelCase(prop)).join(".")];
        }
        delete argv[alias];
      });
    }
    function pushPositional(arg) {
      const maybeCoercedNumber = maybeCoerceNumber("_", arg);
      if (typeof maybeCoercedNumber === "string" || typeof maybeCoercedNumber === "number") {
        argv._.push(maybeCoercedNumber);
      }
    }
    function eatNargs(i, key, args2, argAfterEqualSign) {
      let ii;
      let toEat = checkAllAliases(key, flags.nargs);
      toEat = typeof toEat !== "number" || isNaN(toEat) ? 1 : toEat;
      if (toEat === 0) {
        if (!isUndefined(argAfterEqualSign)) {
          error = Error(__("Argument unexpected for: %s", key));
        }
        setArg(key, defaultValue(key));
        return i;
      }
      let available = isUndefined(argAfterEqualSign) ? 0 : 1;
      if (configuration["nargs-eats-options"]) {
        if (args2.length - (i + 1) + available < toEat) {
          error = Error(__("Not enough arguments following: %s", key));
        }
        available = toEat;
      } else {
        for (ii = i + 1; ii < args2.length; ii++) {
          if (!args2[ii].match(/^-[^0-9]/) || args2[ii].match(negative) || isUnknownOptionAsArg(args2[ii]))
            available++;
          else
            break;
        }
        if (available < toEat)
          error = Error(__("Not enough arguments following: %s", key));
      }
      let consumed = Math.min(available, toEat);
      if (!isUndefined(argAfterEqualSign) && consumed > 0) {
        setArg(key, argAfterEqualSign);
        consumed--;
      }
      for (ii = i + 1; ii < consumed + i + 1; ii++) {
        setArg(key, args2[ii]);
      }
      return i + consumed;
    }
    function eatArray(i, key, args2, argAfterEqualSign) {
      let argsToSet = [];
      let next = argAfterEqualSign || args2[i + 1];
      const nargsCount = checkAllAliases(key, flags.nargs);
      if (checkAllAliases(key, flags.bools) && !/^(true|false)$/.test(next)) {
        argsToSet.push(true);
      } else if (isUndefined(next) || isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) {
        if (defaults[key] !== void 0) {
          const defVal = defaults[key];
          argsToSet = Array.isArray(defVal) ? defVal : [defVal];
        }
      } else {
        if (!isUndefined(argAfterEqualSign)) {
          argsToSet.push(processValue(key, argAfterEqualSign, true));
        }
        for (let ii = i + 1; ii < args2.length; ii++) {
          if (!configuration["greedy-arrays"] && argsToSet.length > 0 || nargsCount && typeof nargsCount === "number" && argsToSet.length >= nargsCount)
            break;
          next = args2[ii];
          if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))
            break;
          i = ii;
          argsToSet.push(processValue(key, next, inputIsString));
        }
      }
      if (typeof nargsCount === "number" && (nargsCount && argsToSet.length < nargsCount || isNaN(nargsCount) && argsToSet.length === 0)) {
        error = Error(__("Not enough arguments following: %s", key));
      }
      setArg(key, argsToSet);
      return i;
    }
    function setArg(key, val, shouldStripQuotes = inputIsString) {
      if (/-/.test(key) && configuration["camel-case-expansion"]) {
        const alias = key.split(".").map(function(prop) {
          return camelCase(prop);
        }).join(".");
        addNewAlias(key, alias);
      }
      const value = processValue(key, val, shouldStripQuotes);
      const splitKey = key.split(".");
      setKey(argv, splitKey, value);
      if (flags.aliases[key]) {
        flags.aliases[key].forEach(function(x) {
          const keyProperties = x.split(".");
          setKey(argv, keyProperties, value);
        });
      }
      if (splitKey.length > 1 && configuration["dot-notation"]) {
        ;
        (flags.aliases[splitKey[0]] || []).forEach(function(x) {
          let keyProperties = x.split(".");
          const a = [].concat(splitKey);
          a.shift();
          keyProperties = keyProperties.concat(a);
          if (!(flags.aliases[key] || []).includes(keyProperties.join("."))) {
            setKey(argv, keyProperties, value);
          }
        });
      }
      if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) {
        const keys = [key].concat(flags.aliases[key] || []);
        keys.forEach(function(key2) {
          Object.defineProperty(argvReturn, key2, {
            enumerable: true,
            get() {
              return val;
            },
            set(value2) {
              val = typeof value2 === "string" ? mixin2.normalize(value2) : value2;
            }
          });
        });
      }
    }
    function addNewAlias(key, alias) {
      if (!(flags.aliases[key] && flags.aliases[key].length)) {
        flags.aliases[key] = [alias];
        newAliases[alias] = true;
      }
      if (!(flags.aliases[alias] && flags.aliases[alias].length)) {
        addNewAlias(alias, key);
      }
    }
    function processValue(key, val, shouldStripQuotes) {
      if (shouldStripQuotes) {
        val = stripQuotes(val);
      }
      if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) {
        if (typeof val === "string")
          val = val === "true";
      }
      let value = Array.isArray(val) ? val.map(function(v) {
        return maybeCoerceNumber(key, v);
      }) : maybeCoerceNumber(key, val);
      if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === "boolean")) {
        value = increment();
      }
      if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) {
        if (Array.isArray(val))
          value = val.map((val2) => {
            return mixin2.normalize(val2);
          });
        else
          value = mixin2.normalize(val);
      }
      return value;
    }
    function maybeCoerceNumber(key, value) {
      if (!configuration["parse-positional-numbers"] && key === "_")
        return value;
      if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) {
        const shouldCoerceNumber = looksLikeNumber(value) && configuration["parse-numbers"] && Number.isSafeInteger(Math.floor(parseFloat(`${value}`)));
        if (shouldCoerceNumber || !isUndefined(value) && checkAllAliases(key, flags.numbers)) {
          value = Number(value);
        }
      }
      return value;
    }
    function setConfig(argv2) {
      const configLookup = /* @__PURE__ */ Object.create(null);
      applyDefaultsAndAliases(configLookup, flags.aliases, defaults);
      Object.keys(flags.configs).forEach(function(configKey) {
        const configPath = argv2[configKey] || configLookup[configKey];
        if (configPath) {
          try {
            let config2 = null;
            const resolvedConfigPath = mixin2.resolve(mixin2.cwd(), configPath);
            const resolveConfig = flags.configs[configKey];
            if (typeof resolveConfig === "function") {
              try {
                config2 = resolveConfig(resolvedConfigPath);
              } catch (e) {
                config2 = e;
              }
              if (config2 instanceof Error) {
                error = config2;
                return;
              }
            } else {
              config2 = mixin2.require(resolvedConfigPath);
            }
            setConfigObject(config2);
          } catch (ex) {
            if (ex.name === "PermissionDenied")
              error = ex;
            else if (argv2[configKey])
              error = Error(__("Invalid JSON config file: %s", configPath));
          }
        }
      });
    }
    function setConfigObject(config2, prev) {
      Object.keys(config2).forEach(function(key) {
        const value = config2[key];
        const fullKey = prev ? prev + "." + key : key;
        if (typeof value === "object" && value !== null && !Array.isArray(value) && configuration["dot-notation"]) {
          setConfigObject(value, fullKey);
        } else {
          if (!hasKey(argv, fullKey.split(".")) || checkAllAliases(fullKey, flags.arrays) && configuration["combine-arrays"]) {
            setArg(fullKey, value);
          }
        }
      });
    }
    function setConfigObjects() {
      if (typeof configObjects !== "undefined") {
        configObjects.forEach(function(configObject) {
          setConfigObject(configObject);
        });
      }
    }
    function applyEnvVars(argv2, configOnly) {
      if (typeof envPrefix === "undefined")
        return;
      const prefix = typeof envPrefix === "string" ? envPrefix : "";
      const env2 = mixin2.env();
      Object.keys(env2).forEach(function(envVar) {
        if (prefix === "" || envVar.lastIndexOf(prefix, 0) === 0) {
          const keys = envVar.split("__").map(function(key, i) {
            if (i === 0) {
              key = key.substring(prefix.length);
            }
            return camelCase(key);
          });
          if ((configOnly && flags.configs[keys.join(".")] || !configOnly) && !hasKey(argv2, keys)) {
            setArg(keys.join("."), env2[envVar]);
          }
        }
      });
    }
    function applyCoercions(argv2) {
      let coerce;
      const applied = /* @__PURE__ */ new Set();
      Object.keys(argv2).forEach(function(key) {
        if (!applied.has(key)) {
          coerce = checkAllAliases(key, flags.coercions);
          if (typeof coerce === "function") {
            try {
              const value = maybeCoerceNumber(key, coerce(argv2[key]));
              [].concat(flags.aliases[key] || [], key).forEach((ali) => {
                applied.add(ali);
                argv2[ali] = value;
              });
            } catch (err) {
              error = err;
            }
          }
        }
      });
    }
    function setPlaceholderKeys(argv2) {
      flags.keys.forEach((key) => {
        if (~key.indexOf("."))
          return;
        if (typeof argv2[key] === "undefined")
          argv2[key] = void 0;
      });
      return argv2;
    }
    function applyDefaultsAndAliases(obj, aliases2, defaults2, canLog = false) {
      Object.keys(defaults2).forEach(function(key) {
        if (!hasKey(obj, key.split("."))) {
          setKey(obj, key.split("."), defaults2[key]);
          if (canLog)
            defaulted[key] = true;
          (aliases2[key] || []).forEach(function(x) {
            if (hasKey(obj, x.split(".")))
              return;
            setKey(obj, x.split("."), defaults2[key]);
          });
        }
      });
    }
    function hasKey(obj, keys) {
      let o = obj;
      if (!configuration["dot-notation"])
        keys = [keys.join(".")];
      keys.slice(0, -1).forEach(function(key2) {
        o = o[key2] || {};
      });
      const key = keys[keys.length - 1];
      if (typeof o !== "object")
        return false;
      else
        return key in o;
    }
    function setKey(obj, keys, value) {
      let o = obj;
      if (!configuration["dot-notation"])
        keys = [keys.join(".")];
      keys.slice(0, -1).forEach(function(key2) {
        key2 = sanitizeKey(key2);
        if (typeof o === "object" && o[key2] === void 0) {
          o[key2] = {};
        }
        if (typeof o[key2] !== "object" || Array.isArray(o[key2])) {
          if (Array.isArray(o[key2])) {
            o[key2].push({});
          } else {
            o[key2] = [o[key2], {}];
          }
          o = o[key2][o[key2].length - 1];
        } else {
          o = o[key2];
        }
      });
      const key = sanitizeKey(keys[keys.length - 1]);
      const isTypeArray = checkAllAliases(keys.join("."), flags.arrays);
      const isValueArray = Array.isArray(value);
      let duplicate = configuration["duplicate-arguments-array"];
      if (!duplicate && checkAllAliases(key, flags.nargs)) {
        duplicate = true;
        if (!isUndefined(o[key]) && flags.nargs[key] === 1 || Array.isArray(o[key]) && o[key].length === flags.nargs[key]) {
          o[key] = void 0;
        }
      }
      if (value === increment()) {
        o[key] = increment(o[key]);
      } else if (Array.isArray(o[key])) {
        if (duplicate && isTypeArray && isValueArray) {
          o[key] = configuration["flatten-duplicate-arrays"] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]);
        } else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) {
          o[key] = value;
        } else {
          o[key] = o[key].concat([value]);
        }
      } else if (o[key] === void 0 && isTypeArray) {
        o[key] = isValueArray ? value : [value];
      } else if (duplicate && !(o[key] === void 0 || checkAllAliases(key, flags.counts) || checkAllAliases(key, flags.bools))) {
        o[key] = [o[key], value];
      } else {
        o[key] = value;
      }
    }
    function extendAliases(...args2) {
      args2.forEach(function(obj) {
        Object.keys(obj || {}).forEach(function(key) {
          if (flags.aliases[key])
            return;
          flags.aliases[key] = [].concat(aliases[key] || []);
          flags.aliases[key].concat(key).forEach(function(x) {
            if (/-/.test(x) && configuration["camel-case-expansion"]) {
              const c = camelCase(x);
              if (c !== key && flags.aliases[key].indexOf(c) === -1) {
                flags.aliases[key].push(c);
                newAliases[c] = true;
              }
            }
          });
          flags.aliases[key].concat(key).forEach(function(x) {
            if (x.length > 1 && /[A-Z]/.test(x) && configuration["camel-case-expansion"]) {
              const c = decamelize(x, "-");
              if (c !== key && flags.aliases[key].indexOf(c) === -1) {
                flags.aliases[key].push(c);
                newAliases[c] = true;
              }
            }
          });
          flags.aliases[key].forEach(function(x) {
            flags.aliases[x] = [key].concat(flags.aliases[key].filter(function(y) {
              return x !== y;
            }));
          });
        });
      });
    }
    function checkAllAliases(key, flag) {
      const toCheck = [].concat(flags.aliases[key] || [], key);
      const keys = Object.keys(flag);
      const setAlias = toCheck.find((key2) => keys.includes(key2));
      return setAlias ? flag[setAlias] : false;
    }
    function hasAnyFlag(key) {
      const flagsKeys = Object.keys(flags);
      const toCheck = [].concat(flagsKeys.map((k) => flags[k]));
      return toCheck.some(function(flag) {
        return Array.isArray(flag) ? flag.includes(key) : flag[key];
      });
    }
    function hasFlagsMatching(arg, ...patterns) {
      const toCheck = [].concat(...patterns);
      return toCheck.some(function(pattern) {
        const match = arg.match(pattern);
        return match && hasAnyFlag(match[1]);
      });
    }
    function hasAllShortFlags(arg) {
      if (arg.match(negative) || !arg.match(/^-[^-]+/)) {
        return false;
      }
      let hasAllFlags = true;
      let next;
      const letters = arg.slice(1).split("");
      for (let j = 0; j < letters.length; j++) {
        next = arg.slice(j + 2);
        if (!hasAnyFlag(letters[j])) {
          hasAllFlags = false;
          break;
        }
        if (letters[j + 1] && letters[j + 1] === "=" || next === "-" || /[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) || letters[j + 1] && letters[j + 1].match(/\W/)) {
          break;
        }
      }
      return hasAllFlags;
    }
    function isUnknownOptionAsArg(arg) {
      return configuration["unknown-options-as-args"] && isUnknownOption(arg);
    }
    function isUnknownOption(arg) {
      arg = arg.replace(/^-{3,}/, "--");
      if (arg.match(negative)) {
        return false;
      }
      if (hasAllShortFlags(arg)) {
        return false;
      }
      const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/;
      const normalFlag = /^-+([^=]+?)$/;
      const flagEndingInHyphen = /^-+([^=]+?)-$/;
      const flagEndingInDigits = /^-+([^=]+?\d+)$/;
      const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/;
      return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters);
    }
    function defaultValue(key) {
      if (!checkAllAliases(key, flags.bools) && !checkAllAliases(key, flags.counts) && `${key}` in defaults) {
        return defaults[key];
      } else {
        return defaultForType(guessType2(key));
      }
    }
    function defaultForType(type) {
      const def = {
        [DefaultValuesForTypeKey.BOOLEAN]: true,
        [DefaultValuesForTypeKey.STRING]: "",
        [DefaultValuesForTypeKey.NUMBER]: void 0,
        [DefaultValuesForTypeKey.ARRAY]: []
      };
      return def[type];
    }
    function guessType2(key) {
      let type = DefaultValuesForTypeKey.BOOLEAN;
      if (checkAllAliases(key, flags.strings))
        type = DefaultValuesForTypeKey.STRING;
      else if (checkAllAliases(key, flags.numbers))
        type = DefaultValuesForTypeKey.NUMBER;
      else if (checkAllAliases(key, flags.bools))
        type = DefaultValuesForTypeKey.BOOLEAN;
      else if (checkAllAliases(key, flags.arrays))
        type = DefaultValuesForTypeKey.ARRAY;
      return type;
    }
    function isUndefined(num) {
      return num === void 0;
    }
    function checkConfiguration() {
      Object.keys(flags.counts).find((key) => {
        if (checkAllAliases(key, flags.arrays)) {
          error = Error(__("Invalid configuration: %s, opts.count excludes opts.array.", key));
          return true;
        } else if (checkAllAliases(key, flags.nargs)) {
          error = Error(__("Invalid configuration: %s, opts.count excludes opts.narg.", key));
          return true;
        }
        return false;
      });
    }
    return {
      aliases: Object.assign({}, flags.aliases),
      argv: Object.assign(argvReturn, argv),
      configuration,
      defaulted: Object.assign({}, defaulted),
      error,
      newAliases: Object.assign({}, newAliases)
    };
  }
};
function combineAliases(aliases) {
  const aliasArrays = [];
  const combined = /* @__PURE__ */ Object.create(null);
  let change = true;
  Object.keys(aliases).forEach(function(key) {
    aliasArrays.push([].concat(aliases[key], key));
  });
  while (change) {
    change = false;
    for (let i = 0; i < aliasArrays.length; i++) {
      for (let ii = i + 1; ii < aliasArrays.length; ii++) {
        const intersect = aliasArrays[i].filter(function(v) {
          return aliasArrays[ii].indexOf(v) !== -1;
        });
        if (intersect.length) {
          aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]);
          aliasArrays.splice(ii, 1);
          change = true;
          break;
        }
      }
    }
  }
  aliasArrays.forEach(function(aliasArray) {
    aliasArray = aliasArray.filter(function(v, i, self) {
      return self.indexOf(v) === i;
    });
    const lastAlias = aliasArray.pop();
    if (lastAlias !== void 0 && typeof lastAlias === "string") {
      combined[lastAlias] = aliasArray;
    }
  });
  return combined;
}
function increment(orig) {
  return orig !== void 0 ? orig + 1 : 1;
}
function sanitizeKey(key) {
  if (key === "__proto__")
    return "___proto___";
  return key;
}
function stripQuotes(val) {
  return typeof val === "string" && (val[0] === "'" || val[0] === '"') && val[val.length - 1] === val[0] ? val.substring(1, val.length - 1) : val;
}

// node_modules/yargs-parser/build/lib/index.js
import { readFileSync } from "fs";
var _a;
var _b;
var _c;
var minNodeVersion = process && process.env && process.env.YARGS_MIN_NODE_VERSION ? Number(process.env.YARGS_MIN_NODE_VERSION) : 12;
var nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1);
if (nodeVersion) {
  const major = Number(nodeVersion.match(/^([^.]+)/)[1]);
  if (major < minNodeVersion) {
    throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`);
  }
}
var env = process ? process.env : {};
var parser = new YargsParser({
  cwd: process.cwd,
  env: () => {
    return env;
  },
  format,
  normalize,
  resolve: resolve2,
  // TODO: figure  out a  way to combine ESM and CJS coverage, such  that
  // we can exercise all the lines below:
  require: (path16) => {
    if (typeof __require !== "undefined") {
      return __require(path16);
    } else if (path16.match(/\.json$/)) {
      return JSON.parse(readFileSync(path16, "utf8"));
    } else {
      throw Error("only .json config files are supported in ESM");
    }
  }
});
var yargsParser = function Parser(args, opts) {
  const result = parser.parse(args.slice(), opts);
  return result.argv;
};
yargsParser.detailed = function(args, opts) {
  return parser.parse(args.slice(), opts);
};
yargsParser.camelCase = camelCase;
yargsParser.decamelize = decamelize;
yargsParser.looksLikeNumber = looksLikeNumber;
var lib_default = yargsParser;

// node_modules/yargs/lib/platform-shims/esm.mjs
import { basename, dirname as dirname2, extname, relative, resolve as resolve4 } from "path";

// node_modules/yargs/build/lib/utils/process-argv.js
function getProcessArgvBinIndex() {
  if (isBundledElectronApp())
    return 0;
  return 1;
}
function isBundledElectronApp() {
  return isElectronApp() && !process.defaultApp;
}
function isElectronApp() {
  return !!process.versions.electron;
}
function hideBin(argv) {
  return argv.slice(getProcessArgvBinIndex() + 1);
}
function getProcessArgvBin() {
  return process.argv[getProcessArgvBinIndex()];
}

// node_modules/yargs/build/lib/yerror.js
var YError = class _YError extends Error {
  constructor(msg) {
    super(msg || "yargs error");
    this.name = "YError";
    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, _YError);
    }
  }
};

// node_modules/y18n/build/lib/platform-shims/node.js
import { readFileSync as readFileSync2, statSync as statSync2, writeFile } from "fs";
import { format as format2 } from "util";
import { resolve as resolve3 } from "path";
var node_default = {
  fs: {
    readFileSync: readFileSync2,
    writeFile
  },
  format: format2,
  resolve: resolve3,
  exists: (file) => {
    try {
      return statSync2(file).isFile();
    } catch (err) {
      return false;
    }
  }
};

// node_modules/y18n/build/lib/index.js
var shim;
var Y18N = class {
  constructor(opts) {
    opts = opts || {};
    this.directory = opts.directory || "./locales";
    this.updateFiles = typeof opts.updateFiles === "boolean" ? opts.updateFiles : true;
    this.locale = opts.locale || "en";
    this.fallbackToLanguage = typeof opts.fallbackToLanguage === "boolean" ? opts.fallbackToLanguage : true;
    this.cache = /* @__PURE__ */ Object.create(null);
    this.writeQueue = [];
  }
  __(...args) {
    if (typeof arguments[0] !== "string") {
      return this._taggedLiteral(arguments[0], ...arguments);
    }
    const str = args.shift();
    let cb = function() {
    };
    if (typeof args[args.length - 1] === "function")
      cb = args.pop();
    cb = cb || function() {
    };
    if (!this.cache[this.locale])
      this._readLocaleFile();
    if (!this.cache[this.locale][str] && this.updateFiles) {
      this.cache[this.locale][str] = str;
      this._enqueueWrite({
        directory: this.directory,
        locale: this.locale,
        cb
      });
    } else {
      cb();
    }
    return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args));
  }
  __n() {
    const args = Array.prototype.slice.call(arguments);
    const singular = args.shift();
    const plural = args.shift();
    const quantity = args.shift();
    let cb = function() {
    };
    if (typeof args[args.length - 1] === "function")
      cb = args.pop();
    if (!this.cache[this.locale])
      this._readLocaleFile();
    let str = quantity === 1 ? singular : plural;
    if (this.cache[this.locale][singular]) {
      const entry = this.cache[this.locale][singular];
      str = entry[quantity === 1 ? "one" : "other"];
    }
    if (!this.cache[this.locale][singular] && this.updateFiles) {
      this.cache[this.locale][singular] = {
        one: singular,
        other: plural
      };
      this._enqueueWrite({
        directory: this.directory,
        locale: this.locale,
        cb
      });
    } else {
      cb();
    }
    const values = [str];
    if (~str.indexOf("%d"))
      values.push(quantity);
    return shim.format.apply(shim.format, values.concat(args));
  }
  setLocale(locale) {
    this.locale = locale;
  }
  getLocale() {
    return this.locale;
  }
  updateLocale(obj) {
    if (!this.cache[this.locale])
      this._readLocaleFile();
    for (const key in obj) {
      if (Object.prototype.hasOwnProperty.call(obj, key)) {
        this.cache[this.locale][key] = obj[key];
      }
    }
  }
  _taggedLiteral(parts, ...args) {
    let str = "";
    parts.forEach(function(part, i) {
      const arg = args[i + 1];
      str += part;
      if (typeof arg !== "undefined") {
        str += "%s";
      }
    });
    return this.__.apply(this, [str].concat([].slice.call(args, 1)));
  }
  _enqueueWrite(work) {
    this.writeQueue.push(work);
    if (this.writeQueue.length === 1)
      this._processWriteQueue();
  }
  _processWriteQueue() {
    const _this = this;
    const work = this.writeQueue[0];
    const directory = work.directory;
    const locale = work.locale;
    const cb = work.cb;
    const languageFile = this._resolveLocaleFile(directory, locale);
    const serializedLocale = JSON.stringify(this.cache[locale], null, 2);
    shim.fs.writeFile(languageFile, serializedLocale, "utf-8", function(err) {
      _this.writeQueue.shift();
      if (_this.writeQueue.length > 0)
        _this._processWriteQueue();
      cb(err);
    });
  }
  _readLocaleFile() {
    let localeLookup = {};
    const languageFile = this._resolveLocaleFile(this.directory, this.locale);
    try {
      if (shim.fs.readFileSync) {
        localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, "utf-8"));
      }
    } catch (err) {
      if (err instanceof SyntaxError) {
        err.message = "syntax error in " + languageFile;
      }
      if (err.code === "ENOENT")
        localeLookup = {};
      else
        throw err;
    }
    this.cache[this.locale] = localeLookup;
  }
  _resolveLocaleFile(directory, locale) {
    let file = shim.resolve(directory, "./", locale + ".json");
    if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf("_")) {
      const languageFile = shim.resolve(directory, "./", locale.split("_")[0] + ".json");
      if (this._fileExistsSync(languageFile))
        file = languageFile;
    }
    return file;
  }
  _fileExistsSync(file) {
    return shim.exists(file);
  }
};
function y18n(opts, _shim) {
  shim = _shim;
  const y18n3 = new Y18N(opts);
  return {
    __: y18n3.__.bind(y18n3),
    __n: y18n3.__n.bind(y18n3),
    setLocale: y18n3.setLocale.bind(y18n3),
    getLocale: y18n3.getLocale.bind(y18n3),
    updateLocale: y18n3.updateLocale.bind(y18n3),
    locale: y18n3.locale
  };
}

// node_modules/y18n/index.mjs
var y18n2 = (opts) => {
  return y18n(opts, node_default);
};
var y18n_default = y18n2;

// node_modules/yargs/lib/platform-shims/esm.mjs
var REQUIRE_ERROR = "require is not supported by ESM";
var REQUIRE_DIRECTORY_ERROR = "loading a directory of commands is not supported yet for ESM";
var __dirname;
try {
  __dirname = fileURLToPath(import.meta.url);
} catch (e) {
  __dirname = process.cwd();
}
var mainFilename = __dirname.substring(0, __dirname.lastIndexOf("node_modules"));
var esm_default = {
  assert: {
    notStrictEqual,
    strictEqual
  },
  cliui: ui,
  findUp: sync_default,
  getEnv: (key) => {
    return process.env[key];
  },
  inspect,
  getCallerFile: () => {
    throw new YError(REQUIRE_DIRECTORY_ERROR);
  },
  getProcessArgvBin,
  mainFilename: mainFilename || process.cwd(),
  Parser: lib_default,
  path: {
    basename,
    dirname: dirname2,
    extname,
    relative,
    resolve: resolve4
  },
  process: {
    argv: () => process.argv,
    cwd: process.cwd,
    emitWarning: (warning, type) => process.emitWarning(warning, type),
    execPath: () => process.execPath,
    exit: process.exit,
    nextTick: process.nextTick,
    stdColumns: typeof process.stdout.columns !== "undefined" ? process.stdout.columns : null
  },
  readFileSync: readFileSync3,
  require: () => {
    throw new YError(REQUIRE_ERROR);
  },
  requireDirectory: () => {
    throw new YError(REQUIRE_DIRECTORY_ERROR);
  },
  stringWidth: (str) => {
    return [...str].length;
  },
  y18n: y18n_default({
    directory: resolve4(__dirname, "../../../locales"),
    updateFiles: false
  })
};

// node_modules/yargs/build/lib/typings/common-types.js
function assertNotStrictEqual(actual, expected, shim3, message) {
  shim3.assert.notStrictEqual(actual, expected, message);
}
function assertSingleKey(actual, shim3) {
  shim3.assert.strictEqual(typeof actual, "string");
}
function objectKeys(object3) {
  return Object.keys(object3);
}

// node_modules/yargs/build/lib/utils/is-promise.js
function isPromise(maybePromise) {
  return !!maybePromise && !!maybePromise.then && typeof maybePromise.then === "function";
}

// node_modules/yargs/build/lib/parse-command.js
function parseCommand(cmd) {
  const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, " ");
  const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/);
  const bregex = /\.*[\][<>]/g;
  const firstCommand = splitCommand.shift();
  if (!firstCommand)
    throw new Error(`No command found in: ${cmd}`);
  const parsedCommand = {
    cmd: firstCommand.replace(bregex, ""),
    demanded: [],
    optional: []
  };
  splitCommand.forEach((cmd2, i) => {
    let variadic = false;
    cmd2 = cmd2.replace(/\s/g, "");
    if (/\.+[\]>]/.test(cmd2) && i === splitCommand.length - 1)
      variadic = true;
    if (/^\[/.test(cmd2)) {
      parsedCommand.optional.push({
        cmd: cmd2.replace(bregex, "").split("|"),
        variadic
      });
    } else {
      parsedCommand.demanded.push({
        cmd: cmd2.replace(bregex, "").split("|"),
        variadic
      });
    }
  });
  return parsedCommand;
}

// node_modules/yargs/build/lib/argsert.js
var positionName = ["first", "second", "third", "fourth", "fifth", "sixth"];
function argsert(arg1, arg2, arg3) {
  function parseArgs() {
    return typeof arg1 === "object" ? [{ demanded: [], optional: [] }, arg1, arg2] : [
      parseCommand(`cmd ${arg1}`),
      arg2,
      arg3
    ];
  }
  try {
    let position = 0;
    const [parsed, callerArguments, _length2] = parseArgs();
    const args = [].slice.call(callerArguments);
    while (args.length && args[args.length - 1] === void 0)
      args.pop();
    const length = _length2 || args.length;
    if (length < parsed.demanded.length) {
      throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`);
    }
    const totalCommands = parsed.demanded.length + parsed.optional.length;
    if (length > totalCommands) {
      throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`);
    }
    parsed.demanded.forEach((demanded) => {
      const arg = args.shift();
      const observedType = guessType(arg);
      const matchingTypes = demanded.cmd.filter((type) => type === observedType || type === "*");
      if (matchingTypes.length === 0)
        argumentTypeError(observedType, demanded.cmd, position);
      position += 1;
    });
    parsed.optional.forEach((optional2) => {
      if (args.length === 0)
        return;
      const arg = args.shift();
      const observedType = guessType(arg);
      const matchingTypes = optional2.cmd.filter((type) => type === observedType || type === "*");
      if (matchingTypes.length === 0)
        argumentTypeError(observedType, optional2.cmd, position);
      position += 1;
    });
  } catch (err) {
    console.warn(err.stack);
  }
}
function guessType(arg) {
  if (Array.isArray(arg)) {
    return "array";
  } else if (arg === null) {
    return "null";
  }
  return typeof arg;
}
function argumentTypeError(observedType, allowedTypes, position) {
  throw new YError(`Invalid ${positionName[position] || "manyith"} argument. Expected ${allowedTypes.join(" or ")} but received ${observedType}.`);
}

// node_modules/yargs/build/lib/middleware.js
var GlobalMiddleware = class {
  constructor(yargs) {
    this.globalMiddleware = [];
    this.frozens = [];
    this.yargs = yargs;
  }
  addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) {
    argsert("<array|function> [boolean] [boolean] [boolean]", [callback, applyBeforeValidation, global], arguments.length);
    if (Array.isArray(callback)) {
      for (let i = 0; i < callback.length; i++) {
        if (typeof callback[i] !== "function") {
          throw Error("middleware must be a function");
        }
        const m = callback[i];
        m.applyBeforeValidation = applyBeforeValidation;
        m.global = global;
      }
      Array.prototype.push.apply(this.globalMiddleware, callback);
    } else if (typeof callback === "function") {
      const m = callback;
      m.applyBeforeValidation = applyBeforeValidation;
      m.global = global;
      m.mutates = mutates;
      this.globalMiddleware.push(callback);
    }
    return this.yargs;
  }
  addCoerceMiddleware(callback, option) {
    const aliases = this.yargs.getAliases();
    this.globalMiddleware = this.globalMiddleware.filter((m) => {
      const toCheck = [...aliases[option] || [], option];
      if (!m.option)
        return true;
      else
        return !toCheck.includes(m.option);
    });
    callback.option = option;
    return this.addMiddleware(callback, true, true, true);
  }
  getMiddleware() {
    return this.globalMiddleware;
  }
  freeze() {
    this.frozens.push([...this.globalMiddleware]);
  }
  unfreeze() {
    const frozen = this.frozens.pop();
    if (frozen !== void 0)
      this.globalMiddleware = frozen;
  }
  reset() {
    this.globalMiddleware = this.globalMiddleware.filter((m) => m.global);
  }
};
function commandMiddlewareFactory(commandMiddleware) {
  if (!commandMiddleware)
    return [];
  return commandMiddleware.map((middleware) => {
    middleware.applyBeforeValidation = false;
    return middleware;
  });
}
function applyMiddleware(argv, yargs, middlewares, beforeValidation) {
  return middlewares.reduce((acc, middleware) => {
    if (middleware.applyBeforeValidation !== beforeValidation) {
      return acc;
    }
    if (middleware.mutates) {
      if (middleware.applied)
        return acc;
      middleware.applied = true;
    }
    if (isPromise(acc)) {
      return acc.then((initialObj) => Promise.all([initialObj, middleware(initialObj, yargs)])).then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj));
    } else {
      const result = middleware(acc, yargs);
      return isPromise(result) ? result.then((middlewareObj) => Object.assign(acc, middlewareObj)) : Object.assign(acc, result);
    }
  }, argv);
}

// node_modules/yargs/build/lib/utils/maybe-async-result.js
function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => {
  throw err;
}) {
  try {
    const result = isFunction(getResult) ? getResult() : getResult;
    return isPromise(result) ? result.then((result2) => resultHandler(result2)) : resultHandler(result);
  } catch (err) {
    return errorHandler(err);
  }
}
function isFunction(arg) {
  return typeof arg === "function";
}

// node_modules/yargs/build/lib/utils/which-module.js
function whichModule(exported) {
  if (typeof __require === "undefined")
    return null;
  for (let i = 0, files = Object.keys(__require.cache), mod; i < files.length; i++) {
    mod = __require.cache[files[i]];
    if (mod.exports === exported)
      return mod;
  }
  return null;
}

// node_modules/yargs/build/lib/command.js
var DEFAULT_MARKER = /(^\*)|(^\$0)/;
var CommandInstance = class {
  constructor(usage2, validation2, globalMiddleware, shim3) {
    this.requireCache = /* @__PURE__ */ new Set();
    this.handlers = {};
    this.aliasMap = {};
    this.frozens = [];
    this.shim = shim3;
    this.usage = usage2;
    this.globalMiddleware = globalMiddleware;
    this.validation = validation2;
  }
  addDirectory(dir, req, callerFile, opts) {
    opts = opts || {};
    if (typeof opts.recurse !== "boolean")
      opts.recurse = false;
    if (!Array.isArray(opts.extensions))
      opts.extensions = ["js"];
    const parentVisit = typeof opts.visit === "function" ? opts.visit : (o) => o;
    opts.visit = (obj, joined, filename) => {
      const visited = parentVisit(obj, joined, filename);
      if (visited) {
        if (this.requireCache.has(joined))
          return visited;
        else
          this.requireCache.add(joined);
        this.addHandler(visited);
      }
      return visited;
    };
    this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts);
  }
  addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) {
    let aliases = [];
    const middlewares = commandMiddlewareFactory(commandMiddleware);
    handler = handler || (() => {
    });
    if (Array.isArray(cmd)) {
      if (isCommandAndAliases(cmd)) {
        [cmd, ...aliases] = cmd;
      } else {
        for (const command2 of cmd) {
          this.addHandler(command2);
        }
      }
    } else if (isCommandHandlerDefinition(cmd)) {
      let command2 = Array.isArray(cmd.command) || typeof cmd.command === "string" ? cmd.command : this.moduleName(cmd);
      if (cmd.aliases)
        command2 = [].concat(command2).concat(cmd.aliases);
      this.addHandler(command2, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated);
      return;
    } else if (isCommandBuilderDefinition(builder)) {
      this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated);
      return;
    }
    if (typeof cmd === "string") {
      const parsedCommand = parseCommand(cmd);
      aliases = aliases.map((alias) => parseCommand(alias).cmd);
      let isDefault = false;
      const parsedAliases = [parsedCommand.cmd].concat(aliases).filter((c) => {
        if (DEFAULT_MARKER.test(c)) {
          isDefault = true;
          return false;
        }
        return true;
      });
      if (parsedAliases.length === 0 && isDefault)
        parsedAliases.push("$0");
      if (isDefault) {
        parsedCommand.cmd = parsedAliases[0];
        aliases = parsedAliases.slice(1);
        cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd);
      }
      aliases.forEach((alias) => {
        this.aliasMap[alias] = parsedCommand.cmd;
      });
      if (description !== false) {
        this.usage.command(cmd, description, isDefault, aliases, deprecated);
      }
      this.handlers[parsedCommand.cmd] = {
        original: cmd,
        description,
        handler,
        builder: builder || {},
        middlewares,
        deprecated,
        demanded: parsedCommand.demanded,
        optional: parsedCommand.optional
      };
      if (isDefault)
        this.defaultCommand = this.handlers[parsedCommand.cmd];
    }
  }
  getCommandHandlers() {
    return this.handlers;
  }
  getCommands() {
    return Object.keys(this.handlers).concat(Object.keys(this.aliasMap));
  }
  hasDefaultCommand() {
    return !!this.defaultCommand;
  }
  runCommand(command2, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) {
    const commandHandler = this.handlers[command2] || this.handlers[this.aliasMap[command2]] || this.defaultCommand;
    const currentContext = yargs.getInternalMethods().getContext();
    const parentCommands = currentContext.commands.slice();
    const isDefaultCommand = !command2;
    if (command2) {
      currentContext.commands.push(command2);
      currentContext.fullCommands.push(commandHandler.original);
    }
    const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet);
    return isPromise(builderResult) ? builderResult.then((result) => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs);
  }
  applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) {
    const builder = commandHandler.builder;
    let innerYargs = yargs;
    if (isCommandBuilderCallback(builder)) {
      yargs.getInternalMethods().getUsageInstance().freeze();
      const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet);
      if (isPromise(builderOutput)) {
        return builderOutput.then((output) => {
          innerYargs = isYargsInstance(output) ? output : yargs;
          return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
        });
      }
    } else if (isCommandBuilderOptionDefinitions(builder)) {
      yargs.getInternalMethods().getUsageInstance().freeze();
      innerYargs = yargs.getInternalMethods().reset(aliases);
      Object.keys(commandHandler.builder).forEach((key) => {
        innerYargs.option(key, builder[key]);
      });
    }
    return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly);
  }
  parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) {
    if (isDefaultCommand)
      innerYargs.getInternalMethods().getUsageInstance().unfreeze(true);
    if (this.shouldUpdateUsage(innerYargs)) {
      innerYargs.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description);
    }
    const innerArgv = innerYargs.getInternalMethods().runYargsParserAndExecuteCommands(null, void 0, true, commandIndex, helpOnly);
    return isPromise(innerArgv) ? innerArgv.then((argv) => ({
      aliases: innerYargs.parsed.aliases,
      innerArgv: argv
    })) : {
      aliases: innerYargs.parsed.aliases,
      innerArgv
    };
  }
  shouldUpdateUsage(yargs) {
    return !yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && yargs.getInternalMethods().getUsageInstance().getUsage().length === 0;
  }
  usageFromParentCommandsCommandHandler(parentCommands, commandHandler) {
    const c = DEFAULT_MARKER.test(commandHandler.original) ? commandHandler.original.replace(DEFAULT_MARKER, "").trim() : commandHandler.original;
    const pc = parentCommands.filter((c2) => {
      return !DEFAULT_MARKER.test(c2);
    });
    pc.push(c);
    return `$0 ${pc.join(" ")}`;
  }
  handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) {
    if (!yargs.getInternalMethods().getHasOutput()) {
      const validation2 = yargs.getInternalMethods().runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand);
      innerArgv = maybeAsyncResult(innerArgv, (result) => {
        validation2(result);
        return result;
      });
    }
    if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) {
      yargs.getInternalMethods().setHasOutput();
      const populateDoubleDash = !!yargs.getOptions().configuration["populate--"];
      yargs.getInternalMethods().postProcess(innerArgv, populateDoubleDash, false, false);
      innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false);
      innerArgv = maybeAsyncResult(innerArgv, (result) => {
        const handlerResult = commandHandler.handler(result);
        return isPromise(handlerResult) ? handlerResult.then(() => result) : result;
      });
      if (!isDefaultCommand) {
        yargs.getInternalMethods().getUsageInstance().cacheHelpMessage();
      }
      if (isPromise(innerArgv) && !yargs.getInternalMethods().hasParseCallback()) {
        innerArgv.catch((error) => {
          try {
            yargs.getInternalMethods().getUsageInstance().fail(null, error);
          } catch (_err) {
          }
        });
      }
    }
    if (!isDefaultCommand) {
      currentContext.commands.pop();
      currentContext.fullCommands.pop();
    }
    return innerArgv;
  }
  applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) {
    let positionalMap = {};
    if (helpOnly)
      return innerArgv;
    if (!yargs.getInternalMethods().getHasOutput()) {
      positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs);
    }
    const middlewares = this.globalMiddleware.getMiddleware().slice(0).concat(commandHandler.middlewares);
    const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true);
    return isPromise(maybePromiseArgv) ? maybePromiseArgv.then((resolvedInnerArgv) => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap);
  }
  populatePositionals(commandHandler, argv, context, yargs) {
    argv._ = argv._.slice(context.commands.length);
    const demanded = commandHandler.demanded.slice(0);
    const optional2 = commandHandler.optional.slice(0);
    const positionalMap = {};
    this.validation.positionalCount(demanded.length, argv._.length);
    while (demanded.length) {
      const demand = demanded.shift();
      this.populatePositional(demand, argv, positionalMap);
    }
    while (optional2.length) {
      const maybe = optional2.shift();
      this.populatePositional(maybe, argv, positionalMap);
    }
    argv._ = context.commands.concat(argv._.map((a) => "" + a));
    this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs);
    return positionalMap;
  }
  populatePositional(positional, argv, positionalMap) {
    const cmd = positional.cmd[0];
    if (positional.variadic) {
      positionalMap[cmd] = argv._.splice(0).map(String);
    } else {
      if (argv._.length)
        positionalMap[cmd] = [String(argv._.shift())];
    }
  }
  cmdToParseOptions(cmdString) {
    const parseOptions = {
      array: [],
      default: {},
      alias: {},
      demand: {}
    };
    const parsed = parseCommand(cmdString);
    parsed.demanded.forEach((d) => {
      const [cmd, ...aliases] = d.cmd;
      if (d.variadic) {
        parseOptions.array.push(cmd);
        parseOptions.default[cmd] = [];
      }
      parseOptions.alias[cmd] = aliases;
      parseOptions.demand[cmd] = true;
    });
    parsed.optional.forEach((o) => {
      const [cmd, ...aliases] = o.cmd;
      if (o.variadic) {
        parseOptions.array.push(cmd);
        parseOptions.default[cmd] = [];
      }
      parseOptions.alias[cmd] = aliases;
    });
    return parseOptions;
  }
  postProcessPositionals(argv, positionalMap, parseOptions, yargs) {
    const options = Object.assign({}, yargs.getOptions());
    options.default = Object.assign(parseOptions.default, options.default);
    for (const key of Object.keys(parseOptions.alias)) {
      options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]);
    }
    options.array = options.array.concat(parseOptions.array);
    options.config = {};
    const unparsed = [];
    Object.keys(positionalMap).forEach((key) => {
      positionalMap[key].map((value) => {
        if (options.configuration["unknown-options-as-args"])
          options.key[key] = true;
        unparsed.push(`--${key}`);
        unparsed.push(value);
      });
    });
    if (!unparsed.length)
      return;
    const config2 = Object.assign({}, options.configuration, {
      "populate--": false
    });
    const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, {
      configuration: config2
    }));
    if (parsed.error) {
      yargs.getInternalMethods().getUsageInstance().fail(parsed.error.message, parsed.error);
    } else {
      const positionalKeys = Object.keys(positionalMap);
      Object.keys(positionalMap).forEach((key) => {
        positionalKeys.push(...parsed.aliases[key]);
      });
      Object.keys(parsed.argv).forEach((key) => {
        if (positionalKeys.includes(key)) {
          if (!positionalMap[key])
            positionalMap[key] = parsed.argv[key];
          if (!this.isInConfigs(yargs, key) && !this.isDefaulted(yargs, key) && Object.prototype.hasOwnProperty.call(argv, key) && Object.prototype.hasOwnProperty.call(parsed.argv, key) && (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) {
            argv[key] = [].concat(argv[key], parsed.argv[key]);
          } else {
            argv[key] = parsed.argv[key];
          }
        }
      });
    }
  }
  isDefaulted(yargs, key) {
    const { default: defaults } = yargs.getOptions();
    return Object.prototype.hasOwnProperty.call(defaults, key) || Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key));
  }
  isInConfigs(yargs, key) {
    const { configObjects } = yargs.getOptions();
    return configObjects.some((c) => Object.prototype.hasOwnProperty.call(c, key)) || configObjects.some((c) => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)));
  }
  runDefaultBuilderOn(yargs) {
    if (!this.defaultCommand)
      return;
    if (this.shouldUpdateUsage(yargs)) {
      const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) ? this.defaultCommand.original : this.defaultCommand.original.replace(/^[^[\]<>]*/, "$0 ");
      yargs.getInternalMethods().getUsageInstance().usage(commandString, this.defaultCommand.description);
    }
    const builder = this.defaultCommand.builder;
    if (isCommandBuilderCallback(builder)) {
      return builder(yargs, true);
    } else if (!isCommandBuilderDefinition(builder)) {
      Object.keys(builder).forEach((key) => {
        yargs.option(key, builder[key]);
      });
    }
    return void 0;
  }
  moduleName(obj) {
    const mod = whichModule(obj);
    if (!mod)
      throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`);
    return this.commandFromFilename(mod.filename);
  }
  commandFromFilename(filename) {
    return this.shim.path.basename(filename, this.shim.path.extname(filename));
  }
  extractDesc({ describe: describe2, description, desc }) {
    for (const test of [describe2, description, desc]) {
      if (typeof test === "string" || test === false)
        return test;
      assertNotStrictEqual(test, true, this.shim);
    }
    return false;
  }
  freeze() {
    this.frozens.push({
      handlers: this.handlers,
      aliasMap: this.aliasMap,
      defaultCommand: this.defaultCommand
    });
  }
  unfreeze() {
    const frozen = this.frozens.pop();
    assertNotStrictEqual(frozen, void 0, this.shim);
    ({
      handlers: this.handlers,
      aliasMap: this.aliasMap,
      defaultCommand: this.defaultCommand
    } = frozen);
  }
  reset() {
    this.handlers = {};
    this.aliasMap = {};
    this.defaultCommand = void 0;
    this.requireCache = /* @__PURE__ */ new Set();
    return this;
  }
};
function command(usage2, validation2, globalMiddleware, shim3) {
  return new CommandInstance(usage2, validation2, globalMiddleware, shim3);
}
function isCommandBuilderDefinition(builder) {
  return typeof builder === "object" && !!builder.builder && typeof builder.handler === "function";
}
function isCommandAndAliases(cmd) {
  return cmd.every((c) => typeof c === "string");
}
function isCommandBuilderCallback(builder) {
  return typeof builder === "function";
}
function isCommandBuilderOptionDefinitions(builder) {
  return typeof builder === "object";
}
function isCommandHandlerDefinition(cmd) {
  return typeof cmd === "object" && !Array.isArray(cmd);
}

// node_modules/yargs/build/lib/utils/obj-filter.js
function objFilter(original = {}, filter = () => true) {
  const obj = {};
  objectKeys(original).forEach((key) => {
    if (filter(key, original[key])) {
      obj[key] = original[key];
    }
  });
  return obj;
}

// node_modules/yargs/build/lib/utils/set-blocking.js
function setBlocking(blocking) {
  if (typeof process === "undefined")
    return;
  [process.stdout, process.stderr].forEach((_stream) => {
    const stream = _stream;
    if (stream._handle && stream.isTTY && typeof stream._handle.setBlocking === "function") {
      stream._handle.setBlocking(blocking);
    }
  });
}

// node_modules/yargs/build/lib/usage.js
function isBoolean(fail) {
  return typeof fail === "boolean";
}
function usage(yargs, shim3) {
  const __ = shim3.y18n.__;
  const self = {};
  const fails = [];
  self.failFn = function failFn(f) {
    fails.push(f);
  };
  let failMessage = null;
  let globalFailMessage = null;
  let showHelpOnFail = true;
  self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) {
    const [enabled, message] = typeof arg1 === "string" ? [true, arg1] : [arg1, arg2];
    if (yargs.getInternalMethods().isGlobalContext()) {
      globalFailMessage = message;
    }
    failMessage = message;
    showHelpOnFail = enabled;
    return self;
  };
  let failureOutput = false;
  self.fail = function fail(msg, err) {
    const logger = yargs.getInternalMethods().getLoggerInstance();
    if (fails.length) {
      for (let i = fails.length - 1; i >= 0; --i) {
        const fail2 = fails[i];
        if (isBoolean(fail2)) {
          if (err)
            throw err;
          else if (msg)
            throw Error(msg);
        } else {
          fail2(msg, err, self);
        }
      }
    } else {
      if (yargs.getExitProcess())
        setBlocking(true);
      if (!failureOutput) {
        failureOutput = true;
        if (showHelpOnFail) {
          yargs.showHelp("error");
          logger.error();
        }
        if (msg || err)
          logger.error(msg || err);
        const globalOrCommandFailMessage = failMessage || globalFailMessage;
        if (globalOrCommandFailMessage) {
          if (msg || err)
            logger.error("");
          logger.error(globalOrCommandFailMessage);
        }
      }
      err = err || new YError(msg);
      if (yargs.getExitProcess()) {
        return yargs.exit(1);
      } else if (yargs.getInternalMethods().hasParseCallback()) {
        return yargs.exit(1, err);
      } else {
        throw err;
      }
    }
  };
  let usages = [];
  let usageDisabled = false;
  self.usage = (msg, description) => {
    if (msg === null) {
      usageDisabled = true;
      usages = [];
      return self;
    }
    usageDisabled = false;
    usages.push([msg, description || ""]);
    return self;
  };
  self.getUsage = () => {
    return usages;
  };
  self.getUsageDisabled = () => {
    return usageDisabled;
  };
  self.getPositionalGroupName = () => {
    return __("Positionals:");
  };
  let examples = [];
  self.example = (cmd, description) => {
    examples.push([cmd, description || ""]);
  };
  let commands = [];
  self.command = function command2(cmd, description, isDefault, aliases, deprecated = false) {
    if (isDefault) {
      commands = commands.map((cmdArray) => {
        cmdArray[2] = false;
        return cmdArray;
      });
    }
    commands.push([cmd, description || "", isDefault, aliases, deprecated]);
  };
  self.getCommands = () => commands;
  let descriptions = {};
  self.describe = function describe2(keyOrKeys, desc) {
    if (Array.isArray(keyOrKeys)) {
      keyOrKeys.forEach((k) => {
        self.describe(k, desc);
      });
    } else if (typeof keyOrKeys === "object") {
      Object.keys(keyOrKeys).forEach((k) => {
        self.describe(k, keyOrKeys[k]);
      });
    } else {
      descriptions[keyOrKeys] = desc;
    }
  };
  self.getDescriptions = () => descriptions;
  let epilogs = [];
  self.epilog = (msg) => {
    epilogs.push(msg);
  };
  let wrapSet = false;
  let wrap2;
  self.wrap = (cols) => {
    wrapSet = true;
    wrap2 = cols;
  };
  self.getWrap = () => {
    if (shim3.getEnv("YARGS_DISABLE_WRAP")) {
      return null;
    }
    if (!wrapSet) {
      wrap2 = windowWidth();
      wrapSet = true;
    }
    return wrap2;
  };
  const deferY18nLookupPrefix = "__yargsString__:";
  self.deferY18nLookup = (str) => deferY18nLookupPrefix + str;
  self.help = function help() {
    if (cachedHelpMessage)
      return cachedHelpMessage;
    normalizeAliases();
    const base$0 = yargs.customScriptName ? yargs.$0 : shim3.path.basename(yargs.$0);
    const demandedOptions = yargs.getDemandedOptions();
    const demandedCommands = yargs.getDemandedCommands();
    const deprecatedOptions = yargs.getDeprecatedOptions();
    const groups = yargs.getGroups();
    const options = yargs.getOptions();
    let keys = [];
    keys = keys.concat(Object.keys(descriptions));
    keys = keys.concat(Object.keys(demandedOptions));
    keys = keys.concat(Object.keys(demandedCommands));
    keys = keys.concat(Object.keys(options.default));
    keys = keys.filter(filterHiddenOptions);
    keys = Object.keys(keys.reduce((acc, key) => {
      if (key !== "_")
        acc[key] = true;
      return acc;
    }, {}));
    const theWrap = self.getWrap();
    const ui2 = shim3.cliui({
      width: theWrap,
      wrap: !!theWrap
    });
    if (!usageDisabled) {
      if (usages.length) {
        usages.forEach((usage2) => {
          ui2.div({ text: `${usage2[0].replace(/\$0/g, base$0)}` });
          if (usage2[1]) {
            ui2.div({ text: `${usage2[1]}`, padding: [1, 0, 0, 0] });
          }
        });
        ui2.div();
      } else if (commands.length) {
        let u = null;
        if (demandedCommands._) {
          u = `${base$0} <${__("command")}>
`;
        } else {
          u = `${base$0} [${__("command")}]
`;
        }
        ui2.div(`${u}`);
      }
    }
    if (commands.length > 1 || commands.length === 1 && !commands[0][2]) {
      ui2.div(__("Commands:"));
      const context = yargs.getInternalMethods().getContext();
      const parentCommands = context.commands.length ? `${context.commands.join(" ")} ` : "";
      if (yargs.getInternalMethods().getParserConfiguration()["sort-commands"] === true) {
        commands = commands.sort((a, b) => a[0].localeCompare(b[0]));
      }
      const prefix = base$0 ? `${base$0} ` : "";
      commands.forEach((command2) => {
        const commandString = `${prefix}${parentCommands}${command2[0].replace(/^\$0 ?/, "")}`;
        ui2.span({
          text: commandString,
          padding: [0, 2, 0, 2],
          width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4
        }, { text: command2[1] });
        const hints = [];
        if (command2[2])
          hints.push(`[${__("default")}]`);
        if (command2[3] && command2[3].length) {
          hints.push(`[${__("aliases:")} ${command2[3].join(", ")}]`);
        }
        if (command2[4]) {
          if (typeof command2[4] === "string") {
            hints.push(`[${__("deprecated: %s", command2[4])}]`);
          } else {
            hints.push(`[${__("deprecated")}]`);
          }
        }
        if (hints.length) {
          ui2.div({
            text: hints.join(" "),
            padding: [0, 0, 0, 2],
            align: "right"
          });
        } else {
          ui2.div();
        }
      });
      ui2.div();
    }
    const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []);
    keys = keys.filter((key) => !yargs.parsed.newAliases[key] && aliasKeys.every((alias) => (options.alias[alias] || []).indexOf(key) === -1));
    const defaultGroup = __("Options:");
    if (!groups[defaultGroup])
      groups[defaultGroup] = [];
    addUngroupedKeys(keys, options.alias, groups, defaultGroup);
    const isLongSwitch = (sw) => /^--/.test(getText(sw));
    const displayedGroups = Object.keys(groups).filter((groupName) => groups[groupName].length > 0).map((groupName) => {
      const normalizedKeys = groups[groupName].filter(filterHiddenOptions).map((key) => {
        if (aliasKeys.includes(key))
          return key;
        for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== void 0; i++) {
          if ((options.alias[aliasKey] || []).includes(key))
            return aliasKey;
        }
        return key;
      });
      return { groupName, normalizedKeys };
    }).filter(({ normalizedKeys }) => normalizedKeys.length > 0).map(({ groupName, normalizedKeys }) => {
      const switches = normalizedKeys.reduce((acc, key) => {
        acc[key] = [key].concat(options.alias[key] || []).map((sw) => {
          if (groupName === self.getPositionalGroupName())
            return sw;
          else {
            return (/^[0-9]$/.test(sw) ? options.boolean.includes(key) ? "-" : "--" : sw.length > 1 ? "--" : "-") + sw;
          }
        }).sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) ? 0 : isLongSwitch(sw1) ? 1 : -1).join(", ");
        return acc;
      }, {});
      return { groupName, normalizedKeys, switches };
    });
    const shortSwitchesUsed = displayedGroups.filter(({ groupName }) => groupName !== self.getPositionalGroupName()).some(({ normalizedKeys, switches }) => !normalizedKeys.every((key) => isLongSwitch(switches[key])));
    if (shortSwitchesUsed) {
      displayedGroups.filter(({ groupName }) => groupName !== self.getPositionalGroupName()).forEach(({ normalizedKeys, switches }) => {
        normalizedKeys.forEach((key) => {
          if (isLongSwitch(switches[key])) {
            switches[key] = addIndentation(switches[key], "-x, ".length);
          }
        });
      });
    }
    displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => {
      ui2.div(groupName);
      normalizedKeys.forEach((key) => {
        const kswitch = switches[key];
        let desc = descriptions[key] || "";
        let type = null;
        if (desc.includes(deferY18nLookupPrefix))
          desc = __(desc.substring(deferY18nLookupPrefix.length));
        if (options.boolean.includes(key))
          type = `[${__("boolean")}]`;
        if (options.count.includes(key))
          type = `[${__("count")}]`;
        if (options.string.includes(key))
          type = `[${__("string")}]`;
        if (options.normalize.includes(key))
          type = `[${__("string")}]`;
        if (options.array.includes(key))
          type = `[${__("array")}]`;
        if (options.number.includes(key))
          type = `[${__("number")}]`;
        const deprecatedExtra = (deprecated) => typeof deprecated === "string" ? `[${__("deprecated: %s", deprecated)}]` : `[${__("deprecated")}]`;
        const extra = [
          key in deprecatedOptions ? deprecatedExtra(deprecatedOptions[key]) : null,
          type,
          key in demandedOptions ? `[${__("required")}]` : null,
          options.choices && options.choices[key] ? `[${__("choices:")} ${self.stringifiedValues(options.choices[key])}]` : null,
          defaultString(options.default[key], options.defaultDescription[key])
        ].filter(Boolean).join(" ");
        ui2.span({
          text: getText(kswitch),
          padding: [0, 2, 0, 2 + getIndentation(kswitch)],
          width: maxWidth(switches, theWrap) + 4
        }, desc);
        const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()["hide-types"] === true;
        if (extra && !shouldHideOptionExtras)
          ui2.div({ text: extra, padding: [0, 0, 0, 2], align: "right" });
        else
          ui2.div();
      });
      ui2.div();
    });
    if (examples.length) {
      ui2.div(__("Examples:"));
      examples.forEach((example) => {
        example[0] = example[0].replace(/\$0/g, base$0);
      });
      examples.forEach((example) => {
        if (example[1] === "") {
          ui2.div({
            text: example[0],
            padding: [0, 2, 0, 2]
          });
        } else {
          ui2.div({
            text: example[0],
            padding: [0, 2, 0, 2],
            width: maxWidth(examples, theWrap) + 4
          }, {
            text: example[1]
          });
        }
      });
      ui2.div();
    }
    if (epilogs.length > 0) {
      const e = epilogs.map((epilog) => epilog.replace(/\$0/g, base$0)).join("\n");
      ui2.div(`${e}
`);
    }
    return ui2.toString().replace(/\s*$/, "");
  };
  function maxWidth(table, theWrap, modifier) {
    let width = 0;
    if (!Array.isArray(table)) {
      table = Object.values(table).map((v) => [v]);
    }
    table.forEach((v) => {
      width = Math.max(shim3.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width);
    });
    if (theWrap)
      width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10));
    return width;
  }
  function normalizeAliases() {
    const demandedOptions = yargs.getDemandedOptions();
    const options = yargs.getOptions();
    (Object.keys(options.alias) || []).forEach((key) => {
      options.alias[key].forEach((alias) => {
        if (descriptions[alias])
          self.describe(key, descriptions[alias]);
        if (alias in demandedOptions)
          yargs.demandOption(key, demandedOptions[alias]);
        if (options.boolean.includes(alias))
          yargs.boolean(key);
        if (options.count.includes(alias))
          yargs.count(key);
        if (options.string.includes(alias))
          yargs.string(key);
        if (options.normalize.includes(alias))
          yargs.normalize(key);
        if (options.array.includes(alias))
          yargs.array(key);
        if (options.number.includes(alias))
          yargs.number(key);
      });
    });
  }
  let cachedHelpMessage;
  self.cacheHelpMessage = function() {
    cachedHelpMessage = this.help();
  };
  self.clearCachedHelpMessage = function() {
    cachedHelpMessage = void 0;
  };
  self.hasCachedHelpMessage = function() {
    return !!cachedHelpMessage;
  };
  function addUngroupedKeys(keys, aliases, groups, defaultGroup) {
    let groupedKeys = [];
    let toCheck = null;
    Object.keys(groups).forEach((group) => {
      groupedKeys = groupedKeys.concat(groups[group]);
    });
    keys.forEach((key) => {
      toCheck = [key].concat(aliases[key]);
      if (!toCheck.some((k) => groupedKeys.indexOf(k) !== -1)) {
        groups[defaultGroup].push(key);
      }
    });
    return groupedKeys;
  }
  function filterHiddenOptions(key) {
    return yargs.getOptions().hiddenOptions.indexOf(key) < 0 || yargs.parsed.argv[yargs.getOptions().showHiddenOpt];
  }
  self.showHelp = (level) => {
    const logger = yargs.getInternalMethods().getLoggerInstance();
    if (!level)
      level = "error";
    const emit = typeof level === "function" ? level : logger[level];
    emit(self.help());
  };
  self.functionDescription = (fn) => {
    const description = fn.name ? shim3.Parser.decamelize(fn.name, "-") : __("generated-value");
    return ["(", description, ")"].join("");
  };
  self.stringifiedValues = function stringifiedValues(values, separator) {
    let string3 = "";
    const sep = separator || ", ";
    const array2 = [].concat(values);
    if (!values || !array2.length)
      return string3;
    array2.forEach((value) => {
      if (string3.length)
        string3 += sep;
      string3 += JSON.stringify(value);
    });
    return string3;
  };
  function defaultString(value, defaultDescription) {
    let string3 = `[${__("default:")} `;
    if (value === void 0 && !defaultDescription)
      return null;
    if (defaultDescription) {
      string3 += defaultDescription;
    } else {
      switch (typeof value) {
        case "string":
          string3 += `"${value}"`;
          break;
        case "object":
          string3 += JSON.stringify(value);
          break;
        default:
          string3 += value;
      }
    }
    return `${string3}]`;
  }
  function windowWidth() {
    const maxWidth2 = 80;
    if (shim3.process.stdColumns) {
      return Math.min(maxWidth2, shim3.process.stdColumns);
    } else {
      return maxWidth2;
    }
  }
  let version2 = null;
  self.version = (ver) => {
    version2 = ver;
  };
  self.showVersion = (level) => {
    const logger = yargs.getInternalMethods().getLoggerInstance();
    if (!level)
      level = "error";
    const emit = typeof level === "function" ? level : logger[level];
    emit(version2);
  };
  self.reset = function reset(localLookup) {
    failMessage = null;
    failureOutput = false;
    usages = [];
    usageDisabled = false;
    epilogs = [];
    examples = [];
    commands = [];
    descriptions = objFilter(descriptions, (k) => !localLookup[k]);
    return self;
  };
  const frozens = [];
  self.freeze = function freeze() {
    frozens.push({
      failMessage,
      failureOutput,
      usages,
      usageDisabled,
      epilogs,
      examples,
      commands,
      descriptions
    });
  };
  self.unfreeze = function unfreeze(defaultCommand = false) {
    const frozen = frozens.pop();
    if (!frozen)
      return;
    if (defaultCommand) {
      descriptions = { ...frozen.descriptions, ...descriptions };
      commands = [...frozen.commands, ...commands];
      usages = [...frozen.usages, ...usages];
      examples = [...frozen.examples, ...examples];
      epilogs = [...frozen.epilogs, ...epilogs];
    } else {
      ({
        failMessage,
        failureOutput,
        usages,
        usageDisabled,
        epilogs,
        examples,
        commands,
        descriptions
      } = frozen);
    }
  };
  return self;
}
function isIndentedText(text) {
  return typeof text === "object";
}
function addIndentation(text, indent) {
  return isIndentedText(text) ? { text: text.text, indentation: text.indentation + indent } : { text, indentation: indent };
}
function getIndentation(text) {
  return isIndentedText(text) ? text.indentation : 0;
}
function getText(text) {
  return isIndentedText(text) ? text.text : text;
}

// node_modules/yargs/build/lib/completion-templates.js
var completionShTemplate = `###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc
#    or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.
#
_{{app_name}}_yargs_completions()
{
    local cur_word args type_list

    cur_word="\${COMP_WORDS[COMP_CWORD]}"
    args=("\${COMP_WORDS[@]}")

    # ask yargs to generate completions.
    type_list=$({{app_path}} --get-yargs-completions "\${args[@]}")

    COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) )

    # if no match was found, fall back to filename completion
    if [ \${#COMPREPLY[@]} -eq 0 ]; then
      COMPREPLY=()
    fi

    return 0
}
complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;
var completionZshTemplate = `#compdef {{app_name}}
###-begin-{{app_name}}-completions-###
#
# yargs command completion script
#
# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc
#    or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.
#
_{{app_name}}_yargs_completions()
{
  local reply
  local si=$IFS
  IFS=$'
' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}"))
  IFS=$si
  _describe 'values' reply
}
compdef _{{app_name}}_yargs_completions {{app_name}}
###-end-{{app_name}}-completions-###
`;

// node_modules/yargs/build/lib/completion.js
var Completion = class {
  constructor(yargs, usage2, command2, shim3) {
    var _a4, _b2, _c2;
    this.yargs = yargs;
    this.usage = usage2;
    this.command = command2;
    this.shim = shim3;
    this.completionKey = "get-yargs-completions";
    this.aliases = null;
    this.customCompletionFunction = null;
    this.indexAfterLastReset = 0;
    this.zshShell = (_c2 = ((_a4 = this.shim.getEnv("SHELL")) === null || _a4 === void 0 ? void 0 : _a4.includes("zsh")) || ((_b2 = this.shim.getEnv("ZSH_NAME")) === null || _b2 === void 0 ? void 0 : _b2.includes("zsh"))) !== null && _c2 !== void 0 ? _c2 : false;
  }
  defaultCompletion(args, argv, current, done) {
    const handlers = this.command.getCommandHandlers();
    for (let i = 0, ii = args.length; i < ii; ++i) {
      if (handlers[args[i]] && handlers[args[i]].builder) {
        const builder = handlers[args[i]].builder;
        if (isCommandBuilderCallback(builder)) {
          this.indexAfterLastReset = i + 1;
          const y = this.yargs.getInternalMethods().reset();
          builder(y, true);
          return y.argv;
        }
      }
    }
    const completions = [];
    this.commandCompletions(completions, args, current);
    this.optionCompletions(completions, args, argv, current);
    this.choicesFromOptionsCompletions(completions, args, argv, current);
    this.choicesFromPositionalsCompletions(completions, args, argv, current);
    done(null, completions);
  }
  commandCompletions(completions, args, current) {
    const parentCommands = this.yargs.getInternalMethods().getContext().commands;
    if (!current.match(/^-/) && parentCommands[parentCommands.length - 1] !== current && !this.previousArgHasChoices(args)) {
      this.usage.getCommands().forEach((usageCommand) => {
        const commandName = parseCommand(usageCommand[0]).cmd;
        if (args.indexOf(commandName) === -1) {
          if (!this.zshShell) {
            completions.push(commandName);
          } else {
            const desc = usageCommand[1] || "";
            completions.push(commandName.replace(/:/g, "\\:") + ":" + desc);
          }
        }
      });
    }
  }
  optionCompletions(completions, args, argv, current) {
    if ((current.match(/^-/) || current === "" && completions.length === 0) && !this.previousArgHasChoices(args)) {
      const options = this.yargs.getOptions();
      const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
      Object.keys(options.key).forEach((key) => {
        const negable = !!options.configuration["boolean-negation"] && options.boolean.includes(key);
        const isPositionalKey = positionalKeys.includes(key);
        if (!isPositionalKey && !options.hiddenOptions.includes(key) && !this.argsContainKey(args, key, negable)) {
          this.completeOptionKey(key, completions, current, negable && !!options.default[key]);
        }
      });
    }
  }
  choicesFromOptionsCompletions(completions, args, argv, current) {
    if (this.previousArgHasChoices(args)) {
      const choices = this.getPreviousArgChoices(args);
      if (choices && choices.length > 0) {
        completions.push(...choices.map((c) => c.replace(/:/g, "\\:")));
      }
    }
  }
  choicesFromPositionalsCompletions(completions, args, argv, current) {
    if (current === "" && completions.length > 0 && this.previousArgHasChoices(args)) {
      return;
    }
    const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || [];
    const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + 1);
    const positionalKey = positionalKeys[argv._.length - offset - 1];
    if (!positionalKey) {
      return;
    }
    const choices = this.yargs.getOptions().choices[positionalKey] || [];
    for (const choice of choices) {
      if (choice.startsWith(current)) {
        completions.push(choice.replace(/:/g, "\\:"));
      }
    }
  }
  getPreviousArgChoices(args) {
    if (args.length < 1)
      return;
    let previousArg = args[args.length - 1];
    let filter = "";
    if (!previousArg.startsWith("-") && args.length > 1) {
      filter = previousArg;
      previousArg = args[args.length - 2];
    }
    if (!previousArg.startsWith("-"))
      return;
    const previousArgKey = previousArg.replace(/^-+/, "");
    const options = this.yargs.getOptions();
    const possibleAliases = [
      previousArgKey,
      ...this.yargs.getAliases()[previousArgKey] || []
    ];
    let choices;
    for (const possibleAlias of possibleAliases) {
      if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && Array.isArray(options.choices[possibleAlias])) {
        choices = options.choices[possibleAlias];
        break;
      }
    }
    if (choices) {
      return choices.filter((choice) => !filter || choice.startsWith(filter));
    }
  }
  previousArgHasChoices(args) {
    const choices = this.getPreviousArgChoices(args);
    return choices !== void 0 && choices.length > 0;
  }
  argsContainKey(args, key, negable) {
    const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? "-" : "--") + s) !== -1;
    if (argsContains(key))
      return true;
    if (negable && argsContains(`no-${key}`))
      return true;
    if (this.aliases) {
      for (const alias of this.aliases[key]) {
        if (argsContains(alias))
          return true;
      }
    }
    return false;
  }
  completeOptionKey(key, completions, current, negable) {
    var _a4, _b2, _c2, _d;
    let keyWithDesc = key;
    if (this.zshShell) {
      const descs = this.usage.getDescriptions();
      const aliasKey = (_b2 = (_a4 = this === null || this === void 0 ? void 0 : this.aliases) === null || _a4 === void 0 ? void 0 : _a4[key]) === null || _b2 === void 0 ? void 0 : _b2.find((alias) => {
        const desc2 = descs[alias];
        return typeof desc2 === "string" && desc2.length > 0;
      });
      const descFromAlias = aliasKey ? descs[aliasKey] : void 0;
      const desc = (_d = (_c2 = descs[key]) !== null && _c2 !== void 0 ? _c2 : descFromAlias) !== null && _d !== void 0 ? _d : "";
      keyWithDesc = `${key.replace(/:/g, "\\:")}:${desc.replace("__yargsString__:", "").replace(/(\r\n|\n|\r)/gm, " ")}`;
    }
    const startsByTwoDashes = (s) => /^--/.test(s);
    const isShortOption = (s) => /^[^0-9]$/.test(s);
    const dashes = !startsByTwoDashes(current) && isShortOption(key) ? "-" : "--";
    completions.push(dashes + keyWithDesc);
    if (negable) {
      completions.push(dashes + "no-" + keyWithDesc);
    }
  }
  customCompletion(args, argv, current, done) {
    assertNotStrictEqual(this.customCompletionFunction, null, this.shim);
    if (isSyncCompletionFunction(this.customCompletionFunction)) {
      const result = this.customCompletionFunction(current, argv);
      if (isPromise(result)) {
        return result.then((list) => {
          this.shim.process.nextTick(() => {
            done(null, list);
          });
        }).catch((err) => {
          this.shim.process.nextTick(() => {
            done(err, void 0);
          });
        });
      }
      return done(null, result);
    } else if (isFallbackCompletionFunction(this.customCompletionFunction)) {
      return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), (completions) => {
        done(null, completions);
      });
    } else {
      return this.customCompletionFunction(current, argv, (completions) => {
        done(null, completions);
      });
    }
  }
  getCompletion(args, done) {
    const current = args.length ? args[args.length - 1] : "";
    const argv = this.yargs.parse(args, true);
    const completionFunction = this.customCompletionFunction ? (argv2) => this.customCompletion(args, argv2, current, done) : (argv2) => this.defaultCompletion(args, argv2, current, done);
    return isPromise(argv) ? argv.then(completionFunction) : completionFunction(argv);
  }
  generateCompletionScript($0, cmd) {
    let script = this.zshShell ? completionZshTemplate : completionShTemplate;
    const name = this.shim.path.basename($0);
    if ($0.match(/\.js$/))
      $0 = `./${$0}`;
    script = script.replace(/{{app_name}}/g, name);
    script = script.replace(/{{completion_command}}/g, cmd);
    return script.replace(/{{app_path}}/g, $0);
  }
  registerFunction(fn) {
    this.customCompletionFunction = fn;
  }
  setParsed(parsed) {
    this.aliases = parsed.aliases;
  }
};
function completion(yargs, usage2, command2, shim3) {
  return new Completion(yargs, usage2, command2, shim3);
}
function isSyncCompletionFunction(completionFunction) {
  return completionFunction.length < 3;
}
function isFallbackCompletionFunction(completionFunction) {
  return completionFunction.length > 3;
}

// node_modules/yargs/build/lib/utils/levenshtein.js
function levenshtein(a, b) {
  if (a.length === 0)
    return b.length;
  if (b.length === 0)
    return a.length;
  const matrix = [];
  let i;
  for (i = 0; i <= b.length; i++) {
    matrix[i] = [i];
  }
  let j;
  for (j = 0; j <= a.length; j++) {
    matrix[0][j] = j;
  }
  for (i = 1; i <= b.length; i++) {
    for (j = 1; j <= a.length; j++) {
      if (b.charAt(i - 1) === a.charAt(j - 1)) {
        matrix[i][j] = matrix[i - 1][j - 1];
      } else {
        if (i > 1 && j > 1 && b.charAt(i - 2) === a.charAt(j - 1) && b.charAt(i - 1) === a.charAt(j - 2)) {
          matrix[i][j] = matrix[i - 2][j - 2] + 1;
        } else {
          matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1));
        }
      }
    }
  }
  return matrix[b.length][a.length];
}

// node_modules/yargs/build/lib/validation.js
var specialKeys = ["$0", "--", "_"];
function validation(yargs, usage2, shim3) {
  const __ = shim3.y18n.__;
  const __n = shim3.y18n.__n;
  const self = {};
  self.nonOptionCount = function nonOptionCount(argv) {
    const demandedCommands = yargs.getDemandedCommands();
    const positionalCount = argv._.length + (argv["--"] ? argv["--"].length : 0);
    const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length;
    if (demandedCommands._ && (_s < demandedCommands._.min || _s > demandedCommands._.max)) {
      if (_s < demandedCommands._.min) {
        if (demandedCommands._.minMsg !== void 0) {
          usage2.fail(demandedCommands._.minMsg ? demandedCommands._.minMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.min.toString()) : null);
        } else {
          usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", _s, _s.toString(), demandedCommands._.min.toString()));
        }
      } else if (_s > demandedCommands._.max) {
        if (demandedCommands._.maxMsg !== void 0) {
          usage2.fail(demandedCommands._.maxMsg ? demandedCommands._.maxMsg.replace(/\$0/g, _s.toString()).replace(/\$1/, demandedCommands._.max.toString()) : null);
        } else {
          usage2.fail(__n("Too many non-option arguments: got %s, maximum of %s", "Too many non-option arguments: got %s, maximum of %s", _s, _s.toString(), demandedCommands._.max.toString()));
        }
      }
    }
  };
  self.positionalCount = function positionalCount(required2, observed) {
    if (observed < required2) {
      usage2.fail(__n("Not enough non-option arguments: got %s, need at least %s", "Not enough non-option arguments: got %s, need at least %s", observed, observed + "", required2 + ""));
    }
  };
  self.requiredArguments = function requiredArguments(argv, demandedOptions) {
    let missing = null;
    for (const key of Object.keys(demandedOptions)) {
      if (!Object.prototype.hasOwnProperty.call(argv, key) || typeof argv[key] === "undefined") {
        missing = missing || {};
        missing[key] = demandedOptions[key];
      }
    }
    if (missing) {
      const customMsgs = [];
      for (const key of Object.keys(missing)) {
        const msg = missing[key];
        if (msg && customMsgs.indexOf(msg) < 0) {
          customMsgs.push(msg);
        }
      }
      const customMsg = customMsgs.length ? `
${customMsgs.join("\n")}` : "";
      usage2.fail(__n("Missing required argument: %s", "Missing required arguments: %s", Object.keys(missing).length, Object.keys(missing).join(", ") + customMsg));
    }
  };
  self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) {
    var _a4;
    const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
    const unknown2 = [];
    const currentContext = yargs.getInternalMethods().getContext();
    Object.keys(argv).forEach((key) => {
      if (!specialKeys.includes(key) && !Object.prototype.hasOwnProperty.call(positionalMap, key) && !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && !self.isValidAndSomeAliasIsNotNew(key, aliases)) {
        unknown2.push(key);
      }
    });
    if (checkPositionals && (currentContext.commands.length > 0 || commandKeys.length > 0 || isDefaultCommand)) {
      argv._.slice(currentContext.commands.length).forEach((key) => {
        if (!commandKeys.includes("" + key)) {
          unknown2.push("" + key);
        }
      });
    }
    if (checkPositionals) {
      const demandedCommands = yargs.getDemandedCommands();
      const maxNonOptDemanded = ((_a4 = demandedCommands._) === null || _a4 === void 0 ? void 0 : _a4.max) || 0;
      const expected = currentContext.commands.length + maxNonOptDemanded;
      if (expected < argv._.length) {
        argv._.slice(expected).forEach((key) => {
          key = String(key);
          if (!currentContext.commands.includes(key) && !unknown2.includes(key)) {
            unknown2.push(key);
          }
        });
      }
    }
    if (unknown2.length) {
      usage2.fail(__n("Unknown argument: %s", "Unknown arguments: %s", unknown2.length, unknown2.map((s) => s.trim() ? s : `"${s}"`).join(", ")));
    }
  };
  self.unknownCommands = function unknownCommands(argv) {
    const commandKeys = yargs.getInternalMethods().getCommandInstance().getCommands();
    const unknown2 = [];
    const currentContext = yargs.getInternalMethods().getContext();
    if (currentContext.commands.length > 0 || commandKeys.length > 0) {
      argv._.slice(currentContext.commands.length).forEach((key) => {
        if (!commandKeys.includes("" + key)) {
          unknown2.push("" + key);
        }
      });
    }
    if (unknown2.length > 0) {
      usage2.fail(__n("Unknown command: %s", "Unknown commands: %s", unknown2.length, unknown2.join(", ")));
      return true;
    } else {
      return false;
    }
  };
  self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) {
    if (!Object.prototype.hasOwnProperty.call(aliases, key)) {
      return false;
    }
    const newAliases = yargs.parsed.newAliases;
    return [key, ...aliases[key]].some((a) => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]);
  };
  self.limitedChoices = function limitedChoices(argv) {
    const options = yargs.getOptions();
    const invalid = {};
    if (!Object.keys(options.choices).length)
      return;
    Object.keys(argv).forEach((key) => {
      if (specialKeys.indexOf(key) === -1 && Object.prototype.hasOwnProperty.call(options.choices, key)) {
        [].concat(argv[key]).forEach((value) => {
          if (options.choices[key].indexOf(value) === -1 && value !== void 0) {
            invalid[key] = (invalid[key] || []).concat(value);
          }
        });
      }
    });
    const invalidKeys = Object.keys(invalid);
    if (!invalidKeys.length)
      return;
    let msg = __("Invalid values:");
    invalidKeys.forEach((key) => {
      msg += `
  ${__("Argument: %s, Given: %s, Choices: %s", key, usage2.stringifiedValues(invalid[key]), usage2.stringifiedValues(options.choices[key]))}`;
    });
    usage2.fail(msg);
  };
  let implied = {};
  self.implies = function implies(key, value) {
    argsert("<string|object> [array|number|string]", [key, value], arguments.length);
    if (typeof key === "object") {
      Object.keys(key).forEach((k) => {
        self.implies(k, key[k]);
      });
    } else {
      yargs.global(key);
      if (!implied[key]) {
        implied[key] = [];
      }
      if (Array.isArray(value)) {
        value.forEach((i) => self.implies(key, i));
      } else {
        assertNotStrictEqual(value, void 0, shim3);
        implied[key].push(value);
      }
    }
  };
  self.getImplied = function getImplied() {
    return implied;
  };
  function keyExists(argv, val) {
    const num = Number(val);
    val = isNaN(num) ? val : num;
    if (typeof val === "number") {
      val = argv._.length >= val;
    } else if (val.match(/^--no-.+/)) {
      val = val.match(/^--no-(.+)/)[1];
      val = !Object.prototype.hasOwnProperty.call(argv, val);
    } else {
      val = Object.prototype.hasOwnProperty.call(argv, val);
    }
    return val;
  }
  self.implications = function implications(argv) {
    const implyFail = [];
    Object.keys(implied).forEach((key) => {
      const origKey = key;
      (implied[key] || []).forEach((value) => {
        let key2 = origKey;
        const origValue = value;
        key2 = keyExists(argv, key2);
        value = keyExists(argv, value);
        if (key2 && !value) {
          implyFail.push(` ${origKey} -> ${origValue}`);
        }
      });
    });
    if (implyFail.length) {
      let msg = `${__("Implications failed:")}
`;
      implyFail.forEach((value) => {
        msg += value;
      });
      usage2.fail(msg);
    }
  };
  let conflicting = {};
  self.conflicts = function conflicts(key, value) {
    argsert("<string|object> [array|string]", [key, value], arguments.length);
    if (typeof key === "object") {
      Object.keys(key).forEach((k) => {
        self.conflicts(k, key[k]);
      });
    } else {
      yargs.global(key);
      if (!conflicting[key]) {
        conflicting[key] = [];
      }
      if (Array.isArray(value)) {
        value.forEach((i) => self.conflicts(key, i));
      } else {
        conflicting[key].push(value);
      }
    }
  };
  self.getConflicting = () => conflicting;
  self.conflicting = function conflictingFn(argv) {
    Object.keys(argv).forEach((key) => {
      if (conflicting[key]) {
        conflicting[key].forEach((value) => {
          if (value && argv[key] !== void 0 && argv[value] !== void 0) {
            usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
          }
        });
      }
    });
    if (yargs.getInternalMethods().getParserConfiguration()["strip-dashed"]) {
      Object.keys(conflicting).forEach((key) => {
        conflicting[key].forEach((value) => {
          if (value && argv[shim3.Parser.camelCase(key)] !== void 0 && argv[shim3.Parser.camelCase(value)] !== void 0) {
            usage2.fail(__("Arguments %s and %s are mutually exclusive", key, value));
          }
        });
      });
    }
  };
  self.recommendCommands = function recommendCommands(cmd, potentialCommands) {
    const threshold = 3;
    potentialCommands = potentialCommands.sort((a, b) => b.length - a.length);
    let recommended = null;
    let bestDistance = Infinity;
    for (let i = 0, candidate; (candidate = potentialCommands[i]) !== void 0; i++) {
      const d = levenshtein(cmd, candidate);
      if (d <= threshold && d < bestDistance) {
        bestDistance = d;
        recommended = candidate;
      }
    }
    if (recommended)
      usage2.fail(__("Did you mean %s?", recommended));
  };
  self.reset = function reset(localLookup) {
    implied = objFilter(implied, (k) => !localLookup[k]);
    conflicting = objFilter(conflicting, (k) => !localLookup[k]);
    return self;
  };
  const frozens = [];
  self.freeze = function freeze() {
    frozens.push({
      implied,
      conflicting
    });
  };
  self.unfreeze = function unfreeze() {
    const frozen = frozens.pop();
    assertNotStrictEqual(frozen, void 0, shim3);
    ({ implied, conflicting } = frozen);
  };
  return self;
}

// node_modules/yargs/build/lib/utils/apply-extends.js
var previouslyVisitedConfigs = [];
var shim2;
function applyExtends(config2, cwd, mergeExtends, _shim) {
  shim2 = _shim;
  let defaultConfig = {};
  if (Object.prototype.hasOwnProperty.call(config2, "extends")) {
    if (typeof config2.extends !== "string")
      return defaultConfig;
    const isPath = /\.json|\..*rc$/.test(config2.extends);
    let pathToDefault = null;
    if (!isPath) {
      try {
        pathToDefault = __require.resolve(config2.extends);
      } catch (_err) {
        return config2;
      }
    } else {
      pathToDefault = getPathToDefaultConfig(cwd, config2.extends);
    }
    checkForCircularExtends(pathToDefault);
    previouslyVisitedConfigs.push(pathToDefault);
    defaultConfig = isPath ? JSON.parse(shim2.readFileSync(pathToDefault, "utf8")) : __require(config2.extends);
    delete config2.extends;
    defaultConfig = applyExtends(defaultConfig, shim2.path.dirname(pathToDefault), mergeExtends, shim2);
  }
  previouslyVisitedConfigs = [];
  return mergeExtends ? mergeDeep(defaultConfig, config2) : Object.assign({}, defaultConfig, config2);
}
function checkForCircularExtends(cfgPath) {
  if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) {
    throw new YError(`Circular extended configurations: '${cfgPath}'.`);
  }
}
function getPathToDefaultConfig(cwd, pathToExtend) {
  return shim2.path.resolve(cwd, pathToExtend);
}
function mergeDeep(config1, config2) {
  const target = {};
  function isObject2(obj) {
    return obj && typeof obj === "object" && !Array.isArray(obj);
  }
  Object.assign(target, config1);
  for (const key of Object.keys(config2)) {
    if (isObject2(config2[key]) && isObject2(target[key])) {
      target[key] = mergeDeep(config1[key], config2[key]);
    } else {
      target[key] = config2[key];
    }
  }
  return target;
}

// node_modules/yargs/build/lib/yargs-factory.js
var __classPrivateFieldSet = function(receiver, state, value, kind, f) {
  if (kind === "m") throw new TypeError("Private method is not writable");
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it");
  return kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value;
};
var __classPrivateFieldGet = function(receiver, state, kind, f) {
  if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var _YargsInstance_command;
var _YargsInstance_cwd;
var _YargsInstance_context;
var _YargsInstance_completion;
var _YargsInstance_completionCommand;
var _YargsInstance_defaultShowHiddenOpt;
var _YargsInstance_exitError;
var _YargsInstance_detectLocale;
var _YargsInstance_emittedWarnings;
var _YargsInstance_exitProcess;
var _YargsInstance_frozens;
var _YargsInstance_globalMiddleware;
var _YargsInstance_groups;
var _YargsInstance_hasOutput;
var _YargsInstance_helpOpt;
var _YargsInstance_isGlobalContext;
var _YargsInstance_logger;
var _YargsInstance_output;
var _YargsInstance_options;
var _YargsInstance_parentRequire;
var _YargsInstance_parserConfig;
var _YargsInstance_parseFn;
var _YargsInstance_parseContext;
var _YargsInstance_pkgs;
var _YargsInstance_preservedGroups;
var _YargsInstance_processArgs;
var _YargsInstance_recommendCommands;
var _YargsInstance_shim;
var _YargsInstance_strict;
var _YargsInstance_strictCommands;
var _YargsInstance_strictOptions;
var _YargsInstance_usage;
var _YargsInstance_usageConfig;
var _YargsInstance_versionOpt;
var _YargsInstance_validation;
function YargsFactory(_shim) {
  return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => {
    const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim);
    Object.defineProperty(yargs, "argv", {
      get: () => {
        return yargs.parse();
      },
      enumerable: true
    });
    yargs.help();
    yargs.version();
    return yargs;
  };
}
var kCopyDoubleDash = Symbol("copyDoubleDash");
var kCreateLogger = Symbol("copyDoubleDash");
var kDeleteFromParserHintObject = Symbol("deleteFromParserHintObject");
var kEmitWarning = Symbol("emitWarning");
var kFreeze = Symbol("freeze");
var kGetDollarZero = Symbol("getDollarZero");
var kGetParserConfiguration = Symbol("getParserConfiguration");
var kGetUsageConfiguration = Symbol("getUsageConfiguration");
var kGuessLocale = Symbol("guessLocale");
var kGuessVersion = Symbol("guessVersion");
var kParsePositionalNumbers = Symbol("parsePositionalNumbers");
var kPkgUp = Symbol("pkgUp");
var kPopulateParserHintArray = Symbol("populateParserHintArray");
var kPopulateParserHintSingleValueDictionary = Symbol("populateParserHintSingleValueDictionary");
var kPopulateParserHintArrayDictionary = Symbol("populateParserHintArrayDictionary");
var kPopulateParserHintDictionary = Symbol("populateParserHintDictionary");
var kSanitizeKey = Symbol("sanitizeKey");
var kSetKey = Symbol("setKey");
var kUnfreeze = Symbol("unfreeze");
var kValidateAsync = Symbol("validateAsync");
var kGetCommandInstance = Symbol("getCommandInstance");
var kGetContext = Symbol("getContext");
var kGetHasOutput = Symbol("getHasOutput");
var kGetLoggerInstance = Symbol("getLoggerInstance");
var kGetParseContext = Symbol("getParseContext");
var kGetUsageInstance = Symbol("getUsageInstance");
var kGetValidationInstance = Symbol("getValidationInstance");
var kHasParseCallback = Symbol("hasParseCallback");
var kIsGlobalContext = Symbol("isGlobalContext");
var kPostProcess = Symbol("postProcess");
var kRebase = Symbol("rebase");
var kReset = Symbol("reset");
var kRunYargsParserAndExecuteCommands = Symbol("runYargsParserAndExecuteCommands");
var kRunValidation = Symbol("runValidation");
var kSetHasOutput = Symbol("setHasOutput");
var kTrackManuallySetKeys = Symbol("kTrackManuallySetKeys");
var YargsInstance = class {
  constructor(processArgs = [], cwd, parentRequire, shim3) {
    this.customScriptName = false;
    this.parsed = false;
    _YargsInstance_command.set(this, void 0);
    _YargsInstance_cwd.set(this, void 0);
    _YargsInstance_context.set(this, { commands: [], fullCommands: [] });
    _YargsInstance_completion.set(this, null);
    _YargsInstance_completionCommand.set(this, null);
    _YargsInstance_defaultShowHiddenOpt.set(this, "show-hidden");
    _YargsInstance_exitError.set(this, null);
    _YargsInstance_detectLocale.set(this, true);
    _YargsInstance_emittedWarnings.set(this, {});
    _YargsInstance_exitProcess.set(this, true);
    _YargsInstance_frozens.set(this, []);
    _YargsInstance_globalMiddleware.set(this, void 0);
    _YargsInstance_groups.set(this, {});
    _YargsInstance_hasOutput.set(this, false);
    _YargsInstance_helpOpt.set(this, null);
    _YargsInstance_isGlobalContext.set(this, true);
    _YargsInstance_logger.set(this, void 0);
    _YargsInstance_output.set(this, "");
    _YargsInstance_options.set(this, void 0);
    _YargsInstance_parentRequire.set(this, void 0);
    _YargsInstance_parserConfig.set(this, {});
    _YargsInstance_parseFn.set(this, null);
    _YargsInstance_parseContext.set(this, null);
    _YargsInstance_pkgs.set(this, {});
    _YargsInstance_preservedGroups.set(this, {});
    _YargsInstance_processArgs.set(this, void 0);
    _YargsInstance_recommendCommands.set(this, false);
    _YargsInstance_shim.set(this, void 0);
    _YargsInstance_strict.set(this, false);
    _YargsInstance_strictCommands.set(this, false);
    _YargsInstance_strictOptions.set(this, false);
    _YargsInstance_usage.set(this, void 0);
    _YargsInstance_usageConfig.set(this, {});
    _YargsInstance_versionOpt.set(this, null);
    _YargsInstance_validation.set(this, void 0);
    __classPrivateFieldSet(this, _YargsInstance_shim, shim3, "f");
    __classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f");
    __classPrivateFieldSet(this, _YargsInstance_cwd, cwd, "f");
    __classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f");
    __classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f");
    this.$0 = this[kGetDollarZero]();
    this[kReset]();
    __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f");
    __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f");
    __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f");
    __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f");
    __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f");
    __classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f");
  }
  addHelpOpt(opt, msg) {
    const defaultHelpOpt = "help";
    argsert("[string|boolean] [string]", [opt, msg], arguments.length);
    if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) {
      this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"));
      __classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f");
    }
    if (opt === false && msg === void 0)
      return this;
    __classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === "string" ? opt : defaultHelpOpt, "f");
    this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"));
    this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup("Show help"));
    return this;
  }
  help(opt, msg) {
    return this.addHelpOpt(opt, msg);
  }
  addShowHiddenOpt(opt, msg) {
    argsert("[string|boolean] [string]", [opt, msg], arguments.length);
    if (opt === false && msg === void 0)
      return this;
    const showHiddenOpt = typeof opt === "string" ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f");
    this.boolean(showHiddenOpt);
    this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup("Show hidden options"));
    __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt;
    return this;
  }
  showHidden(opt, msg) {
    return this.addShowHiddenOpt(opt, msg);
  }
  alias(key, value) {
    argsert("<object|string|array> [string|array]", [key, value], arguments.length);
    this[kPopulateParserHintArrayDictionary](this.alias.bind(this), "alias", key, value);
    return this;
  }
  array(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("array", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  boolean(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("boolean", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  check(f, global) {
    argsert("<function> [boolean]", [f, global], arguments.length);
    this.middleware((argv, _yargs) => {
      return maybeAsyncResult(() => {
        return f(argv, _yargs.getOptions());
      }, (result) => {
        if (!result) {
          __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__("Argument check failed: %s", f.toString()));
        } else if (typeof result === "string" || result instanceof Error) {
          __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(result.toString(), result);
        }
        return argv;
      }, (err) => {
        __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err);
        return argv;
      });
    }, false, global);
    return this;
  }
  choices(key, value) {
    argsert("<object|string|array> [string|array]", [key, value], arguments.length);
    this[kPopulateParserHintArrayDictionary](this.choices.bind(this), "choices", key, value);
    return this;
  }
  coerce(keys, value) {
    argsert("<object|string|array> [function]", [keys, value], arguments.length);
    if (Array.isArray(keys)) {
      if (!value) {
        throw new YError("coerce callback must be provided");
      }
      for (const key of keys) {
        this.coerce(key, value);
      }
      return this;
    } else if (typeof keys === "object") {
      for (const key of Object.keys(keys)) {
        this.coerce(key, keys[key]);
      }
      return this;
    }
    if (!value) {
      throw new YError("coerce callback must be provided");
    }
    __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true;
    __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => {
      let aliases;
      const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys);
      if (!shouldCoerce) {
        return argv;
      }
      return maybeAsyncResult(() => {
        aliases = yargs.getAliases();
        return value(argv[keys]);
      }, (result) => {
        argv[keys] = result;
        const stripAliased = yargs.getInternalMethods().getParserConfiguration()["strip-aliased"];
        if (aliases[keys] && stripAliased !== true) {
          for (const alias of aliases[keys]) {
            argv[alias] = result;
          }
        }
        return argv;
      }, (err) => {
        throw new YError(err.message);
      });
    }, keys);
    return this;
  }
  conflicts(key1, key2) {
    argsert("<string|object> [string|array]", [key1, key2], arguments.length);
    __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicts(key1, key2);
    return this;
  }
  config(key = "config", msg, parseFn) {
    argsert("[object|string] [string|function] [function]", [key, msg, parseFn], arguments.length);
    if (typeof key === "object" && !Array.isArray(key)) {
      key = applyExtends(key, __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
      __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(key);
      return this;
    }
    if (typeof msg === "function") {
      parseFn = msg;
      msg = void 0;
    }
    this.describe(key, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup("Path to JSON config file"));
    (Array.isArray(key) ? key : [key]).forEach((k) => {
      __classPrivateFieldGet(this, _YargsInstance_options, "f").config[k] = parseFn || true;
    });
    return this;
  }
  completion(cmd, desc, fn) {
    argsert("[string] [string|boolean|function] [function]", [cmd, desc, fn], arguments.length);
    if (typeof desc === "function") {
      fn = desc;
      desc = void 0;
    }
    __classPrivateFieldSet(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || "completion", "f");
    if (!desc && desc !== false) {
      desc = "generate completion script";
    }
    this.command(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), desc);
    if (fn)
      __classPrivateFieldGet(this, _YargsInstance_completion, "f").registerFunction(fn);
    return this;
  }
  command(cmd, description, builder, handler, middlewares, deprecated) {
    argsert("<string|array|object> [string|boolean] [function|object] [function] [array] [boolean|string]", [cmd, description, builder, handler, middlewares, deprecated], arguments.length);
    __classPrivateFieldGet(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated);
    return this;
  }
  commands(cmd, description, builder, handler, middlewares, deprecated) {
    return this.command(cmd, description, builder, handler, middlewares, deprecated);
  }
  commandDir(dir, opts) {
    argsert("<string> [object]", [dir, opts], arguments.length);
    const req = __classPrivateFieldGet(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").require;
    __classPrivateFieldGet(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet(this, _YargsInstance_shim, "f").getCallerFile(), opts);
    return this;
  }
  count(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("count", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  default(key, value, defaultDescription) {
    argsert("<object|string|array> [*] [string]", [key, value, defaultDescription], arguments.length);
    if (defaultDescription) {
      assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
      __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription;
    }
    if (typeof value === "function") {
      assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
      if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key])
        __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = __classPrivateFieldGet(this, _YargsInstance_usage, "f").functionDescription(value);
      value = value.call();
    }
    this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), "default", key, value);
    return this;
  }
  defaults(key, value, defaultDescription) {
    return this.default(key, value, defaultDescription);
  }
  demandCommand(min = 1, max, minMsg, maxMsg) {
    argsert("[number] [number|string] [string|null|undefined] [string|null|undefined]", [min, max, minMsg, maxMsg], arguments.length);
    if (typeof max !== "number") {
      minMsg = max;
      max = Infinity;
    }
    this.global("_", false);
    __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands._ = {
      min,
      max,
      minMsg,
      maxMsg
    };
    return this;
  }
  demand(keys, max, msg) {
    if (Array.isArray(max)) {
      max.forEach((key) => {
        assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
        this.demandOption(key, msg);
      });
      max = Infinity;
    } else if (typeof max !== "number") {
      msg = max;
      max = Infinity;
    }
    if (typeof keys === "number") {
      assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
      this.demandCommand(keys, max, msg, msg);
    } else if (Array.isArray(keys)) {
      keys.forEach((key) => {
        assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
        this.demandOption(key, msg);
      });
    } else {
      if (typeof msg === "string") {
        this.demandOption(keys, msg);
      } else if (msg === true || typeof msg === "undefined") {
        this.demandOption(keys);
      }
    }
    return this;
  }
  demandOption(keys, msg) {
    argsert("<object|string|array> [string]", [keys, msg], arguments.length);
    this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), "demandedOptions", keys, msg);
    return this;
  }
  deprecateOption(option, message) {
    argsert("<string> [string|boolean]", [option, message], arguments.length);
    __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions[option] = message;
    return this;
  }
  describe(keys, description) {
    argsert("<object|string|array> [string]", [keys, description], arguments.length);
    this[kSetKey](keys, true);
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").describe(keys, description);
    return this;
  }
  detectLocale(detect) {
    argsert("<boolean>", [detect], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_detectLocale, detect, "f");
    return this;
  }
  env(prefix) {
    argsert("[string|boolean]", [prefix], arguments.length);
    if (prefix === false)
      delete __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix;
    else
      __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix = prefix || "";
    return this;
  }
  epilogue(msg) {
    argsert("<string>", [msg], arguments.length);
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").epilog(msg);
    return this;
  }
  epilog(msg) {
    return this.epilogue(msg);
  }
  example(cmd, description) {
    argsert("<string|array> [string]", [cmd, description], arguments.length);
    if (Array.isArray(cmd)) {
      cmd.forEach((exampleParams) => this.example(...exampleParams));
    } else {
      __classPrivateFieldGet(this, _YargsInstance_usage, "f").example(cmd, description);
    }
    return this;
  }
  exit(code, err) {
    __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
    __classPrivateFieldSet(this, _YargsInstance_exitError, err, "f");
    if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
      __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.exit(code);
  }
  exitProcess(enabled = true) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_exitProcess, enabled, "f");
    return this;
  }
  fail(f) {
    argsert("<function|boolean>", [f], arguments.length);
    if (typeof f === "boolean" && f !== false) {
      throw new YError("Invalid first argument. Expected function or boolean 'false'");
    }
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").failFn(f);
    return this;
  }
  getAliases() {
    return this.parsed ? this.parsed.aliases : {};
  }
  async getCompletion(args, done) {
    argsert("<array> [function]", [args, done], arguments.length);
    if (!done) {
      return new Promise((resolve9, reject) => {
        __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => {
          if (err)
            reject(err);
          else
            resolve9(completions);
        });
      });
    } else {
      return __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, done);
    }
  }
  getDemandedOptions() {
    argsert([], 0);
    return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedOptions;
  }
  getDemandedCommands() {
    argsert([], 0);
    return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands;
  }
  getDeprecatedOptions() {
    argsert([], 0);
    return __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions;
  }
  getDetectLocale() {
    return __classPrivateFieldGet(this, _YargsInstance_detectLocale, "f");
  }
  getExitProcess() {
    return __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f");
  }
  getGroups() {
    return Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_groups, "f"), __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"));
  }
  getHelp() {
    __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
    if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
      if (!this.parsed) {
        const parse4 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
        if (isPromise(parse4)) {
          return parse4.then(() => {
            return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help();
          });
        }
      }
      const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
      if (isPromise(builderResponse)) {
        return builderResponse.then(() => {
          return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help();
        });
      }
    }
    return Promise.resolve(__classPrivateFieldGet(this, _YargsInstance_usage, "f").help());
  }
  getOptions() {
    return __classPrivateFieldGet(this, _YargsInstance_options, "f");
  }
  getStrict() {
    return __classPrivateFieldGet(this, _YargsInstance_strict, "f");
  }
  getStrictCommands() {
    return __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f");
  }
  getStrictOptions() {
    return __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f");
  }
  global(globals, global) {
    argsert("<string|array> [boolean]", [globals, global], arguments.length);
    globals = [].concat(globals);
    if (global !== false) {
      __classPrivateFieldGet(this, _YargsInstance_options, "f").local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local.filter((l) => globals.indexOf(l) === -1);
    } else {
      globals.forEach((g) => {
        if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").local.includes(g))
          __classPrivateFieldGet(this, _YargsInstance_options, "f").local.push(g);
      });
    }
    return this;
  }
  group(opts, groupName) {
    argsert("<string|array> <string>", [opts, groupName], arguments.length);
    const existing = __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName];
    if (__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]) {
      delete __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName];
    }
    const seen = {};
    __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter((key) => {
      if (seen[key])
        return false;
      return seen[key] = true;
    });
    return this;
  }
  hide(key) {
    argsert("<string>", [key], arguments.length);
    __classPrivateFieldGet(this, _YargsInstance_options, "f").hiddenOptions.push(key);
    return this;
  }
  implies(key, value) {
    argsert("<string|object> [number|string|array]", [key, value], arguments.length);
    __classPrivateFieldGet(this, _YargsInstance_validation, "f").implies(key, value);
    return this;
  }
  locale(locale) {
    argsert("[string]", [locale], arguments.length);
    if (locale === void 0) {
      this[kGuessLocale]();
      return __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.getLocale();
    }
    __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f");
    __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(locale);
    return this;
  }
  middleware(callback, applyBeforeValidation, global) {
    return __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global);
  }
  nargs(key, value) {
    argsert("<string|object|array> [number]", [key, value], arguments.length);
    this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), "narg", key, value);
    return this;
  }
  normalize(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("normalize", keys);
    return this;
  }
  number(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("number", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  option(key, opt) {
    argsert("<string|object> [object]", [key, opt], arguments.length);
    if (typeof key === "object") {
      Object.keys(key).forEach((k) => {
        this.options(k, key[k]);
      });
    } else {
      if (typeof opt !== "object") {
        opt = {};
      }
      this[kTrackManuallySetKeys](key);
      if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && (key === "version" || (opt === null || opt === void 0 ? void 0 : opt.alias) === "version")) {
        this[kEmitWarning]([
          '"version" is a reserved word.',
          "Please do one of the following:",
          '- Disable version with `yargs.version(false)` if using "version" as an option',
          "- Use the built-in `yargs.version` method instead (if applicable)",
          "- Use a different option key",
          "https://yargs.js.org/docs/#api-reference-version"
        ].join("\n"), void 0, "versionWarning");
      }
      __classPrivateFieldGet(this, _YargsInstance_options, "f").key[key] = true;
      if (opt.alias)
        this.alias(key, opt.alias);
      const deprecate = opt.deprecate || opt.deprecated;
      if (deprecate) {
        this.deprecateOption(key, deprecate);
      }
      const demand = opt.demand || opt.required || opt.require;
      if (demand) {
        this.demand(key, demand);
      }
      if (opt.demandOption) {
        this.demandOption(key, typeof opt.demandOption === "string" ? opt.demandOption : void 0);
      }
      if (opt.conflicts) {
        this.conflicts(key, opt.conflicts);
      }
      if ("default" in opt) {
        this.default(key, opt.default);
      }
      if (opt.implies !== void 0) {
        this.implies(key, opt.implies);
      }
      if (opt.nargs !== void 0) {
        this.nargs(key, opt.nargs);
      }
      if (opt.config) {
        this.config(key, opt.configParser);
      }
      if (opt.normalize) {
        this.normalize(key);
      }
      if (opt.choices) {
        this.choices(key, opt.choices);
      }
      if (opt.coerce) {
        this.coerce(key, opt.coerce);
      }
      if (opt.group) {
        this.group(key, opt.group);
      }
      if (opt.boolean || opt.type === "boolean") {
        this.boolean(key);
        if (opt.alias)
          this.boolean(opt.alias);
      }
      if (opt.array || opt.type === "array") {
        this.array(key);
        if (opt.alias)
          this.array(opt.alias);
      }
      if (opt.number || opt.type === "number") {
        this.number(key);
        if (opt.alias)
          this.number(opt.alias);
      }
      if (opt.string || opt.type === "string") {
        this.string(key);
        if (opt.alias)
          this.string(opt.alias);
      }
      if (opt.count || opt.type === "count") {
        this.count(key);
      }
      if (typeof opt.global === "boolean") {
        this.global(key, opt.global);
      }
      if (opt.defaultDescription) {
        __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription;
      }
      if (opt.skipValidation) {
        this.skipValidation(key);
      }
      const desc = opt.describe || opt.description || opt.desc;
      const descriptions = __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions();
      if (!Object.prototype.hasOwnProperty.call(descriptions, key) || typeof desc === "string") {
        this.describe(key, desc);
      }
      if (opt.hidden) {
        this.hide(key);
      }
      if (opt.requiresArg) {
        this.requiresArg(key);
      }
    }
    return this;
  }
  options(key, opt) {
    return this.option(key, opt);
  }
  parse(args, shortCircuit, _parseFn) {
    argsert("[string|array] [function|boolean|object] [function]", [args, shortCircuit, _parseFn], arguments.length);
    this[kFreeze]();
    if (typeof args === "undefined") {
      args = __classPrivateFieldGet(this, _YargsInstance_processArgs, "f");
    }
    if (typeof shortCircuit === "object") {
      __classPrivateFieldSet(this, _YargsInstance_parseContext, shortCircuit, "f");
      shortCircuit = _parseFn;
    }
    if (typeof shortCircuit === "function") {
      __classPrivateFieldSet(this, _YargsInstance_parseFn, shortCircuit, "f");
      shortCircuit = false;
    }
    if (!shortCircuit)
      __classPrivateFieldSet(this, _YargsInstance_processArgs, args, "f");
    if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"))
      __classPrivateFieldSet(this, _YargsInstance_exitProcess, false, "f");
    const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit);
    const tmpParsed = this.parsed;
    __classPrivateFieldGet(this, _YargsInstance_completion, "f").setParsed(this.parsed);
    if (isPromise(parsed)) {
      return parsed.then((argv) => {
        if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"))
          __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet(this, _YargsInstance_output, "f"));
        return argv;
      }).catch((err) => {
        if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) {
          __classPrivateFieldGet(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet(this, _YargsInstance_output, "f"));
        }
        throw err;
      }).finally(() => {
        this[kUnfreeze]();
        this.parsed = tmpParsed;
      });
    } else {
      if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"))
        __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet(this, _YargsInstance_output, "f"));
      this[kUnfreeze]();
      this.parsed = tmpParsed;
    }
    return parsed;
  }
  parseAsync(args, shortCircuit, _parseFn) {
    const maybePromise = this.parse(args, shortCircuit, _parseFn);
    return !isPromise(maybePromise) ? Promise.resolve(maybePromise) : maybePromise;
  }
  parseSync(args, shortCircuit, _parseFn) {
    const maybePromise = this.parse(args, shortCircuit, _parseFn);
    if (isPromise(maybePromise)) {
      throw new YError(".parseSync() must not be used with asynchronous builders, handlers, or middleware");
    }
    return maybePromise;
  }
  parserConfiguration(config2) {
    argsert("<object>", [config2], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_parserConfig, config2, "f");
    return this;
  }
  pkgConf(key, rootPath) {
    argsert("<string> [string]", [key, rootPath], arguments.length);
    let conf = null;
    const obj = this[kPkgUp](rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"));
    if (obj[key] && typeof obj[key] === "object") {
      conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()["deep-merge-config"] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
      __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(conf);
    }
    return this;
  }
  positional(key, opts) {
    argsert("<string> <object>", [key, opts], arguments.length);
    const supportedOpts = [
      "default",
      "defaultDescription",
      "implies",
      "normalize",
      "choices",
      "conflicts",
      "coerce",
      "type",
      "describe",
      "desc",
      "description",
      "alias"
    ];
    opts = objFilter(opts, (k, v) => {
      if (k === "type" && !["string", "number", "boolean"].includes(v))
        return false;
      return supportedOpts.includes(k);
    });
    const fullCommand = __classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands.length - 1];
    const parseOptions = fullCommand ? __classPrivateFieldGet(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) : {
      array: [],
      alias: {},
      default: {},
      demand: {}
    };
    objectKeys(parseOptions).forEach((pk) => {
      const parseOption = parseOptions[pk];
      if (Array.isArray(parseOption)) {
        if (parseOption.indexOf(key) !== -1)
          opts[pk] = true;
      } else {
        if (parseOption[key] && !(pk in opts))
          opts[pk] = parseOption[key];
      }
    });
    this.group(key, __classPrivateFieldGet(this, _YargsInstance_usage, "f").getPositionalGroupName());
    return this.option(key, opts);
  }
  recommendCommands(recommend = true) {
    argsert("[boolean]", [recommend], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_recommendCommands, recommend, "f");
    return this;
  }
  required(keys, max, msg) {
    return this.demand(keys, max, msg);
  }
  require(keys, max, msg) {
    return this.demand(keys, max, msg);
  }
  requiresArg(keys) {
    argsert("<array|string|object> [number]", [keys], arguments.length);
    if (typeof keys === "string" && __classPrivateFieldGet(this, _YargsInstance_options, "f").narg[keys]) {
      return this;
    } else {
      this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), "narg", keys, NaN);
    }
    return this;
  }
  showCompletionScript($0, cmd) {
    argsert("[string] [string]", [$0, cmd], arguments.length);
    $0 = $0 || this.$0;
    __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || "completion"));
    return this;
  }
  showHelp(level) {
    argsert("[string|function]", [level], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
    if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) {
      if (!this.parsed) {
        const parse4 = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), void 0, void 0, 0, true);
        if (isPromise(parse4)) {
          parse4.then(() => {
            __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level);
          });
          return this;
        }
      }
      const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this);
      if (isPromise(builderResponse)) {
        builderResponse.then(() => {
          __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level);
        });
        return this;
      }
    }
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level);
    return this;
  }
  scriptName(scriptName) {
    this.customScriptName = true;
    this.$0 = scriptName;
    return this;
  }
  showHelpOnFail(enabled, message) {
    argsert("[boolean|string] [string]", [enabled, message], arguments.length);
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message);
    return this;
  }
  showVersion(level) {
    argsert("[string|function]", [level], arguments.length);
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion(level);
    return this;
  }
  skipValidation(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("skipValidation", keys);
    return this;
  }
  strict(enabled) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_strict, enabled !== false, "f");
    return this;
  }
  strictCommands(enabled) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_strictCommands, enabled !== false, "f");
    return this;
  }
  strictOptions(enabled) {
    argsert("[boolean]", [enabled], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_strictOptions, enabled !== false, "f");
    return this;
  }
  string(keys) {
    argsert("<array|string>", [keys], arguments.length);
    this[kPopulateParserHintArray]("string", keys);
    this[kTrackManuallySetKeys](keys);
    return this;
  }
  terminalWidth() {
    argsert([], 0);
    return __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.stdColumns;
  }
  updateLocale(obj) {
    return this.updateStrings(obj);
  }
  updateStrings(obj) {
    argsert("<object>", [obj], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f");
    __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.updateLocale(obj);
    return this;
  }
  usage(msg, description, builder, handler) {
    argsert("<string|null|undefined> [string|boolean] [function|object] [function]", [msg, description, builder, handler], arguments.length);
    if (description !== void 0) {
      assertNotStrictEqual(msg, null, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
      if ((msg || "").match(/^\$0( |$)/)) {
        return this.command(msg, description, builder, handler);
      } else {
        throw new YError(".usage() description must start with $0 if being used as alias for .command()");
      }
    } else {
      __classPrivateFieldGet(this, _YargsInstance_usage, "f").usage(msg);
      return this;
    }
  }
  usageConfiguration(config2) {
    argsert("<object>", [config2], arguments.length);
    __classPrivateFieldSet(this, _YargsInstance_usageConfig, config2, "f");
    return this;
  }
  version(opt, msg, ver) {
    const defaultVersionOpt = "version";
    argsert("[boolean|string] [string] [string]", [opt, msg, ver], arguments.length);
    if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")) {
      this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"));
      __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(void 0);
      __classPrivateFieldSet(this, _YargsInstance_versionOpt, null, "f");
    }
    if (arguments.length === 0) {
      ver = this[kGuessVersion]();
      opt = defaultVersionOpt;
    } else if (arguments.length === 1) {
      if (opt === false) {
        return this;
      }
      ver = opt;
      opt = defaultVersionOpt;
    } else if (arguments.length === 2) {
      ver = msg;
      msg = void 0;
    }
    __classPrivateFieldSet(this, _YargsInstance_versionOpt, typeof opt === "string" ? opt : defaultVersionOpt, "f");
    msg = msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup("Show version number");
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(ver || void 0);
    this.boolean(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"));
    this.describe(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"), msg);
    return this;
  }
  wrap(cols) {
    argsert("<number|null|undefined>", [cols], arguments.length);
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").wrap(cols);
    return this;
  }
  [(_YargsInstance_command = /* @__PURE__ */ new WeakMap(), _YargsInstance_cwd = /* @__PURE__ */ new WeakMap(), _YargsInstance_context = /* @__PURE__ */ new WeakMap(), _YargsInstance_completion = /* @__PURE__ */ new WeakMap(), _YargsInstance_completionCommand = /* @__PURE__ */ new WeakMap(), _YargsInstance_defaultShowHiddenOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_exitError = /* @__PURE__ */ new WeakMap(), _YargsInstance_detectLocale = /* @__PURE__ */ new WeakMap(), _YargsInstance_emittedWarnings = /* @__PURE__ */ new WeakMap(), _YargsInstance_exitProcess = /* @__PURE__ */ new WeakMap(), _YargsInstance_frozens = /* @__PURE__ */ new WeakMap(), _YargsInstance_globalMiddleware = /* @__PURE__ */ new WeakMap(), _YargsInstance_groups = /* @__PURE__ */ new WeakMap(), _YargsInstance_hasOutput = /* @__PURE__ */ new WeakMap(), _YargsInstance_helpOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_isGlobalContext = /* @__PURE__ */ new WeakMap(), _YargsInstance_logger = /* @__PURE__ */ new WeakMap(), _YargsInstance_output = /* @__PURE__ */ new WeakMap(), _YargsInstance_options = /* @__PURE__ */ new WeakMap(), _YargsInstance_parentRequire = /* @__PURE__ */ new WeakMap(), _YargsInstance_parserConfig = /* @__PURE__ */ new WeakMap(), _YargsInstance_parseFn = /* @__PURE__ */ new WeakMap(), _YargsInstance_parseContext = /* @__PURE__ */ new WeakMap(), _YargsInstance_pkgs = /* @__PURE__ */ new WeakMap(), _YargsInstance_preservedGroups = /* @__PURE__ */ new WeakMap(), _YargsInstance_processArgs = /* @__PURE__ */ new WeakMap(), _YargsInstance_recommendCommands = /* @__PURE__ */ new WeakMap(), _YargsInstance_shim = /* @__PURE__ */ new WeakMap(), _YargsInstance_strict = /* @__PURE__ */ new WeakMap(), _YargsInstance_strictCommands = /* @__PURE__ */ new WeakMap(), _YargsInstance_strictOptions = /* @__PURE__ */ new WeakMap(), _YargsInstance_usage = /* @__PURE__ */ new WeakMap(), _YargsInstance_usageConfig = /* @__PURE__ */ new WeakMap(), _YargsInstance_versionOpt = /* @__PURE__ */ new WeakMap(), _YargsInstance_validation = /* @__PURE__ */ new WeakMap(), kCopyDoubleDash)](argv) {
    if (!argv._ || !argv["--"])
      return argv;
    argv._.push.apply(argv._, argv["--"]);
    try {
      delete argv["--"];
    } catch (_err) {
    }
    return argv;
  }
  [kCreateLogger]() {
    return {
      log: (...args) => {
        if (!this[kHasParseCallback]())
          console.log(...args);
        __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
        if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length)
          __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + "\n", "f");
        __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(" "), "f");
      },
      error: (...args) => {
        if (!this[kHasParseCallback]())
          console.error(...args);
        __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
        if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length)
          __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + "\n", "f");
        __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(" "), "f");
      }
    };
  }
  [kDeleteFromParserHintObject](optionKey) {
    objectKeys(__classPrivateFieldGet(this, _YargsInstance_options, "f")).forEach((hintKey) => {
      if (/* @__PURE__ */ ((key) => key === "configObjects")(hintKey))
        return;
      const hint = __classPrivateFieldGet(this, _YargsInstance_options, "f")[hintKey];
      if (Array.isArray(hint)) {
        if (hint.includes(optionKey))
          hint.splice(hint.indexOf(optionKey), 1);
      } else if (typeof hint === "object") {
        delete hint[optionKey];
      }
    });
    delete __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions()[optionKey];
  }
  [kEmitWarning](warning, type, deduplicationId) {
    if (!__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) {
      __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.emitWarning(warning, type);
      __classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true;
    }
  }
  [kFreeze]() {
    __classPrivateFieldGet(this, _YargsInstance_frozens, "f").push({
      options: __classPrivateFieldGet(this, _YargsInstance_options, "f"),
      configObjects: __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects.slice(0),
      exitProcess: __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"),
      groups: __classPrivateFieldGet(this, _YargsInstance_groups, "f"),
      strict: __classPrivateFieldGet(this, _YargsInstance_strict, "f"),
      strictCommands: __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"),
      strictOptions: __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"),
      completionCommand: __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"),
      output: __classPrivateFieldGet(this, _YargsInstance_output, "f"),
      exitError: __classPrivateFieldGet(this, _YargsInstance_exitError, "f"),
      hasOutput: __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"),
      parsed: this.parsed,
      parseFn: __classPrivateFieldGet(this, _YargsInstance_parseFn, "f"),
      parseContext: __classPrivateFieldGet(this, _YargsInstance_parseContext, "f")
    });
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").freeze();
    __classPrivateFieldGet(this, _YargsInstance_validation, "f").freeze();
    __classPrivateFieldGet(this, _YargsInstance_command, "f").freeze();
    __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").freeze();
  }
  [kGetDollarZero]() {
    let $0 = "";
    let default$0;
    if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv()[0])) {
      default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(1, 2);
    } else {
      default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(0, 1);
    }
    $0 = default$0.map((x) => {
      const b = this[kRebase](__classPrivateFieldGet(this, _YargsInstance_cwd, "f"), x);
      return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x;
    }).join(" ").trim();
    if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv("_") && __classPrivateFieldGet(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv("_")) {
      $0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv("_").replace(`${__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.execPath())}/`, "");
    }
    return $0;
  }
  [kGetParserConfiguration]() {
    return __classPrivateFieldGet(this, _YargsInstance_parserConfig, "f");
  }
  [kGetUsageConfiguration]() {
    return __classPrivateFieldGet(this, _YargsInstance_usageConfig, "f");
  }
  [kGuessLocale]() {
    if (!__classPrivateFieldGet(this, _YargsInstance_detectLocale, "f"))
      return;
    const locale = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv("LC_ALL") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv("LC_MESSAGES") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv("LANG") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv("LANGUAGE") || "en_US";
    this.locale(locale.replace(/[.:].*/, ""));
  }
  [kGuessVersion]() {
    const obj = this[kPkgUp]();
    return obj.version || "unknown";
  }
  [kParsePositionalNumbers](argv) {
    const args = argv["--"] ? argv["--"] : argv._;
    for (let i = 0, arg; (arg = args[i]) !== void 0; i++) {
      if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) {
        args[i] = Number(arg);
      }
    }
    return argv;
  }
  [kPkgUp](rootPath) {
    const npath = rootPath || "*";
    if (__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath])
      return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath];
    let obj = {};
    try {
      let startDir = rootPath || __classPrivateFieldGet(this, _YargsInstance_shim, "f").mainFilename;
      if (!rootPath && __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.extname(startDir)) {
        startDir = __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(startDir);
      }
      const pkgJsonPath = __classPrivateFieldGet(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => {
        if (names.includes("package.json")) {
          return "package.json";
        } else {
          return void 0;
        }
      });
      assertNotStrictEqual(pkgJsonPath, void 0, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
      obj = JSON.parse(__classPrivateFieldGet(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, "utf8"));
    } catch (_noop) {
    }
    __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath] = obj || {};
    return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath];
  }
  [kPopulateParserHintArray](type, keys) {
    keys = [].concat(keys);
    keys.forEach((key) => {
      key = this[kSanitizeKey](key);
      __classPrivateFieldGet(this, _YargsInstance_options, "f")[type].push(key);
    });
  }
  [kPopulateParserHintSingleValueDictionary](builder, type, key, value) {
    this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
      __classPrivateFieldGet(this, _YargsInstance_options, "f")[type2][key2] = value2;
    });
  }
  [kPopulateParserHintArrayDictionary](builder, type, key, value) {
    this[kPopulateParserHintDictionary](builder, type, key, value, (type2, key2, value2) => {
      __classPrivateFieldGet(this, _YargsInstance_options, "f")[type2][key2] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[type2][key2] || []).concat(value2);
    });
  }
  [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) {
    if (Array.isArray(key)) {
      key.forEach((k) => {
        builder(k, value);
      });
    } else if (/* @__PURE__ */ ((key2) => typeof key2 === "object")(key)) {
      for (const k of objectKeys(key)) {
        builder(k, key[k]);
      }
    } else {
      singleKeyHandler(type, this[kSanitizeKey](key), value);
    }
  }
  [kSanitizeKey](key) {
    if (key === "__proto__")
      return "___proto___";
    return key;
  }
  [kSetKey](key, set) {
    this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), "key", key, set);
    return this;
  }
  [kUnfreeze]() {
    var _a4, _b2, _c2, _d, _e, _f, _g, _h, _j, _k, _l, _m;
    const frozen = __classPrivateFieldGet(this, _YargsInstance_frozens, "f").pop();
    assertNotStrictEqual(frozen, void 0, __classPrivateFieldGet(this, _YargsInstance_shim, "f"));
    let configObjects;
    _a4 = this, _b2 = this, _c2 = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, {
      options: { set value(_o) {
        __classPrivateFieldSet(_a4, _YargsInstance_options, _o, "f");
      } }.value,
      configObjects,
      exitProcess: { set value(_o) {
        __classPrivateFieldSet(_b2, _YargsInstance_exitProcess, _o, "f");
      } }.value,
      groups: { set value(_o) {
        __classPrivateFieldSet(_c2, _YargsInstance_groups, _o, "f");
      } }.value,
      output: { set value(_o) {
        __classPrivateFieldSet(_d, _YargsInstance_output, _o, "f");
      } }.value,
      exitError: { set value(_o) {
        __classPrivateFieldSet(_e, _YargsInstance_exitError, _o, "f");
      } }.value,
      hasOutput: { set value(_o) {
        __classPrivateFieldSet(_f, _YargsInstance_hasOutput, _o, "f");
      } }.value,
      parsed: this.parsed,
      strict: { set value(_o) {
        __classPrivateFieldSet(_g, _YargsInstance_strict, _o, "f");
      } }.value,
      strictCommands: { set value(_o) {
        __classPrivateFieldSet(_h, _YargsInstance_strictCommands, _o, "f");
      } }.value,
      strictOptions: { set value(_o) {
        __classPrivateFieldSet(_j, _YargsInstance_strictOptions, _o, "f");
      } }.value,
      completionCommand: { set value(_o) {
        __classPrivateFieldSet(_k, _YargsInstance_completionCommand, _o, "f");
      } }.value,
      parseFn: { set value(_o) {
        __classPrivateFieldSet(_l, _YargsInstance_parseFn, _o, "f");
      } }.value,
      parseContext: { set value(_o) {
        __classPrivateFieldSet(_m, _YargsInstance_parseContext, _o, "f");
      } }.value
    } = frozen;
    __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = configObjects;
    __classPrivateFieldGet(this, _YargsInstance_usage, "f").unfreeze();
    __classPrivateFieldGet(this, _YargsInstance_validation, "f").unfreeze();
    __classPrivateFieldGet(this, _YargsInstance_command, "f").unfreeze();
    __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").unfreeze();
  }
  [kValidateAsync](validation2, argv) {
    return maybeAsyncResult(argv, (result) => {
      validation2(result);
      return result;
    });
  }
  getInternalMethods() {
    return {
      getCommandInstance: this[kGetCommandInstance].bind(this),
      getContext: this[kGetContext].bind(this),
      getHasOutput: this[kGetHasOutput].bind(this),
      getLoggerInstance: this[kGetLoggerInstance].bind(this),
      getParseContext: this[kGetParseContext].bind(this),
      getParserConfiguration: this[kGetParserConfiguration].bind(this),
      getUsageConfiguration: this[kGetUsageConfiguration].bind(this),
      getUsageInstance: this[kGetUsageInstance].bind(this),
      getValidationInstance: this[kGetValidationInstance].bind(this),
      hasParseCallback: this[kHasParseCallback].bind(this),
      isGlobalContext: this[kIsGlobalContext].bind(this),
      postProcess: this[kPostProcess].bind(this),
      reset: this[kReset].bind(this),
      runValidation: this[kRunValidation].bind(this),
      runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this),
      setHasOutput: this[kSetHasOutput].bind(this)
    };
  }
  [kGetCommandInstance]() {
    return __classPrivateFieldGet(this, _YargsInstance_command, "f");
  }
  [kGetContext]() {
    return __classPrivateFieldGet(this, _YargsInstance_context, "f");
  }
  [kGetHasOutput]() {
    return __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f");
  }
  [kGetLoggerInstance]() {
    return __classPrivateFieldGet(this, _YargsInstance_logger, "f");
  }
  [kGetParseContext]() {
    return __classPrivateFieldGet(this, _YargsInstance_parseContext, "f") || {};
  }
  [kGetUsageInstance]() {
    return __classPrivateFieldGet(this, _YargsInstance_usage, "f");
  }
  [kGetValidationInstance]() {
    return __classPrivateFieldGet(this, _YargsInstance_validation, "f");
  }
  [kHasParseCallback]() {
    return !!__classPrivateFieldGet(this, _YargsInstance_parseFn, "f");
  }
  [kIsGlobalContext]() {
    return __classPrivateFieldGet(this, _YargsInstance_isGlobalContext, "f");
  }
  [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) {
    if (calledFromCommand)
      return argv;
    if (isPromise(argv))
      return argv;
    if (!populateDoubleDash) {
      argv = this[kCopyDoubleDash](argv);
    }
    const parsePositionalNumbers = this[kGetParserConfiguration]()["parse-positional-numbers"] || this[kGetParserConfiguration]()["parse-positional-numbers"] === void 0;
    if (parsePositionalNumbers) {
      argv = this[kParsePositionalNumbers](argv);
    }
    if (runGlobalMiddleware) {
      argv = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
    }
    return argv;
  }
  [kReset](aliases = {}) {
    __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f") || {}, "f");
    const tmpOptions = {};
    tmpOptions.local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local || [];
    tmpOptions.configObjects = __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || [];
    const localLookup = {};
    tmpOptions.local.forEach((l) => {
      localLookup[l] = true;
      (aliases[l] || []).forEach((a) => {
        localLookup[a] = true;
      });
    });
    Object.assign(__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => {
      const keys = __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName].filter((key) => !(key in localLookup));
      if (keys.length > 0) {
        acc[groupName] = keys;
      }
      return acc;
    }, {}));
    __classPrivateFieldSet(this, _YargsInstance_groups, {}, "f");
    const arrayOptions = [
      "array",
      "boolean",
      "string",
      "skipValidation",
      "count",
      "normalize",
      "number",
      "hiddenOptions"
    ];
    const objectOptions = [
      "narg",
      "key",
      "alias",
      "default",
      "defaultDescription",
      "config",
      "choices",
      "demandedOptions",
      "demandedCommands",
      "deprecatedOptions"
    ];
    arrayOptions.forEach((k) => {
      tmpOptions[k] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[k] || []).filter((k2) => !localLookup[k2]);
    });
    objectOptions.forEach((k) => {
      tmpOptions[k] = objFilter(__classPrivateFieldGet(this, _YargsInstance_options, "f")[k], (k2) => !localLookup[k2]);
    });
    tmpOptions.envPrefix = __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix;
    __classPrivateFieldSet(this, _YargsInstance_options, tmpOptions, "f");
    __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f") ? __classPrivateFieldGet(this, _YargsInstance_usage, "f").reset(localLookup) : usage(this, __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f");
    __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f") ? __classPrivateFieldGet(this, _YargsInstance_validation, "f").reset(localLookup) : validation(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f");
    __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f") ? __classPrivateFieldGet(this, _YargsInstance_command, "f").reset() : command(__classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_validation, "f"), __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f");
    if (!__classPrivateFieldGet(this, _YargsInstance_completion, "f"))
      __classPrivateFieldSet(this, _YargsInstance_completion, completion(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_command, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f");
    __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").reset();
    __classPrivateFieldSet(this, _YargsInstance_completionCommand, null, "f");
    __classPrivateFieldSet(this, _YargsInstance_output, "", "f");
    __classPrivateFieldSet(this, _YargsInstance_exitError, null, "f");
    __classPrivateFieldSet(this, _YargsInstance_hasOutput, false, "f");
    this.parsed = false;
    return this;
  }
  [kRebase](base, dir) {
    return __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.relative(base, dir);
  }
  [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) {
    let skipValidation = !!calledFromCommand || helpOnly;
    args = args || __classPrivateFieldGet(this, _YargsInstance_processArgs, "f");
    __classPrivateFieldGet(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__;
    __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration]();
    const populateDoubleDash = !!__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration["populate--"];
    const config2 = Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration, {
      "populate--": true
    });
    const parsed = __classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f"), {
      configuration: { "parse-positional-numbers": false, ...config2 }
    }));
    const argv = Object.assign(parsed.argv, __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"));
    let argvPromise = void 0;
    const aliases = parsed.aliases;
    let helpOptSet = false;
    let versionOptSet = false;
    Object.keys(argv).forEach((key) => {
      if (key === __classPrivateFieldGet(this, _YargsInstance_helpOpt, "f") && argv[key]) {
        helpOptSet = true;
      } else if (key === __classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && argv[key]) {
        versionOptSet = true;
      }
    });
    argv.$0 = this.$0;
    this.parsed = parsed;
    if (commandIndex === 0) {
      __classPrivateFieldGet(this, _YargsInstance_usage, "f").clearCachedHelpMessage();
    }
    try {
      this[kGuessLocale]();
      if (shortCircuit) {
        return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false);
      }
      if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) {
        const helpCmds = [__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")].concat(aliases[__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] || []).filter((k) => k.length > 1);
        if (helpCmds.includes("" + argv._[argv._.length - 1])) {
          argv._.pop();
          helpOptSet = true;
        }
      }
      __classPrivateFieldSet(this, _YargsInstance_isGlobalContext, false, "f");
      const handlerKeys = __classPrivateFieldGet(this, _YargsInstance_command, "f").getCommands();
      const requestCompletions = __classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey in argv;
      const skipRecommendation = helpOptSet || requestCompletions || helpOnly;
      if (argv._.length) {
        if (handlerKeys.length) {
          let firstUnknownCommand;
          for (let i = commandIndex || 0, cmd; argv._[i] !== void 0; i++) {
            cmd = String(argv._[i]);
            if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) {
              const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly);
              return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
            } else if (!firstUnknownCommand && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) {
              firstUnknownCommand = cmd;
              break;
            }
          }
          if (!__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && __classPrivateFieldGet(this, _YargsInstance_recommendCommands, "f") && firstUnknownCommand && !skipRecommendation) {
            __classPrivateFieldGet(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys);
          }
        }
        if (__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") && argv._.includes(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) && !requestCompletions) {
          if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
            setBlocking(true);
          this.showCompletionScript();
          this.exit(0);
        }
      }
      if (__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) {
        const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly);
        return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false);
      }
      if (requestCompletions) {
        if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
          setBlocking(true);
        args = [].concat(args);
        const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey}`) + 1);
        __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => {
          if (err)
            throw new YError(err.message);
          (completions || []).forEach((completion2) => {
            __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(completion2);
          });
          this.exit(0);
        });
        return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false);
      }
      if (!__classPrivateFieldGet(this, _YargsInstance_hasOutput, "f")) {
        if (helpOptSet) {
          if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
            setBlocking(true);
          skipValidation = true;
          this.showHelp("log");
          this.exit(0);
        } else if (versionOptSet) {
          if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"))
            setBlocking(true);
          skipValidation = true;
          __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion("log");
          this.exit(0);
        }
      }
      if (!skipValidation && __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.length > 0) {
        skipValidation = Object.keys(argv).some((key) => __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true);
      }
      if (!skipValidation) {
        if (parsed.error)
          throw new YError(parsed.error.message);
        if (!requestCompletions) {
          const validation2 = this[kRunValidation](aliases, {}, parsed.error);
          if (!calledFromCommand) {
            argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true);
          }
          argvPromise = this[kValidateAsync](validation2, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv);
          if (isPromise(argvPromise) && !calledFromCommand) {
            argvPromise = argvPromise.then(() => {
              return applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false);
            });
          }
        }
      }
    } catch (err) {
      if (err instanceof YError)
        __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message, err);
      else
        throw err;
    }
    return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true);
  }
  [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) {
    const demandedOptions = { ...this.getDemandedOptions() };
    return (argv) => {
      if (parseErrors)
        throw new YError(parseErrors.message);
      __classPrivateFieldGet(this, _YargsInstance_validation, "f").nonOptionCount(argv);
      __classPrivateFieldGet(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions);
      let failedStrictCommands = false;
      if (__classPrivateFieldGet(this, _YargsInstance_strictCommands, "f")) {
        failedStrictCommands = __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownCommands(argv);
      }
      if (__classPrivateFieldGet(this, _YargsInstance_strict, "f") && !failedStrictCommands) {
        __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand);
      } else if (__classPrivateFieldGet(this, _YargsInstance_strictOptions, "f")) {
        __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false);
      }
      __classPrivateFieldGet(this, _YargsInstance_validation, "f").limitedChoices(argv);
      __classPrivateFieldGet(this, _YargsInstance_validation, "f").implications(argv);
      __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicting(argv);
    };
  }
  [kSetHasOutput]() {
    __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f");
  }
  [kTrackManuallySetKeys](keys) {
    if (typeof keys === "string") {
      __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true;
    } else {
      for (const k of keys) {
        __classPrivateFieldGet(this, _YargsInstance_options, "f").key[k] = true;
      }
    }
  }
};
function isYargsInstance(y) {
  return !!y && typeof y.getInternalMethods === "function";
}

// node_modules/yargs/index.mjs
var Yargs = YargsFactory(esm_default);
var yargs_default = Yargs;

// packages/cli/src/config/config.ts
import process4 from "node:process";
import * as path7 from "node:path";

// packages/cli/src/commands/mcp/add.ts
async function addMcpServer(name, commandOrUrl, args, options) {
  const {
    scope,
    transport,
    env: env2,
    header,
    timeout,
    trust,
    description,
    includeTools,
    excludeTools
  } = options;
  const settings = loadSettings(process.cwd());
  const inHome = settings.workspace.path === settings.user.path;
  if (scope === "project" && inHome) {
    debugLogger.error(
      "Error: Please use --scope user to edit settings in the home directory."
    );
    process.exit(1);
  }
  const settingsScope = scope === "user" ? "User" /* User */ : "Workspace" /* Workspace */;
  let newServer = {};
  const headers = header?.reduce(
    (acc, curr) => {
      const [key, ...valueParts] = curr.split(":");
      const value = valueParts.join(":").trim();
      if (key.trim() && value) {
        acc[key.trim()] = value;
      }
      return acc;
    },
    {}
  );
  switch (transport) {
    case "sse":
      newServer = {
        url: commandOrUrl,
        type: "sse",
        headers,
        timeout,
        trust,
        description,
        includeTools,
        excludeTools
      };
      break;
    case "http":
      newServer = {
        url: commandOrUrl,
        type: "http",
        headers,
        timeout,
        trust,
        description,
        includeTools,
        excludeTools
      };
      break;
    case "stdio":
    default:
      newServer = {
        command: commandOrUrl,
        args: args?.map(String),
        env: env2?.reduce(
          (acc, curr) => {
            const [key, value] = curr.split("=");
            if (key && value) {
              acc[key] = value;
            }
            return acc;
          },
          {}
        ),
        timeout,
        trust,
        description,
        includeTools,
        excludeTools
      };
      break;
  }
  const existingSettings = settings.forScope(settingsScope).settings;
  const mcpServers = existingSettings.mcpServers || {};
  const isExistingServer = !!mcpServers[name];
  if (isExistingServer) {
    debugLogger.log(
      `MCP server "${name}" is already configured within ${scope} settings.`
    );
  }
  mcpServers[name] = newServer;
  settings.setValue(settingsScope, "mcpServers", mcpServers);
  if (isExistingServer) {
    debugLogger.log(`MCP server "${name}" updated in ${scope} settings.`);
  } else {
    debugLogger.log(
      `MCP server "${name}" added to ${scope} settings. (${transport})`
    );
  }
}
var addCommand = {
  command: "add <name> <commandOrUrl> [args...]",
  describe: "Add a server",
  builder: (yargs) => yargs.usage("Usage: gemini mcp add [options] <name> <commandOrUrl> [args...]").parserConfiguration({
    "unknown-options-as-args": true,
    // Pass unknown options as server args
    "populate--": true
    // Populate server args after -- separator
  }).positional("name", {
    describe: "Name of the server",
    type: "string",
    demandOption: true
  }).positional("commandOrUrl", {
    describe: "Command (stdio) or URL (sse, http)",
    type: "string",
    demandOption: true
  }).option("scope", {
    alias: "s",
    describe: "Configuration scope (user or project)",
    type: "string",
    default: "project",
    choices: ["user", "project"]
  }).option("transport", {
    alias: ["t", "type"],
    describe: "Transport type (stdio, sse, http)",
    type: "string",
    default: "stdio",
    choices: ["stdio", "sse", "http"]
  }).option("env", {
    alias: "e",
    describe: "Set environment variables (e.g. -e KEY=value)",
    type: "array",
    string: true,
    nargs: 1
  }).option("header", {
    alias: "H",
    describe: 'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',
    type: "array",
    string: true,
    nargs: 1
  }).option("timeout", {
    describe: "Set connection timeout in milliseconds",
    type: "number"
  }).option("trust", {
    describe: "Trust the server (bypass all tool call confirmation prompts)",
    type: "boolean"
  }).option("description", {
    describe: "Set the description for the server",
    type: "string"
  }).option("include-tools", {
    describe: "A comma-separated list of tools to include",
    type: "array",
    string: true
  }).option("exclude-tools", {
    describe: "A comma-separated list of tools to exclude",
    type: "array",
    string: true
  }).middleware((argv) => {
    if (argv["--"]) {
      const existingArgs = argv["args"] || [];
      argv["args"] = [...existingArgs, ...argv["--"]];
    }
  }),
  handler: async (argv) => {
    await addMcpServer(
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      argv["name"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      argv["commandOrUrl"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      argv["args"],
      {
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        scope: argv["scope"],
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        transport: argv["transport"],
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        env: argv["env"],
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        header: argv["header"],
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        timeout: argv["timeout"],
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        trust: argv["trust"],
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        description: argv["description"],
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        includeTools: argv["includeTools"],
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        excludeTools: argv["excludeTools"]
      }
    );
    await exitCli();
  }
};

// packages/cli/src/commands/mcp/remove.ts
async function removeMcpServer(name, options) {
  const { scope } = options;
  const settingsScope = scope === "user" ? "User" /* User */ : "Workspace" /* Workspace */;
  const settings = loadSettings();
  const existingSettings = settings.forScope(settingsScope).settings;
  const mcpServers = existingSettings.mcpServers || {};
  if (!mcpServers[name]) {
    debugLogger.log(`Server "${name}" not found in ${scope} settings.`);
    return;
  }
  delete mcpServers[name];
  settings.setValue(settingsScope, "mcpServers", mcpServers);
  debugLogger.log(`Server "${name}" removed from ${scope} settings.`);
}
var removeCommand = {
  command: "remove <name>",
  describe: "Remove a server",
  builder: (yargs) => yargs.usage("Usage: gemini mcp remove [options] <name>").positional("name", {
    describe: "Name of the server",
    type: "string",
    demandOption: true
  }).option("scope", {
    alias: "s",
    describe: "Configuration scope (user or project)",
    type: "string",
    default: "project",
    choices: ["user", "project"]
  }),
  handler: async (argv) => {
    await removeMcpServer(argv["name"], {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      scope: argv["scope"]
    });
    await exitCli();
  }
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod/v4/core/core.js
var _a2;
// @__NO_SIDE_EFFECTS__
function $constructor(name, initializer3, params) {
  function init(inst, def) {
    if (!inst._zod) {
      Object.defineProperty(inst, "_zod", {
        value: {
          def,
          constr: _,
          traits: /* @__PURE__ */ new Set()
        },
        enumerable: false
      });
    }
    if (inst._zod.traits.has(name)) {
      return;
    }
    inst._zod.traits.add(name);
    initializer3(inst, def);
    const proto = _.prototype;
    const keys = Object.keys(proto);
    for (let i = 0; i < keys.length; i++) {
      const k = keys[i];
      if (!(k in inst)) {
        inst[k] = proto[k].bind(inst);
      }
    }
  }
  const Parent = params?.Parent ?? Object;
  class Definition extends Parent {
  }
  Object.defineProperty(Definition, "name", { value: name });
  function _(def) {
    var _a4;
    const inst = params?.Parent ? new Definition() : this;
    init(inst, def);
    (_a4 = inst._zod).deferred ?? (_a4.deferred = []);
    for (const fn of inst._zod.deferred) {
      fn();
    }
    return inst;
  }
  Object.defineProperty(_, "init", { value: init });
  Object.defineProperty(_, Symbol.hasInstance, {
    value: (inst) => {
      if (params?.Parent && inst instanceof params.Parent)
        return true;
      return inst?._zod?.traits?.has(name);
    }
  });
  Object.defineProperty(_, "name", { value: name });
  return _;
}
var $brand = 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";
  }
};
(_a2 = globalThis).__zod_globalConfig ?? (_a2.__zod_globalConfig = {});
var globalConfig = globalThis.__zod_globalConfig;
function config(newConfig) {
  if (newConfig)
    Object.assign(globalConfig, newConfig);
  return globalConfig;
}

// packages/cli/node_modules/@modelcontextprotocol/sdk/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,
  explicitlyAborted: () => explicitlyAborted,
  extend: () => extend,
  finalizeIssue: () => finalizeIssue,
  floatSafeRemainder: () => floatSafeRemainder,
  getElementAtPath: () => getElementAtPath,
  getEnumValues: () => getEnumValues,
  getLengthableOrigin: () => getLengthableOrigin,
  getParsedType: () => getParsedType,
  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(_) {
}
function getEnumValues(entries) {
  const numericValues = Object.values(entries).filter((v) => typeof v === "number");
  const values = Object.entries(entries).filter(([k, _]) => numericValues.indexOf(+k) === -1).map(([_, v]) => v);
  return values;
}
function joinValues(array2, separator = "|") {
  return array2.map((val) => stringifyPrimitive(val)).join(separator);
}
function jsonStringifyReplacer(_, value) {
  if (typeof value === "bigint")
    return value.toString();
  return value;
}
function cached(getter) {
  const set = false;
  return {
    get value() {
      if (!set) {
        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 floatSafeRemainder(val, step) {
  const ratio = val / step;
  const roundedRatio = Math.round(ratio);
  const tolerance = Number.EPSILON * Math.max(Math.abs(ratio), 1);
  if (Math.abs(ratio - roundedRatio) < tolerance)
    return 0;
  return ratio - roundedRatio;
}
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(v) {
      Object.defineProperty(object3, key, {
        value: v
        // 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, path16) {
  if (!path16)
    return obj;
  return path16.reduce((acc, key) => acc?.[key], obj);
}
function promiseAllObject(promisesObj) {
  const keys = Object.keys(promisesObj);
  const promises = keys.map((key) => promisesObj[key]);
  return Promise.all(promises).then((results) => {
    const resolvedObj = {};
    for (let i = 0; i < keys.length; i++) {
      resolvedObj[keys[i]] = results[i];
    }
    return resolvedObj;
  });
}
function randomString(length = 10) {
  const chars = "abcdefghijklmnopqrstuvwxyz";
  let str = "";
  for (let i = 0; i < length; i++) {
    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 = /* @__PURE__ */ cached(() => {
  if (globalConfig.jitless) {
    return false;
  }
  if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) {
    return false;
  }
  try {
    const F = Function;
    new F("");
    return true;
  } catch (_) {
    return false;
  }
});
function isPlainObject(o) {
  if (isObject(o) === false)
    return false;
  const ctor = o.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(o) {
  if (isPlainObject(o))
    return { ...o };
  if (Array.isArray(o))
    return [...o];
  if (o instanceof Map)
    return new Map(o);
  if (o instanceof Set)
    return new Set(o);
  return o;
}
function numKeys(data) {
  let keyCount = 0;
  for (const key in data) {
    if (Object.prototype.hasOwnProperty.call(data, key)) {
      keyCount++;
    }
  }
  return keyCount;
}
var getParsedType = (data) => {
  const t = typeof data;
  switch (t) {
    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: ${t}`);
  }
};
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 ?? inst._zod.def);
  if (!def || 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?.message !== void 0) {
    if (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(_, prop, receiver) {
      target ?? (target = getter());
      return Reflect.get(target, prop, receiver);
    },
    set(_, prop, value, receiver) {
      target ?? (target = getter());
      return Reflect.set(target, prop, value, receiver);
    },
    has(_, prop) {
      target ?? (target = getter());
      return Reflect.has(target, prop);
    },
    deleteProperty(_, prop) {
      target ?? (target = getter());
      return Reflect.deleteProperty(target, prop);
    },
    ownKeys(_) {
      target ?? (target = getter());
      return Reflect.ownKeys(target);
    },
    getOwnPropertyDescriptor(_, prop) {
      target ?? (target = getter());
      return Reflect.getOwnPropertyDescriptor(target, prop);
    },
    defineProperty(_, prop, descriptor) {
      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((k) => {
    return shape[k]._zod.optin === "optional" && shape[k]._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(a, b) {
  if (a._zod.def.checks?.length) {
    throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");
  }
  const def = mergeDefs(a._zod.def, {
    get shape() {
      const _shape = { ...a._zod.def.shape, ...b._zod.def.shape };
      assignProp(this, "shape", _shape);
      return _shape;
    },
    get catchall() {
      return b._zod.def.catchall;
    },
    checks: b._zod.def.checks ?? []
  });
  return clone(a, 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) {
  if (x.aborted === true)
    return true;
  for (let i = startIndex; i < x.issues.length; i++) {
    if (x.issues[i]?.continue !== true) {
      return true;
    }
  }
  return false;
}
function explicitlyAborted(x, startIndex = 0) {
  if (x.aborted === true)
    return true;
  for (let i = startIndex; i < x.issues.length; i++) {
    if (x.issues[i]?.continue === false) {
      return true;
    }
  }
  return false;
}
function prefixIssues(path16, issues) {
  return issues.map((iss) => {
    var _a4;
    (_a4 = iss).path ?? (_a4.path = []);
    iss.path.unshift(path16);
    return iss;
  });
}
function unwrapMessage(message) {
  return typeof message === "string" ? message : message?.message;
}
function finalizeIssue(iss, ctx, config2) {
  const message = iss.message ? iss.message : unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config2.customError?.(iss)) ?? unwrapMessage(config2.localeError?.(iss)) ?? "Invalid input";
  const { inst: _inst, continue: _continue, input: _input, ...rest } = iss;
  rest.path ?? (rest.path = []);
  rest.message = message;
  if (ctx?.reportInput) {
    rest.input = _input;
  }
  return rest;
}
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 t = typeof data;
  switch (t) {
    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 t;
}
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(([k, _]) => {
    return Number.isNaN(Number.parseInt(k, 10));
  }).map((el) => el[1]);
}
function base64ToUint8Array(base642) {
  const binaryString = atob(base642);
  const bytes = new Uint8Array(binaryString.length);
  for (let i = 0; i < binaryString.length; i++) {
    bytes[i] = binaryString.charCodeAt(i);
  }
  return bytes;
}
function uint8ArrayToBase64(bytes) {
  let binaryString = "";
  for (let i = 0; i < bytes.length; i++) {
    binaryString += String.fromCharCode(bytes[i]);
  }
  return btoa(binaryString);
}
function base64urlToUint8Array(base64url2) {
  const base642 = base64url2.replace(/-/g, "+").replace(/_/g, "/");
  const padding = "=".repeat((4 - base642.length % 4) % 4);
  return base64ToUint8Array(base642 + padding);
}
function uint8ArrayToBase64url(bytes) {
  return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
function hexToUint8Array(hex) {
  const cleanHex = hex.replace(/^0x/, "");
  if (cleanHex.length % 2 !== 0) {
    throw new Error("Invalid hex string length");
  }
  const bytes = new Uint8Array(cleanHex.length / 2);
  for (let i = 0; i < cleanHex.length; i += 2) {
    bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16);
  }
  return bytes;
}
function uint8ArrayToHex(bytes) {
  return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
}
var Class = class {
  constructor(..._args) {
  }
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/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(error, mapper = (issue2) => issue2.message) {
  const fieldErrors = {};
  const formErrors = [];
  for (const sub of error.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(error, mapper = (issue2) => issue2.message) {
  const fieldErrors = { _errors: [] };
  const processError = (error2, path16 = []) => {
    for (const issue2 of error2.issues) {
      if (issue2.code === "invalid_union" && issue2.errors.length) {
        issue2.errors.map((issues) => processError({ issues }, [...path16, ...issue2.path]));
      } else if (issue2.code === "invalid_key") {
        processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
      } else if (issue2.code === "invalid_element") {
        processError({ issues: issue2.issues }, [...path16, ...issue2.path]);
      } else {
        const fullpath = [...path16, ...issue2.path];
        if (fullpath.length === 0) {
          fieldErrors._errors.push(mapper(issue2));
        } else {
          let curr = fieldErrors;
          let i = 0;
          while (i < fullpath.length) {
            const el = fullpath[i];
            const terminal = i === fullpath.length - 1;
            if (!terminal) {
              curr[el] = curr[el] || { _errors: [] };
            } else {
              curr[el] = curr[el] || { _errors: [] };
              curr[el]._errors.push(mapper(issue2));
            }
            curr = curr[el];
            i++;
          }
        }
      }
    }
  };
  processError(error);
  return fieldErrors;
}

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod/v4/core/parse.js
var _parse = (_Err) => (schema, value, _ctx, _params) => {
  const ctx = _ctx ? { ..._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 e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e, _params?.callee);
    throw e;
  }
  return result.value;
};
var _parseAsync = (_Err) => async (schema, value, _ctx, params) => {
  const ctx = _ctx ? { ..._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 e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config())));
    captureStackTrace(e, params?.callee);
    throw e;
  }
  return result.value;
};
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 ?? $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 ? { ..._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 ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _parse(_Err)(schema, value, ctx);
};
var _decode = (_Err) => (schema, value, _ctx) => {
  return _parse(_Err)(schema, value, _ctx);
};
var _encodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _parseAsync(_Err)(schema, value, ctx);
};
var _decodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _parseAsync(_Err)(schema, value, _ctx);
};
var _safeEncode = (_Err) => (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _safeParse(_Err)(schema, value, ctx);
};
var _safeDecode = (_Err) => (schema, value, _ctx) => {
  return _safeParse(_Err)(schema, value, _ctx);
};
var _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => {
  const ctx = _ctx ? { ..._ctx, direction: "backward" } : { direction: "backward" };
  return _safeParseAsync(_Err)(schema, value, ctx);
};
var _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => {
  return _safeParseAsync(_Err)(schema, value, _ctx);
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod/v4/core/regexes.js
var cuid = /^[cC][0-9a-z]{6,}$/;
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 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 email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;
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 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 httpProtocol = /^https?$/;
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 time3 = 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 timeRegex = `${time3}(?:${opts.join("|")})`;
  return new RegExp(`^${dateSource}T(?:${timeRegex})$`);
}
var string = (params) => {
  const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`;
  return new RegExp(`^${regex}$`);
};
var integer = /^-?\d+$/;
var number = /^-?\d+(?:\.\d+)?$/;
var boolean = /^(?:true|false)$/i;
var lowercase = /^[^A-Z]*$/;
var uppercase = /^[^a-z]*$/;

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod/v4/core/checks.js
var $ZodCheck = /* @__PURE__ */ $constructor("$ZodCheck", (inst, def) => {
  var _a4;
  inst._zod ?? (inst._zod = {});
  inst._zod.def = def;
  (_a4 = inst._zod).onattach ?? (_a4.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) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? 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) => {
    const bag = inst2._zod.bag;
    const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? 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;
    (_a4 = inst2._zod.bag).multipleOf ?? (_a4.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) : floatSafeRemainder(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) => {
  $ZodCheck.init(inst, def);
  def.format = def.format || "float64";
  const isInt = def.format?.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 $ZodCheckMaxLength = /* @__PURE__ */ $constructor("$ZodCheckMaxLength", (inst, def) => {
  var _a4;
  $ZodCheck.init(inst, def);
  (_a4 = inst._zod.def).when ?? (_a4.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.maximum ?? 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;
  $ZodCheck.init(inst, def);
  (_a4 = inst._zod.def).when ?? (_a4.when = (payload) => {
    const val = payload.value;
    return !nullish(val) && val.length !== void 0;
  });
  inst._zod.onattach.push((inst2) => {
    const curr = inst2._zod.bag.minimum ?? 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;
  $ZodCheck.init(inst, def);
  (_a4 = inst._zod.def).when ?? (_a4.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, _b2;
  $ZodCheck.init(inst, def);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.format = def.format;
    if (def.pattern) {
      bag.patterns ?? (bag.patterns = /* @__PURE__ */ new Set());
      bag.patterns.add(def.pattern);
    }
  });
  if (def.pattern)
    (_a4 = inst._zod).check ?? (_a4.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
    (_b2 = inst._zod).check ?? (_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) => {
  def.pattern ?? (def.pattern = lowercase);
  $ZodCheckStringFormat.init(inst, def);
});
var $ZodCheckUpperCase = /* @__PURE__ */ $constructor("$ZodCheckUpperCase", (inst, def) => {
  def.pattern ?? (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) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (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) => {
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`);
  def.pattern ?? (def.pattern = pattern);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (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) => {
  $ZodCheck.init(inst, def);
  const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`);
  def.pattern ?? (def.pattern = pattern);
  inst._zod.onattach.push((inst2) => {
    const bag = inst2._zod.bag;
    bag.patterns ?? (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
    });
  };
});
var $ZodCheckOverwrite = /* @__PURE__ */ $constructor("$ZodCheckOverwrite", (inst, def) => {
  $ZodCheck.init(inst, def);
  inst._zod.check = (payload) => {
    payload.value = def.tx(payload.value);
  };
});

// packages/cli/node_modules/@modelcontextprotocol/sdk/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() {
    const F = Function;
    const args = this?.args;
    const content = this?.content ?? [``];
    const lines = [...content.map((x) => `  ${x}`)];
    return new F(...args, lines.join("\n"));
  }
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod/v4/core/versions.js
var version = {
  major: 4,
  minor: 4,
  patch: 3
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod/v4/core/schemas.js
var $ZodType = /* @__PURE__ */ $constructor("$ZodType", (inst, def) => {
  var _a4;
  inst ?? (inst = {});
  inst._zod.def = def;
  inst._zod.bag = inst._zod.bag || {};
  inst._zod.version = version;
  const checks = [...inst._zod.def.checks ?? []];
  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) {
    (_a4 = inst._zod).deferred ?? (_a4.deferred = []);
    inst._zod.deferred?.push(() => {
      inst._zod.run = inst._zod.parse;
    });
  } else {
    const runChecks = (payload, checks2, ctx) => {
      let isAborted = aborted(payload);
      let asyncResult;
      for (const ch of checks2) {
        if (ch._zod.def.when) {
          if (explicitlyAborted(payload))
            continue;
          const shouldRun = ch._zod.def.when(payload);
          if (!shouldRun)
            continue;
        } else if (isAborted) {
          continue;
        }
        const currLen = payload.issues.length;
        const _ = ch._zod.check(payload);
        if (_ instanceof Promise && ctx?.async === false) {
          throw new $ZodAsyncError();
        }
        if (asyncResult || _ instanceof Promise) {
          asyncResult = (asyncResult ?? Promise.resolve()).then(async () => {
            await _;
            const nextLen = payload.issues.length;
            if (nextLen === currLen)
              return;
            if (!isAborted)
              isAborted = aborted(payload, currLen);
          });
        } else {
          const nextLen = payload.issues.length;
          if (nextLen === currLen)
            continue;
          if (!isAborted)
            isAborted = 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) => {
      try {
        const r = safeParse(inst, value);
        return r.success ? { value: r.data } : { issues: r.error?.issues };
      } catch (_) {
        return safeParseAsync(inst, value).then((r) => r.success ? { value: r.data } : { issues: r.error?.issues });
      }
    },
    vendor: "zod",
    version: 1
  }));
});
var $ZodString = /* @__PURE__ */ $constructor("$ZodString", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = [...inst?._zod.bag?.patterns ?? []].pop() ?? string(inst._zod.bag);
  inst._zod.parse = (payload, _) => {
    if (def.coerce)
      try {
        payload.value = String(payload.value);
      } catch (_2) {
      }
    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) => {
  def.pattern ?? (def.pattern = guid);
  $ZodStringFormat.init(inst, def);
});
var $ZodUUID = /* @__PURE__ */ $constructor("$ZodUUID", (inst, def) => {
  if (def.version) {
    const versionMap = {
      v1: 1,
      v2: 2,
      v3: 3,
      v4: 4,
      v5: 5,
      v6: 6,
      v7: 7,
      v8: 8
    };
    const v = versionMap[def.version];
    if (v === void 0)
      throw new Error(`Invalid UUID version: "${def.version}"`);
    def.pattern ?? (def.pattern = uuid(v));
  } else
    def.pattern ?? (def.pattern = uuid());
  $ZodStringFormat.init(inst, def);
});
var $ZodEmail = /* @__PURE__ */ $constructor("$ZodEmail", (inst, def) => {
  def.pattern ?? (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();
      if (!def.normalize && def.protocol?.source === httpProtocol.source) {
        if (!/^https?:\/\//i.test(trimmed)) {
          payload.issues.push({
            code: "invalid_format",
            format: "url",
            note: "Invalid URL format",
            input: payload.value,
            inst,
            continue: !def.abort
          });
          return;
        }
      }
      const url = new URL(trimmed);
      if (def.hostname) {
        def.hostname.lastIndex = 0;
        if (!def.hostname.test(url.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(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.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 = url.href;
      } else {
        payload.value = trimmed;
      }
      return;
    } catch (_) {
      payload.issues.push({
        code: "invalid_format",
        format: "url",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodEmoji = /* @__PURE__ */ $constructor("$ZodEmoji", (inst, def) => {
  def.pattern ?? (def.pattern = emoji());
  $ZodStringFormat.init(inst, def);
});
var $ZodNanoID = /* @__PURE__ */ $constructor("$ZodNanoID", (inst, def) => {
  def.pattern ?? (def.pattern = nanoid);
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID = /* @__PURE__ */ $constructor("$ZodCUID", (inst, def) => {
  def.pattern ?? (def.pattern = cuid);
  $ZodStringFormat.init(inst, def);
});
var $ZodCUID2 = /* @__PURE__ */ $constructor("$ZodCUID2", (inst, def) => {
  def.pattern ?? (def.pattern = cuid2);
  $ZodStringFormat.init(inst, def);
});
var $ZodULID = /* @__PURE__ */ $constructor("$ZodULID", (inst, def) => {
  def.pattern ?? (def.pattern = ulid);
  $ZodStringFormat.init(inst, def);
});
var $ZodXID = /* @__PURE__ */ $constructor("$ZodXID", (inst, def) => {
  def.pattern ?? (def.pattern = xid);
  $ZodStringFormat.init(inst, def);
});
var $ZodKSUID = /* @__PURE__ */ $constructor("$ZodKSUID", (inst, def) => {
  def.pattern ?? (def.pattern = ksuid);
  $ZodStringFormat.init(inst, def);
});
var $ZodISODateTime = /* @__PURE__ */ $constructor("$ZodISODateTime", (inst, def) => {
  def.pattern ?? (def.pattern = datetime(def));
  $ZodStringFormat.init(inst, def);
});
var $ZodISODate = /* @__PURE__ */ $constructor("$ZodISODate", (inst, def) => {
  def.pattern ?? (def.pattern = date);
  $ZodStringFormat.init(inst, def);
});
var $ZodISOTime = /* @__PURE__ */ $constructor("$ZodISOTime", (inst, def) => {
  def.pattern ?? (def.pattern = time(def));
  $ZodStringFormat.init(inst, def);
});
var $ZodISODuration = /* @__PURE__ */ $constructor("$ZodISODuration", (inst, def) => {
  def.pattern ?? (def.pattern = duration);
  $ZodStringFormat.init(inst, def);
});
var $ZodIPv4 = /* @__PURE__ */ $constructor("$ZodIPv4", (inst, def) => {
  def.pattern ?? (def.pattern = ipv4);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv4`;
});
var $ZodIPv6 = /* @__PURE__ */ $constructor("$ZodIPv6", (inst, def) => {
  def.pattern ?? (def.pattern = ipv6);
  $ZodStringFormat.init(inst, def);
  inst._zod.bag.format = `ipv6`;
  inst._zod.check = (payload) => {
    try {
      new URL(`http://[${payload.value}]`);
    } catch {
      payload.issues.push({
        code: "invalid_format",
        format: "ipv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
var $ZodCIDRv4 = /* @__PURE__ */ $constructor("$ZodCIDRv4", (inst, def) => {
  def.pattern ?? (def.pattern = cidrv4);
  $ZodStringFormat.init(inst, def);
});
var $ZodCIDRv6 = /* @__PURE__ */ $constructor("$ZodCIDRv6", (inst, def) => {
  def.pattern ?? (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 {
      payload.issues.push({
        code: "invalid_format",
        format: "cidrv6",
        input: payload.value,
        inst,
        continue: !def.abort
      });
    }
  };
});
function isValidBase64(data) {
  if (data === "")
    return true;
  if (/\s/.test(data))
    return false;
  if (data.length % 4 !== 0)
    return false;
  try {
    atob(data);
    return true;
  } catch {
    return false;
  }
}
var $ZodBase64 = /* @__PURE__ */ $constructor("$ZodBase64", (inst, def) => {
  def.pattern ?? (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 base642 = data.replace(/[-_]/g, (c) => c === "-" ? "+" : "/");
  const padded = base642.padEnd(Math.ceil(base642.length / 4) * 4, "=");
  return isValidBase64(padded);
}
var $ZodBase64URL = /* @__PURE__ */ $constructor("$ZodBase64URL", (inst, def) => {
  def.pattern ?? (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) => {
  def.pattern ?? (def.pattern = e164);
  $ZodStringFormat.init(inst, def);
});
function isValidJWT(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?.typ !== "JWT")
      return false;
    if (!parsedHeader.alg)
      return false;
    if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm))
      return false;
    return true;
  } catch {
    return false;
  }
}
var $ZodJWT = /* @__PURE__ */ $constructor("$ZodJWT", (inst, def) => {
  $ZodStringFormat.init(inst, def);
  inst._zod.check = (payload) => {
    if (isValidJWT(payload.value, def.alg))
      return;
    payload.issues.push({
      code: "invalid_format",
      format: "jwt",
      input: payload.value,
      inst,
      continue: !def.abort
    });
  };
});
var $ZodNumber = /* @__PURE__ */ $constructor("$ZodNumber", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.pattern = inst._zod.bag.pattern ?? number;
  inst._zod.parse = (payload, _ctx) => {
    if (def.coerce)
      try {
        payload.value = Number(payload.value);
      } catch (_) {
      }
    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 (_) {
      }
    const input = payload.value;
    if (typeof input === "boolean")
      return payload;
    payload.issues.push({
      expected: "boolean",
      code: "invalid_type",
      input,
      inst
    });
    return 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;
  };
});
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 i = 0; i < input.length; i++) {
      const item = input[i];
      const result = def.element._zod.run({
        value: item,
        issues: []
      }, ctx);
      if (result instanceof Promise) {
        proms.push(result.then((result2) => handleArrayResult(result2, payload, i)));
      } else {
        handleArrayResult(result, payload, i);
      }
    }
    if (proms.length) {
      return Promise.all(proms).then(() => payload);
    }
    return payload;
  };
});
function handlePropertyResult(result, final, key, input, isOptionalIn, isOptionalOut) {
  const isPresent = key in input;
  if (result.issues.length) {
    if (isOptionalIn && isOptionalOut && !isPresent) {
      return;
    }
    final.issues.push(...prefixIssues(key, result.issues));
  }
  if (!isPresent && !isOptionalIn) {
    if (!result.issues.length) {
      final.issues.push({
        code: "invalid_type",
        expected: "nonoptional",
        input: void 0,
        path: [key]
      });
    }
    return;
  }
  if (result.value === void 0) {
    if (isPresent) {
      final.value[key] = void 0;
    }
  } else {
    final.value[key] = result.value;
  }
}
function normalizeDef(def) {
  const keys = Object.keys(def.shape);
  for (const k of keys) {
    if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) {
      throw new Error(`Invalid element at key "${k}": 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 t = _catchall.def.type;
  const isOptionalIn = _catchall.optin === "optional";
  const isOptionalOut = _catchall.optout === "optional";
  for (const key in input) {
    if (key === "__proto__")
      continue;
    if (keySet.has(key))
      continue;
    if (t === "never") {
      unrecognized.push(key);
      continue;
    }
    const r = _catchall.run({ value: input[key], issues: [] }, ctx);
    if (r instanceof Promise) {
      proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut)));
    } else {
      handlePropertyResult(r, payload, key, input, isOptionalIn, 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?.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", () => {
    const shape = def.shape;
    const propValues = {};
    for (const key in shape) {
      const field = shape[key]._zod;
      if (field.values) {
        propValues[key] ?? (propValues[key] = /* @__PURE__ */ new Set());
        for (const v of field.values)
          propValues[key].add(v);
      }
    }
    return propValues;
  });
  const isObject2 = isObject;
  const catchall = def.catchall;
  let value;
  inst._zod.parse = (payload, ctx) => {
    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 isOptionalIn = el._zod.optin === "optional";
      const isOptionalOut = el._zod.optout === "optional";
      const r = el._zod.run({ value: input[key], issues: [] }, ctx);
      if (r instanceof Promise) {
        proms.push(r.then((r2) => handlePropertyResult(r2, payload, key, input, isOptionalIn, isOptionalOut)));
      } else {
        handlePropertyResult(r, payload, key, input, isOptionalIn, 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) => {
    const doc = new Doc(["shape", "payload", "ctx"]);
    const normalized = _normalized.value;
    const parseStr = (key) => {
      const k = esc(key);
      return `shape[${k}]._zod.run({ value: input[${k}], 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 k = esc(key);
      const schema = shape[key];
      const isOptionalIn = schema?._zod?.optin === "optional";
      const isOptionalOut = schema?._zod?.optout === "optional";
      doc.write(`const ${id} = ${parseStr(key)};`);
      if (isOptionalIn && isOptionalOut) {
        doc.write(`
        if (${id}.issues.length) {
          if (${k} in input) {
            payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
              ...iss,
              path: iss.path ? [${k}, ...iss.path] : [${k}]
            })));
          }
        }
        
        if (${id}.value === undefined) {
          if (${k} in input) {
            newResult[${k}] = undefined;
          }
        } else {
          newResult[${k}] = ${id}.value;
        }
        
      `);
      } else if (!isOptionalIn) {
        doc.write(`
        const ${id}_present = ${k} in input;
        if (${id}.issues.length) {
          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${k}, ...iss.path] : [${k}]
          })));
        }
        if (!${id}_present && !${id}.issues.length) {
          payload.issues.push({
            code: "invalid_type",
            expected: "nonoptional",
            input: undefined,
            path: [${k}]
          });
        }

        if (${id}_present) {
          if (${id}.value === undefined) {
            newResult[${k}] = undefined;
          } else {
            newResult[${k}] = ${id}.value;
          }
        }

      `);
      } else {
        doc.write(`
        if (${id}.issues.length) {
          payload.issues = payload.issues.concat(${id}.issues.map(iss => ({
            ...iss,
            path: iss.path ? [${k}, ...iss.path] : [${k}]
          })));
        }
        
        if (${id}.value === undefined) {
          if (${k} in input) {
            newResult[${k}] = undefined;
          }
        } else {
          newResult[${k}] = ${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 ?? (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?.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((r) => !aborted(r));
  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((o) => o._zod.optin === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : void 0);
  defineLazy(inst._zod, "values", () => {
    if (def.options.every((o) => o._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((o) => o._zod.pattern)) {
      const patterns = def.options.map((o) => o._zod.pattern);
      return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`);
    }
    return void 0;
  });
  const first = def.options.length === 1 ? def.options[0]._zod.run : null;
  inst._zod.parse = (payload, ctx) => {
    if (first) {
      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);
    });
  };
});
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 [k, v] of Object.entries(pv)) {
        if (!propValues[k])
          propValues[k] = /* @__PURE__ */ new Set();
        for (const val of v) {
          propValues[k].add(val);
        }
      }
    }
    return propValues;
  });
  const disc = cached(() => {
    const opts = def.options;
    const map = /* @__PURE__ */ new Map();
    for (const o of opts) {
      const values = o._zod.propValues?.[def.discriminator];
      if (!values || values.size === 0)
        throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`);
      for (const v of values) {
        if (map.has(v)) {
          throw new Error(`Duplicate discriminator value "${String(v)}"`);
        }
        map.set(v, o);
      }
    }
    return map;
  });
  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?.[def.discriminator]);
    if (opt) {
      return opt._zod.run(payload, ctx);
    }
    if (def.unionFallback || ctx.direction === "backward") {
      return _super(payload, ctx);
    }
    payload.issues.push({
      code: "invalid_union",
      errors: [],
      note: "No matching discriminator",
      discriminator: def.discriminator,
      options: Array.from(disc.value.keys()),
      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 left2 = def.left._zod.run({ value: input, issues: [] }, ctx);
    const right2 = def.right._zod.run({ value: input, issues: [] }, ctx);
    const async = left2 instanceof Promise || right2 instanceof Promise;
    if (async) {
      return Promise.all([left2, right2]).then(([left3, right3]) => {
        return handleIntersectionResults(payload, left3, right3);
      });
    }
    return handleIntersectionResults(payload, left2, right2);
  };
});
function mergeValues(a, b) {
  if (a === b) {
    return { valid: true, data: a };
  }
  if (a instanceof Date && b instanceof Date && +a === +b) {
    return { valid: true, data: a };
  }
  if (isPlainObject(a) && isPlainObject(b)) {
    const bKeys = Object.keys(b);
    const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1);
    const newObj = { ...a, ...b };
    for (const key of sharedKeys) {
      const sharedValue = mergeValues(a[key], b[key]);
      if (!sharedValue.valid) {
        return {
          valid: false,
          mergeErrorPath: [key, ...sharedValue.mergeErrorPath]
        };
      }
      newObj[key] = sharedValue.data;
    }
    return { valid: true, data: newObj };
  }
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) {
      return { valid: false, mergeErrorPath: [] };
    }
    const newArray = [];
    for (let index = 0; index < a.length; index++) {
      const itemA = a[index];
      const itemB = b[index];
      const sharedValue = mergeValues(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, left2, right2) {
  const unrecKeys = /* @__PURE__ */ new Map();
  let unrecIssue;
  for (const iss of left2.issues) {
    if (iss.code === "unrecognized_keys") {
      unrecIssue ?? (unrecIssue = iss);
      for (const k of iss.keys) {
        if (!unrecKeys.has(k))
          unrecKeys.set(k, {});
        unrecKeys.get(k).l = true;
      }
    } else {
      result.issues.push(iss);
    }
  }
  for (const iss of right2.issues) {
    if (iss.code === "unrecognized_keys") {
      for (const k of iss.keys) {
        if (!unrecKeys.has(k))
          unrecKeys.set(k, {});
        unrecKeys.get(k).r = true;
      }
    } else {
      result.issues.push(iss);
    }
  }
  const bothKeys = [...unrecKeys].filter(([, f]) => f.l && f.r).map(([k]) => k);
  if (bothKeys.length && unrecIssue) {
    result.issues.push({ ...unrecIssue, keys: bothKeys });
  }
  if (aborted(result))
    return result;
  const merged = mergeValues(left2.value, right2.value);
  if (!merged.valid) {
    throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(merged.mergeErrorPath)}`);
  }
  result.value = merged.data;
  return result;
}
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 keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx);
          if (keyResult instanceof Promise) {
            throw new Error("Async schemas not supported in object keys currently");
          }
          if (keyResult.issues.length) {
            payload.issues.push({
              code: "invalid_key",
              origin: "record",
              issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())),
              input: key,
              path: [key],
              inst
            });
            continue;
          }
          const outKey = keyResult.value;
          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[outKey] = result2.value;
            }));
          } else {
            if (result.issues.length) {
              payload.issues.push(...prefixIssues(key, result.issues));
            }
            payload.value[outKey] = result.value;
          }
        }
      }
      let unrecognized;
      for (const key in input) {
        if (!recordKeys.has(key)) {
          unrecognized = 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;
        if (!Object.prototype.propertyIsEnumerable.call(input, key))
          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 $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((k) => propertyKeyTypes.has(typeof k)).map((o) => typeof o === "string" ? escapeRegex(o) : o.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((o) => typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o)).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 $ZodTransform = /* @__PURE__ */ $constructor("$ZodTransform", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  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;
        payload.fallback = true;
        return payload;
      });
    }
    if (_out instanceof Promise) {
      throw new $ZodAsyncError();
    }
    payload.value = _out;
    payload.fallback = true;
    return payload;
  };
});
function handleOptionalResult(result, input) {
  if (input === void 0 && (result.issues.length || result.fallback)) {
    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 input = payload.value;
      const result = def.innerType._zod.run(payload, ctx);
      if (result instanceof Promise)
        return result.then((r) => handleOptionalResult(r, input));
      return handleOptionalResult(result, input);
    }
    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 v = def.innerType._zod.values;
    return v ? new Set([...v].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 $ZodCatch = /* @__PURE__ */ $constructor("$ZodCatch", (inst, def) => {
  $ZodType.init(inst, def);
  inst._zod.optin = "optional";
  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 = [];
          payload.fallback = true;
        }
        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 = [];
      payload.fallback = true;
    }
    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 right2 = def.out._zod.run(payload, ctx);
      if (right2 instanceof Promise) {
        return right2.then((right3) => handlePipeResult(right3, def.in, ctx));
      }
      return handlePipeResult(right2, def.in, ctx);
    }
    const left2 = def.in._zod.run(payload, ctx);
    if (left2 instanceof Promise) {
      return left2.then((left3) => handlePipeResult(left3, def.out, ctx));
    }
    return handlePipeResult(left2, def.out, ctx);
  };
});
function handlePipeResult(left2, next, ctx) {
  if (left2.issues.length) {
    left2.aborted = true;
    return left2;
  }
  return next._zod.run({ value: left2.value, issues: left2.issues, fallback: left2.fallback }, ctx);
}
var $ZodPreprocess = /* @__PURE__ */ $constructor("$ZodPreprocess", (inst, def) => {
  $ZodPipe.init(inst, def);
});
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", () => def.innerType?._zod?.optin);
  defineLazy(inst._zod, "optout", () => def.innerType?._zod?.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 $ZodCustom = /* @__PURE__ */ $constructor("$ZodCustom", (inst, def) => {
  $ZodCheck.init(inst, def);
  $ZodType.init(inst, def);
  inst._zod.parse = (payload, _) => {
    return payload;
  };
  inst._zod.check = (payload) => {
    const input = payload.value;
    const r = def.fn(input);
    if (r instanceof Promise) {
      return r.then((r2) => handleRefineResult(r2, payload, input, inst));
    }
    handleRefineResult(r, payload, input, inst);
    return;
  };
});
function handleRefineResult(result, payload, input, inst) {
  if (!result) {
    const _iss = {
      code: "custom",
      input,
      inst,
      // incorporates params.error into issue reporting
      path: [...inst._zod.def.path ?? []],
      // 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));
  }
}

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

// packages/cli/node_modules/@modelcontextprotocol/sdk/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 _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 _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)
  });
}
// @__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 _int(Class2, params) {
  return new Class2({
    type: "number",
    check: "number_format",
    abort: false,
    format: "safeint",
    ...normalizeParams(params)
  });
}
// @__NO_SIDE_EFFECTS__
function _boolean(Class2, params) {
  return new Class2({
    type: "boolean",
    ...normalizeParams(params)
  });
}
// @__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 _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 _multipleOf(value, params) {
  return new $ZodCheckMultipleOf({
    check: "multiple_of",
    ...normalizeParams(params),
    value
  });
}
// @__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 _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 _custom(Class2, fn, _params) {
  const norm = normalizeParams(_params);
  norm.abort ?? (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, params) {
  const ch = /* @__PURE__ */ _check((payload) => {
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(issue(issue2, payload.value, ch._zod.def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_issue.inst = ch);
        _issue.continue ?? (_issue.continue = !ch._zod.def.abort);
        payload.issues.push(issue(_issue));
      }
    };
    return fn(payload.value, payload);
  }, params);
  return ch;
}
// @__NO_SIDE_EFFECTS__
function _check(fn, params) {
  const ch = new $ZodCheck({
    check: "custom",
    ...normalizeParams(params)
  });
  ch._zod.check = fn;
  return ch;
}

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod/v4/core/to-json-schema.js
function initializeContext(params) {
  let target = params?.target ?? "draft-2020-12";
  if (target === "draft-4")
    target = "draft-04";
  if (target === "draft-7")
    target = "draft-07";
  return {
    processors: params.processors ?? {},
    metadataRegistry: params?.metadata ?? globalRegistry,
    target,
    unrepresentable: params?.unrepresentable ?? "throw",
    override: params?.override ?? (() => {
    }),
    io: params?.io ?? "output",
    counter: 0,
    seen: /* @__PURE__ */ new Map(),
    cycles: params?.cycles ?? "ref",
    reused: params?.reused ?? "inline",
    external: params?.external ?? void 0
  };
}
function process2(schema, ctx, _params = { path: [], schemaPath: [] }) {
  var _a4;
  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 = schema._zod.toJSONSchema?.();
  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 meta2 = ctx.metadataRegistry.get(schema);
  if (meta2)
    Object.assign(result.schema, meta2);
  if (ctx.io === "input" && isTransforming(schema)) {
    delete result.schema.examples;
    delete result.schema.default;
  }
  if (ctx.io === "input" && "_prefault" in result.schema)
    (_a4 = result.schema).default ?? (_a4.default = result.schema._prefault);
  delete result.schema._prefault;
  const _result = ctx.seen.get(schema);
  return _result.schema;
}
function extractDefs(ctx, schema) {
  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 = ctx.metadataRegistry.get(entry[0])?.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) => {
    const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions";
    if (ctx.external) {
      const externalId = ctx.external.registry.get(entry[0])?.id;
      const uriGenerator = ctx.external.uri ?? ((id2) => id2);
      if (externalId) {
        return { ref: uriGenerator(externalId) };
      }
      const id = entry[1].defId ?? entry[1].schema.id ?? `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 = entry[1].schema.id ?? `__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: #/${seen.cycle?.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 = ctx.external.registry.get(entry[0])?.id;
      if (schema !== entry[0] && ext) {
        extractToDef(entry);
        continue;
      }
    }
    const id = ctx.metadataRegistry.get(entry[0])?.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) {
  const root = ctx.seen.get(schema);
  if (!root)
    throw new Error("Unprocessed schema. This is a bug in Zod.");
  const flattenRef = (zodSchema) => {
    const seen = ctx.seen.get(zodSchema);
    if (seen.ref === null)
      return;
    const schema2 = seen.def ?? 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 = schema2.allOf ?? [];
        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?.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: seen.path ?? []
    });
  };
  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 (ctx.external?.uri) {
    const id = ctx.external.registry.get(schema)?.id;
    if (!id)
      throw new Error("Schema is missing an `id` property");
    result.$id = ctx.external.uri(id);
  }
  Object.assign(result, root.def ?? root.schema);
  const rootMetaId = ctx.metadataRegistry.get(schema)?.id;
  if (rootMetaId !== void 0 && result.id === rootMetaId)
    delete result.id;
  const defs = ctx.external?.defs ?? {};
  for (const entry of ctx.seen.entries()) {
    const seen = entry[1];
    if (seen.def && seen.defId) {
      if (seen.def.id === seen.defId)
        delete seen.def.id;
      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 ?? { 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") {
    if (_schema._zod.traits.has("$ZodCodec"))
      return true;
    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 ?? {};
  const ctx = initializeContext({ ...libraryOptions ?? {}, target, io, processors });
  process2(schema, ctx);
  extractDefs(ctx, schema);
  return finalize(ctx, schema);
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/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) => {
  const json = _json;
  json.type = "string";
  const { minimum, maximum, format: format3, patterns, contentEncoding } = schema._zod.bag;
  if (typeof minimum === "number")
    json.minLength = minimum;
  if (typeof maximum === "number")
    json.maxLength = maximum;
  if (format3) {
    json.format = formatMap[format3] ?? format3;
    if (json.format === "")
      delete json.format;
    if (format3 === "time") {
      delete json.format;
    }
  }
  if (contentEncoding)
    json.contentEncoding = contentEncoding;
  if (patterns && patterns.size > 0) {
    const regexes = [...patterns];
    if (regexes.length === 1)
      json.pattern = regexes[0].source;
    else if (regexes.length > 1) {
      json.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 json = _json;
  const { minimum, maximum, format: format3, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag;
  if (typeof format3 === "string" && format3.includes("int"))
    json.type = "integer";
  else
    json.type = "number";
  const exMin = typeof exclusiveMinimum === "number" && exclusiveMinimum >= (minimum ?? Number.NEGATIVE_INFINITY);
  const exMax = typeof exclusiveMaximum === "number" && exclusiveMaximum <= (maximum ?? Number.POSITIVE_INFINITY);
  const legacy = ctx.target === "draft-04" || ctx.target === "openapi-3.0";
  if (exMin) {
    if (legacy) {
      json.minimum = exclusiveMinimum;
      json.exclusiveMinimum = true;
    } else {
      json.exclusiveMinimum = exclusiveMinimum;
    }
  } else if (typeof minimum === "number") {
    json.minimum = minimum;
  }
  if (exMax) {
    if (legacy) {
      json.maximum = exclusiveMaximum;
      json.exclusiveMaximum = true;
    } else {
      json.exclusiveMaximum = exclusiveMaximum;
    }
  } else if (typeof maximum === "number") {
    json.maximum = maximum;
  }
  if (typeof multipleOf === "number")
    json.multipleOf = multipleOf;
};
var booleanProcessor = (_schema, _ctx, json, _params) => {
  json.type = "boolean";
};
var neverProcessor = (_schema, _ctx, json, _params) => {
  json.not = {};
};
var unknownProcessor = (_schema, _ctx, _json, _params) => {
};
var enumProcessor = (schema, _ctx, json, _params) => {
  const def = schema._zod.def;
  const values = getEnumValues(def.entries);
  if (values.every((v) => typeof v === "number"))
    json.type = "number";
  if (values.every((v) => typeof v === "string"))
    json.type = "string";
  json.enum = values;
};
var literalProcessor = (schema, ctx, json, _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];
    json.type = val === null ? "null" : typeof val;
    if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") {
      json.enum = [val];
    } else {
      json.const = val;
    }
  } else {
    if (vals.every((v) => typeof v === "number"))
      json.type = "number";
    if (vals.every((v) => typeof v === "string"))
      json.type = "string";
    if (vals.every((v) => typeof v === "boolean"))
      json.type = "boolean";
    if (vals.every((v) => v === null))
      json.type = "null";
    json.enum = vals;
  }
};
var customProcessor = (_schema, ctx, _json, _params) => {
  if (ctx.unrepresentable === "throw") {
    throw new Error("Custom 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 arrayProcessor = (schema, ctx, _json, params) => {
  const json = _json;
  const def = schema._zod.def;
  const { minimum, maximum } = schema._zod.bag;
  if (typeof minimum === "number")
    json.minItems = minimum;
  if (typeof maximum === "number")
    json.maxItems = maximum;
  json.type = "array";
  json.items = process2(def.element, ctx, {
    ...params,
    path: [...params.path, "items"]
  });
};
var objectProcessor = (schema, ctx, _json, params) => {
  const json = _json;
  const def = schema._zod.def;
  json.type = "object";
  json.properties = {};
  const shape = def.shape;
  for (const key in shape) {
    json.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 v = def.shape[key]._zod;
    if (ctx.io === "input") {
      return v.optin === void 0;
    } else {
      return v.optout === void 0;
    }
  }));
  if (requiredKeys.size > 0) {
    json.required = Array.from(requiredKeys);
  }
  if (def.catchall?._zod.def.type === "never") {
    json.additionalProperties = false;
  } else if (!def.catchall) {
    if (ctx.io === "output")
      json.additionalProperties = false;
  } else if (def.catchall) {
    json.additionalProperties = process2(def.catchall, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
};
var unionProcessor = (schema, ctx, json, params) => {
  const def = schema._zod.def;
  const isExclusive = def.inclusive === false;
  const options = def.options.map((x, i) => process2(x, ctx, {
    ...params,
    path: [...params.path, isExclusive ? "oneOf" : "anyOf", i]
  }));
  if (isExclusive) {
    json.oneOf = options;
  } else {
    json.anyOf = options;
  }
};
var intersectionProcessor = (schema, ctx, json, params) => {
  const def = schema._zod.def;
  const a = process2(def.left, ctx, {
    ...params,
    path: [...params.path, "allOf", 0]
  });
  const b = process2(def.right, ctx, {
    ...params,
    path: [...params.path, "allOf", 1]
  });
  const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1;
  const allOf = [
    ...isSimpleIntersection(a) ? a.allOf : [a],
    ...isSimpleIntersection(b) ? b.allOf : [b]
  ];
  json.allOf = allOf;
};
var recordProcessor = (schema, ctx, _json, params) => {
  const json = _json;
  const def = schema._zod.def;
  json.type = "object";
  const keyType = def.keyType;
  const keyBag = keyType._zod.bag;
  const patterns = keyBag?.patterns;
  if (def.mode === "loose" && patterns && patterns.size > 0) {
    const valueSchema = process2(def.valueType, ctx, {
      ...params,
      path: [...params.path, "patternProperties", "*"]
    });
    json.patternProperties = {};
    for (const pattern of patterns) {
      json.patternProperties[pattern.source] = valueSchema;
    }
  } else {
    if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") {
      json.propertyNames = process2(def.keyType, ctx, {
        ...params,
        path: [...params.path, "propertyNames"]
      });
    }
    json.additionalProperties = process2(def.valueType, ctx, {
      ...params,
      path: [...params.path, "additionalProperties"]
    });
  }
  const keyValues = keyType._zod.values;
  if (keyValues) {
    const validKeyValues = [...keyValues].filter((v) => typeof v === "string" || typeof v === "number");
    if (validKeyValues.length > 0) {
      json.required = validKeyValues;
    }
  }
};
var nullableProcessor = (schema, ctx, json, 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;
    json.nullable = true;
  } else {
    json.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, json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json.default = JSON.parse(JSON.stringify(def.defaultValue));
};
var prefaultProcessor = (schema, ctx, json, 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")
    json._prefault = JSON.parse(JSON.stringify(def.defaultValue));
};
var catchProcessor = (schema, ctx, json, 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 {
    throw new Error("Dynamic catch values are not supported in JSON Schema");
  }
  json.default = catchValue;
};
var pipeProcessor = (schema, ctx, _json, params) => {
  const def = schema._zod.def;
  const inIsTransform = def.in._zod.traits.has("$ZodTransform");
  const innerType = ctx.io === "input" ? inIsTransform ? def.out : def.in : def.out;
  process2(innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = innerType;
};
var readonlyProcessor = (schema, ctx, json, params) => {
  const def = schema._zod.def;
  process2(def.innerType, ctx, params);
  const seen = ctx.seen.get(schema);
  seen.ref = def.innerType;
  json.readOnly = true;
};
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;
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-compat.js
function isZ4Schema(s) {
  const schema = s;
  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 _a4, _b2;
  if (!schema)
    return void 0;
  let rawShape;
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    rawShape = (_b2 = (_a4 = v4Schema._zod) === null || _a4 === void 0 ? void 0 : _a4.def) === null || _b2 === void 0 ? void 0 : _b2.shape;
  } else {
    const v3Schema = schema;
    rawShape = v3Schema.shape;
  }
  if (!rawShape)
    return void 0;
  if (typeof rawShape === "function") {
    try {
      return rawShape();
    } catch (_c2) {
      return void 0;
    }
  }
  return rawShape;
}
function getLiteralValue(schema) {
  var _a4;
  if (isZ4Schema(schema)) {
    const v4Schema = schema;
    const def2 = (_a4 = v4Schema._zod) === null || _a4 === void 0 ? void 0 : _a4.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;
}

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod/v4/classic/iso.js
var ZodISODateTime = /* @__PURE__ */ $constructor("ZodISODateTime", (inst, def) => {
  $ZodISODateTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function datetime2(params) {
  return _isoDateTime(ZodISODateTime, params);
}
var ZodISODate = /* @__PURE__ */ $constructor("ZodISODate", (inst, def) => {
  $ZodISODate.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function date2(params) {
  return _isoDate(ZodISODate, params);
}
var ZodISOTime = /* @__PURE__ */ $constructor("ZodISOTime", (inst, def) => {
  $ZodISOTime.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function time2(params) {
  return _isoTime(ZodISOTime, params);
}
var ZodISODuration = /* @__PURE__ */ $constructor("ZodISODuration", (inst, def) => {
  $ZodISODuration.init(inst, def);
  ZodStringFormat.init(inst, def);
});
function duration2(params) {
  return _isoDuration(ZodISODuration, params);
}

// packages/cli/node_modules/@modelcontextprotocol/sdk/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 ZodRealError = /* @__PURE__ */ $constructor("ZodError", initializer2, {
  Parent: Error
});

// packages/cli/node_modules/@modelcontextprotocol/sdk/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);

// packages/cli/node_modules/@modelcontextprotocol/sdk/node_modules/zod/v4/classic/schemas.js
var _installedGroups = /* @__PURE__ */ new WeakMap();
function _installLazyMethods(inst, group, methods) {
  const proto = Object.getPrototypeOf(inst);
  let installed = _installedGroups.get(proto);
  if (!installed) {
    installed = /* @__PURE__ */ new Set();
    _installedGroups.set(proto, installed);
  }
  if (installed.has(group))
    return;
  installed.add(group);
  for (const key in methods) {
    const fn = methods[key];
    Object.defineProperty(proto, key, {
      configurable: true,
      enumerable: false,
      get() {
        const bound = fn.bind(this);
        Object.defineProperty(this, key, {
          configurable: true,
          writable: true,
          enumerable: true,
          value: bound
        });
        return bound;
      },
      set(v) {
        Object.defineProperty(this, key, {
          configurable: true,
          writable: true,
          enumerable: true,
          value: v
        });
      }
    });
  }
}
var ZodType = /* @__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.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);
  _installLazyMethods(inst, "ZodType", {
    check(...chks) {
      const def2 = this.def;
      return this.clone(util_exports.mergeDefs(def2, {
        checks: [
          ...def2.checks ?? [],
          ...chks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch)
        ]
      }), { parent: true });
    },
    with(...chks) {
      return this.check(...chks);
    },
    clone(def2, params) {
      return clone(this, def2, params);
    },
    brand() {
      return this;
    },
    register(reg, meta2) {
      reg.add(this, meta2);
      return this;
    },
    refine(check, params) {
      return this.check(refine(check, params));
    },
    superRefine(refinement, params) {
      return this.check(superRefine(refinement, params));
    },
    overwrite(fn) {
      return this.check(_overwrite(fn));
    },
    optional() {
      return optional(this);
    },
    exactOptional() {
      return exactOptional(this);
    },
    nullable() {
      return nullable(this);
    },
    nullish() {
      return optional(nullable(this));
    },
    nonoptional(params) {
      return nonoptional(this, params);
    },
    array() {
      return array(this);
    },
    or(arg) {
      return union([this, arg]);
    },
    and(arg) {
      return intersection(this, arg);
    },
    transform(tx) {
      return pipe(this, transform(tx));
    },
    default(d) {
      return _default(this, d);
    },
    prefault(d) {
      return prefault(this, d);
    },
    catch(params) {
      return _catch(this, params);
    },
    pipe(target) {
      return pipe(this, target);
    },
    readonly() {
      return readonly(this);
    },
    describe(description) {
      const cl = this.clone();
      globalRegistry.add(cl, { description });
      return cl;
    },
    meta(...args) {
      if (args.length === 0)
        return globalRegistry.get(this);
      const cl = this.clone();
      globalRegistry.add(cl, args[0]);
      return cl;
    },
    isOptional() {
      return this.safeParse(void 0).success;
    },
    isNullable() {
      return this.safeParse(null).success;
    },
    apply(fn) {
      return fn(this);
    }
  });
  Object.defineProperty(inst, "description", {
    get() {
      return globalRegistry.get(inst)?.description;
    },
    configurable: true
  });
  return inst;
});
var _ZodString = /* @__PURE__ */ $constructor("_ZodString", (inst, def) => {
  $ZodString.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params);
  const bag = inst._zod.bag;
  inst.format = bag.format ?? null;
  inst.minLength = bag.minimum ?? null;
  inst.maxLength = bag.maximum ?? null;
  _installLazyMethods(inst, "_ZodString", {
    regex(...args) {
      return this.check(_regex(...args));
    },
    includes(...args) {
      return this.check(_includes(...args));
    },
    startsWith(...args) {
      return this.check(_startsWith(...args));
    },
    endsWith(...args) {
      return this.check(_endsWith(...args));
    },
    min(...args) {
      return this.check(_minLength(...args));
    },
    max(...args) {
      return this.check(_maxLength(...args));
    },
    length(...args) {
      return this.check(_length(...args));
    },
    nonempty(...args) {
      return this.check(_minLength(1, ...args));
    },
    lowercase(params) {
      return this.check(_lowercase(params));
    },
    uppercase(params) {
      return this.check(_uppercase(params));
    },
    trim() {
      return this.check(_trim());
    },
    normalize(...args) {
      return this.check(_normalize(...args));
    },
    toLowerCase() {
      return this.check(_toLowerCase());
    },
    toUpperCase() {
      return this.check(_toUpperCase());
    },
    slugify() {
      return this.check(_slugify());
    }
  });
});
var ZodString = /* @__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(datetime2(params));
  inst.date = (params) => inst.check(date2(params));
  inst.time = (params) => inst.check(time2(params));
  inst.duration = (params) => inst.check(duration2(params));
});
function string2(params) {
  return _string(ZodString, 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);
});
var ZodGUID = /* @__PURE__ */ $constructor("ZodGUID", (inst, def) => {
  $ZodGUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodUUID = /* @__PURE__ */ $constructor("ZodUUID", (inst, def) => {
  $ZodUUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodURL = /* @__PURE__ */ $constructor("ZodURL", (inst, def) => {
  $ZodURL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodEmoji = /* @__PURE__ */ $constructor("ZodEmoji", (inst, def) => {
  $ZodEmoji.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodNanoID = /* @__PURE__ */ $constructor("ZodNanoID", (inst, def) => {
  $ZodNanoID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodCUID = /* @__PURE__ */ $constructor("ZodCUID", (inst, def) => {
  $ZodCUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodCUID2 = /* @__PURE__ */ $constructor("ZodCUID2", (inst, def) => {
  $ZodCUID2.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodULID = /* @__PURE__ */ $constructor("ZodULID", (inst, def) => {
  $ZodULID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodXID = /* @__PURE__ */ $constructor("ZodXID", (inst, def) => {
  $ZodXID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodKSUID = /* @__PURE__ */ $constructor("ZodKSUID", (inst, def) => {
  $ZodKSUID.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodIPv4 = /* @__PURE__ */ $constructor("ZodIPv4", (inst, def) => {
  $ZodIPv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodIPv6 = /* @__PURE__ */ $constructor("ZodIPv6", (inst, def) => {
  $ZodIPv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodCIDRv4 = /* @__PURE__ */ $constructor("ZodCIDRv4", (inst, def) => {
  $ZodCIDRv4.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodCIDRv6 = /* @__PURE__ */ $constructor("ZodCIDRv6", (inst, def) => {
  $ZodCIDRv6.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodBase64 = /* @__PURE__ */ $constructor("ZodBase64", (inst, def) => {
  $ZodBase64.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodBase64URL = /* @__PURE__ */ $constructor("ZodBase64URL", (inst, def) => {
  $ZodBase64URL.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodE164 = /* @__PURE__ */ $constructor("ZodE164", (inst, def) => {
  $ZodE164.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodJWT = /* @__PURE__ */ $constructor("ZodJWT", (inst, def) => {
  $ZodJWT.init(inst, def);
  ZodStringFormat.init(inst, def);
});
var ZodNumber = /* @__PURE__ */ $constructor("ZodNumber", (inst, def) => {
  $ZodNumber.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params);
  _installLazyMethods(inst, "ZodNumber", {
    gt(value, params) {
      return this.check(_gt(value, params));
    },
    gte(value, params) {
      return this.check(_gte(value, params));
    },
    min(value, params) {
      return this.check(_gte(value, params));
    },
    lt(value, params) {
      return this.check(_lt(value, params));
    },
    lte(value, params) {
      return this.check(_lte(value, params));
    },
    max(value, params) {
      return this.check(_lte(value, params));
    },
    int(params) {
      return this.check(int(params));
    },
    safe(params) {
      return this.check(int(params));
    },
    positive(params) {
      return this.check(_gt(0, params));
    },
    nonnegative(params) {
      return this.check(_gte(0, params));
    },
    negative(params) {
      return this.check(_lt(0, params));
    },
    nonpositive(params) {
      return this.check(_lte(0, params));
    },
    multipleOf(value, params) {
      return this.check(_multipleOf(value, params));
    },
    step(value, params) {
      return this.check(_multipleOf(value, params));
    },
    finite() {
      return this;
    }
  });
  const bag = inst._zod.bag;
  inst.minValue = Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null;
  inst.maxValue = Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null;
  inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5);
  inst.isFinite = true;
  inst.format = bag.format ?? null;
});
function number2(params) {
  return _number(ZodNumber, params);
}
var ZodNumberFormat = /* @__PURE__ */ $constructor("ZodNumberFormat", (inst, def) => {
  $ZodNumberFormat.init(inst, def);
  ZodNumber.init(inst, def);
});
function int(params) {
  return _int(ZodNumberFormat, params);
}
var ZodBoolean = /* @__PURE__ */ $constructor("ZodBoolean", (inst, def) => {
  $ZodBoolean.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params);
});
function boolean2(params) {
  return _boolean(ZodBoolean, params);
}
var ZodUnknown = /* @__PURE__ */ $constructor("ZodUnknown", (inst, def) => {
  $ZodUnknown.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params);
});
function unknown() {
  return _unknown(ZodUnknown);
}
var ZodNever = /* @__PURE__ */ $constructor("ZodNever", (inst, def) => {
  $ZodNever.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params);
});
function never(params) {
  return _never(ZodNever, params);
}
var ZodArray = /* @__PURE__ */ $constructor("ZodArray", (inst, def) => {
  $ZodArray.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params);
  inst.element = def.element;
  _installLazyMethods(inst, "ZodArray", {
    min(n, params) {
      return this.check(_minLength(n, params));
    },
    nonempty(params) {
      return this.check(_minLength(1, params));
    },
    max(n, params) {
      return this.check(_maxLength(n, params));
    },
    length(n, params) {
      return this.check(_length(n, params));
    },
    unwrap() {
      return this.element;
    }
  });
});
function array(element, params) {
  return _array(ZodArray, element, params);
}
var ZodObject = /* @__PURE__ */ $constructor("ZodObject", (inst, def) => {
  $ZodObjectJIT.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params);
  util_exports.defineLazy(inst, "shape", () => {
    return def.shape;
  });
  _installLazyMethods(inst, "ZodObject", {
    keyof() {
      return _enum(Object.keys(this._zod.def.shape));
    },
    catchall(catchall) {
      return this.clone({ ...this._zod.def, catchall });
    },
    passthrough() {
      return this.clone({ ...this._zod.def, catchall: unknown() });
    },
    loose() {
      return this.clone({ ...this._zod.def, catchall: unknown() });
    },
    strict() {
      return this.clone({ ...this._zod.def, catchall: never() });
    },
    strip() {
      return this.clone({ ...this._zod.def, catchall: void 0 });
    },
    extend(incoming) {
      return util_exports.extend(this, incoming);
    },
    safeExtend(incoming) {
      return util_exports.safeExtend(this, incoming);
    },
    merge(other) {
      return util_exports.merge(this, other);
    },
    pick(mask) {
      return util_exports.pick(this, mask);
    },
    omit(mask) {
      return util_exports.omit(this, mask);
    },
    partial(...args) {
      return util_exports.partial(ZodOptional, this, args[0]);
    },
    required(...args) {
      return util_exports.required(ZodNonOptional, this, args[0]);
    }
  });
});
function object2(shape, params) {
  const def = {
    type: "object",
    shape: shape ?? {},
    ...util_exports.normalizeParams(params)
  };
  return new ZodObject(def);
}
function looseObject(shape, params) {
  return new ZodObject({
    type: "object",
    shape,
    catchall: unknown(),
    ...util_exports.normalizeParams(params)
  });
}
var ZodUnion = /* @__PURE__ */ $constructor("ZodUnion", (inst, def) => {
  $ZodUnion.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params);
  inst.options = def.options;
});
function union(options, params) {
  return new ZodUnion({
    type: "union",
    options,
    ...util_exports.normalizeParams(params)
  });
}
var ZodDiscriminatedUnion = /* @__PURE__ */ $constructor("ZodDiscriminatedUnion", (inst, def) => {
  ZodUnion.init(inst, def);
  $ZodDiscriminatedUnion.init(inst, def);
});
function discriminatedUnion(discriminator, options, params) {
  return new ZodDiscriminatedUnion({
    type: "union",
    options,
    discriminator,
    ...util_exports.normalizeParams(params)
  });
}
var ZodIntersection = /* @__PURE__ */ $constructor("ZodIntersection", (inst, def) => {
  $ZodIntersection.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params);
});
function intersection(left2, right2) {
  return new ZodIntersection({
    type: "intersection",
    left: left2,
    right: right2
  });
}
var ZodRecord = /* @__PURE__ */ $constructor("ZodRecord", (inst, def) => {
  $ZodRecord.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params);
  inst.keyType = def.keyType;
  inst.valueType = def.valueType;
});
function record(keyType, valueType, params) {
  if (!valueType || !valueType._zod) {
    return new ZodRecord({
      type: "record",
      keyType: string2(),
      valueType: keyType,
      ...util_exports.normalizeParams(valueType)
    });
  }
  return new ZodRecord({
    type: "record",
    keyType,
    valueType,
    ...util_exports.normalizeParams(params)
  });
}
var ZodEnum = /* @__PURE__ */ $constructor("ZodEnum", (inst, def) => {
  $ZodEnum.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, 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 ZodEnum({
      ...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 ZodEnum({
      ...def,
      checks: [],
      ...util_exports.normalizeParams(params),
      entries: newEntries
    });
  };
});
function _enum(values, params) {
  const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values;
  return new ZodEnum({
    type: "enum",
    entries,
    ...util_exports.normalizeParams(params)
  });
}
var ZodLiteral = /* @__PURE__ */ $constructor("ZodLiteral", (inst, def) => {
  $ZodLiteral.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, 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 ZodLiteral({
    type: "literal",
    values: Array.isArray(value) ? value : [value],
    ...util_exports.normalizeParams(params)
  });
}
var ZodTransform = /* @__PURE__ */ $constructor("ZodTransform", (inst, def) => {
  $ZodTransform.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params);
  inst._zod.parse = (payload, _ctx) => {
    if (_ctx.direction === "backward") {
      throw new $ZodEncodeError(inst.constructor.name);
    }
    payload.addIssue = (issue2) => {
      if (typeof issue2 === "string") {
        payload.issues.push(util_exports.issue(issue2, payload.value, def));
      } else {
        const _issue = issue2;
        if (_issue.fatal)
          _issue.continue = false;
        _issue.code ?? (_issue.code = "custom");
        _issue.input ?? (_issue.input = payload.value);
        _issue.inst ?? (_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;
        payload.fallback = true;
        return payload;
      });
    }
    payload.value = output;
    payload.fallback = true;
    return payload;
  };
});
function transform(fn) {
  return new ZodTransform({
    type: "transform",
    transform: fn
  });
}
var ZodOptional = /* @__PURE__ */ $constructor("ZodOptional", (inst, def) => {
  $ZodOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function optional(innerType) {
  return new ZodOptional({
    type: "optional",
    innerType
  });
}
var ZodExactOptional = /* @__PURE__ */ $constructor("ZodExactOptional", (inst, def) => {
  $ZodExactOptional.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function exactOptional(innerType) {
  return new ZodExactOptional({
    type: "optional",
    innerType
  });
}
var ZodNullable = /* @__PURE__ */ $constructor("ZodNullable", (inst, def) => {
  $ZodNullable.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nullable(innerType) {
  return new ZodNullable({
    type: "nullable",
    innerType
  });
}
var ZodDefault = /* @__PURE__ */ $constructor("ZodDefault", (inst, def) => {
  $ZodDefault.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeDefault = inst.unwrap;
});
function _default(innerType, defaultValue) {
  return new ZodDefault({
    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);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, 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);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function nonoptional(innerType, params) {
  return new ZodNonOptional({
    type: "nonoptional",
    innerType,
    ...util_exports.normalizeParams(params)
  });
}
var ZodCatch = /* @__PURE__ */ $constructor("ZodCatch", (inst, def) => {
  $ZodCatch.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params);
  inst.unwrap = () => inst._zod.def.innerType;
  inst.removeCatch = inst.unwrap;
});
function _catch(innerType, catchValue) {
  return new ZodCatch({
    type: "catch",
    innerType,
    catchValue: typeof catchValue === "function" ? catchValue : () => catchValue
  });
}
var ZodPipe = /* @__PURE__ */ $constructor("ZodPipe", (inst, def) => {
  $ZodPipe.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, 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 ZodPreprocess = /* @__PURE__ */ $constructor("ZodPreprocess", (inst, def) => {
  ZodPipe.init(inst, def);
  $ZodPreprocess.init(inst, def);
});
var ZodReadonly = /* @__PURE__ */ $constructor("ZodReadonly", (inst, def) => {
  $ZodReadonly.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params);
  inst.unwrap = () => inst._zod.def.innerType;
});
function readonly(innerType) {
  return new ZodReadonly({
    type: "readonly",
    innerType
  });
}
var ZodCustom = /* @__PURE__ */ $constructor("ZodCustom", (inst, def) => {
  $ZodCustom.init(inst, def);
  ZodType.init(inst, def);
  inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params);
});
function custom(fn, _params) {
  return _custom(ZodCustom, fn ?? (() => true), _params);
}
function refine(fn, _params = {}) {
  return _refine(ZodCustom, fn, _params);
}
function superRefine(fn, params) {
  return _superRefine(fn, params);
}
function preprocess(fn, schema) {
  return new ZodPreprocess({
    type: "pipe",
    in: transform(fn),
    out: schema
  });
}

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/types.js
var LATEST_PROTOCOL_VERSION = "2025-06-18";
var SUPPORTED_PROTOCOL_VERSIONS = [LATEST_PROTOCOL_VERSION, "2025-03-26", "2024-11-05", "2024-10-07"];
var JSONRPC_VERSION = "2.0";
var AssertObjectSchema = custom((v) => v !== null && (typeof v === "object" || typeof v === "function"));
var ProgressTokenSchema = union([string2(), number2().int()]);
var CursorSchema = string2();
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()
});
var BaseRequestParamsSchema = looseObject({
  /**
   * See [General fields: `_meta`](/specification/draft/basic/index#meta) for notes on `_meta` usage.
   */
  _meta: RequestMetaSchema.optional()
});
var RequestSchema = object2({
  method: string2(),
  params: BaseRequestParamsSchema.optional()
});
var NotificationsParamsSchema = 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: record(string2(), unknown()).optional()
});
var NotificationSchema = object2({
  method: string2(),
  params: NotificationsParamsSchema.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: record(string2(), unknown()).optional()
});
var RequestIdSchema = union([string2(), number2().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 JSONRPCResponseSchema = object2({
  jsonrpc: literal(JSONRPC_VERSION),
  id: RequestIdSchema,
  result: ResultSchema
}).strict();
var isJSONRPCResponse = (value) => JSONRPCResponseSchema.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 JSONRPCErrorSchema = object2({
  jsonrpc: literal(JSONRPC_VERSION),
  id: RequestIdSchema,
  error: object2({
    /**
     * The error type that occurred.
     */
    code: number2().int(),
    /**
     * A short description of the error. The message SHOULD be limited to a concise single sentence.
     */
    message: string2(),
    /**
     * Additional information about the error. The value of this member is defined by the sender (e.g. detailed error information, nested errors etc.).
     */
    data: optional(unknown())
  })
}).strict();
var isJSONRPCError = (value) => JSONRPCErrorSchema.safeParse(value).success;
var JSONRPCMessageSchema = union([JSONRPCRequestSchema, JSONRPCNotificationSchema, JSONRPCResponseSchema, JSONRPCErrorSchema]);
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,
  /**
   * An optional string describing the reason for the cancellation. This MAY be logged or presented to the user.
   */
  reason: string2().optional()
});
var CancelledNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/cancelled"),
  params: CancelledNotificationParamsSchema
});
var IconSchema = object2({
  /**
   * URL or data URI for the icon.
   */
  src: string2(),
  /**
   * Optional MIME type for the icon.
   */
  mimeType: string2().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(string2()).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: string2(),
  /**
   * 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: string2().optional()
});
var ImplementationSchema = BaseMetadataSchema.extend({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  version: string2(),
  /**
   * An optional URL of the website for this implementation.
   */
  websiteUrl: string2().optional()
});
var FormElicitationCapabilitySchema = intersection(object2({
  applyDefaults: boolean2().optional()
}), record(string2(), 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(string2(), unknown()).optional()));
var ClientCapabilitiesSchema = object2({
  /**
   * Experimental, non-standard capabilities that the client supports.
   */
  experimental: record(string2(), 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: boolean2().optional()
  }).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: string2(),
  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(string2(), 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: optional(object2({
    /**
     * Whether this server supports issuing notifications for changes to the prompt list.
     */
    listChanged: optional(boolean2())
  })),
  /**
   * Present if the server offers any resources to read.
   */
  resources: object2({
    /**
     * Whether this server supports clients subscribing to resource updates.
     */
    subscribe: boolean2().optional(),
    /**
     * Whether this server supports issuing notifications for changes to the resource list.
     */
    listChanged: boolean2().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: boolean2().optional()
  }).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: string2(),
  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: string2().optional()
});
var InitializedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/initialized")
});
var PingRequestSchema = RequestSchema.extend({
  method: literal("ping")
});
var ProgressSchema = object2({
  /**
   * The progress thus far. This should increase every time progress is made, even if the total is unknown.
   */
  progress: number2(),
  /**
   * Total number of items to process (or total progress required), if known.
   */
  total: optional(number2()),
  /**
   * An optional message describing the current progress.
   */
  message: optional(string2())
});
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: optional(CursorSchema)
});
var ResourceContentsSchema = object2({
  /**
   * The URI of this resource.
   */
  uri: string2(),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optional(string2()),
  /**
   * 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(string2(), 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: string2()
});
var Base64Schema = string2().refine((val) => {
  try {
    atob(val);
    return true;
  } catch (_a4) {
    return false;
  }
}, { message: "Invalid Base64 string" });
var BlobResourceContentsSchema = ResourceContentsSchema.extend({
  /**
   * A base64-encoded string representing the binary data of the item.
   */
  blob: Base64Schema
});
var ResourceSchema = object2({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * The URI of this resource.
   */
  uri: string2(),
  /**
   * 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(string2()),
  /**
   * The MIME type of this resource, if known.
   */
  mimeType: optional(string2()),
  /**
   * 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: string2(),
  /**
   * 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(string2()),
  /**
   * 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(string2()),
  /**
   * 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: string2()
});
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")
});
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: string2()
});
var ResourceUpdatedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/resources/updated"),
  params: ResourceUpdatedNotificationParamsSchema
});
var PromptArgumentSchema = object2({
  /**
   * The name of the argument.
   */
  name: string2(),
  /**
   * A human-readable description of the argument.
   */
  description: optional(string2()),
  /**
   * Whether this argument must be provided.
   */
  required: optional(boolean2())
});
var PromptSchema = object2({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * An optional description of what this prompt provides
   */
  description: optional(string2()),
  /**
   * 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: string2(),
  /**
   * Arguments to use for templating the prompt.
   */
  arguments: record(string2(), string2()).optional()
});
var GetPromptRequestSchema = RequestSchema.extend({
  method: literal("prompts/get"),
  params: GetPromptRequestParamsSchema
});
var TextContentSchema = object2({
  type: literal("text"),
  /**
   * The text content of the message.
   */
  text: string2(),
  /**
   * 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(string2(), 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: string2(),
  /**
   * 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(string2(), 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: string2(),
  /**
   * 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(string2(), 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: string2(),
  /**
   * Unique identifier for this tool call.
   * Used to correlate with ToolResultContent in subsequent messages.
   */
  id: string2(),
  /**
   * Arguments to pass to the tool.
   * Must conform to the tool's inputSchema.
   */
  input: object2({}).passthrough(),
  /**
   * 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(object2({}).passthrough())
}).passthrough();
var EmbeddedResourceSchema = object2({
  type: literal("resource"),
  resource: union([TextResourceContentsSchema, BlobResourceContentsSchema]),
  /**
   * 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(string2(), unknown()).optional()
});
var ResourceLinkSchema = ResourceSchema.extend({
  type: literal("resource_link")
});
var ContentBlockSchema = union([
  TextContentSchema,
  ImageContentSchema,
  AudioContentSchema,
  ResourceLinkSchema,
  EmbeddedResourceSchema
]);
var PromptMessageSchema = object2({
  role: _enum(["user", "assistant"]),
  content: ContentBlockSchema
});
var GetPromptResultSchema = ResultSchema.extend({
  /**
   * An optional description for the prompt.
   */
  description: optional(string2()),
  messages: array(PromptMessageSchema)
});
var PromptListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/prompts/list_changed")
});
var ToolAnnotationsSchema = object2({
  /**
   * A human-readable title for the tool.
   */
  title: string2().optional(),
  /**
   * If true, the tool does not modify its environment.
   *
   * Default: false
   */
  readOnlyHint: boolean2().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: boolean2().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: boolean2().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: boolean2().optional()
});
var ToolSchema = object2({
  ...BaseMetadataSchema.shape,
  ...IconsSchema.shape,
  /**
   * A human-readable description of the tool.
   */
  description: string2().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(string2(), AssertObjectSchema).optional(),
    required: array(string2()).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(string2(), AssertObjectSchema).optional(),
    required: array(string2()).optional()
  }).catchall(unknown()).optional(),
  /**
   * Optional additional tool information.
   */
  annotations: optional(ToolAnnotationsSchema),
  /**
   * 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(string2(), 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(string2(), 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: optional(boolean2())
});
var CompatibilityCallToolResultSchema = CallToolResultSchema.or(ResultSchema.extend({
  toolResult: unknown()
}));
var CallToolRequestParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * The name of the tool to call.
   */
  name: string2(),
  /**
   * Arguments to pass to the tool.
   */
  arguments: optional(record(string2(), unknown()))
});
var CallToolRequestSchema = RequestSchema.extend({
  method: literal("tools/call"),
  params: CallToolRequestParamsSchema
});
var ToolListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/tools/list_changed")
});
var LoggingLevelSchema = _enum(["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: string2().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: string2().optional()
});
var ModelPreferencesSchema = object2({
  /**
   * Optional hints to use for model selection.
   */
  hints: optional(array(ModelHintSchema)),
  /**
   * How much to prioritize cost when selecting a model.
   */
  costPriority: optional(number2().min(0).max(1)),
  /**
   * How much to prioritize sampling speed (latency) when selecting a model.
   */
  speedPriority: optional(number2().min(0).max(1)),
  /**
   * How much to prioritize intelligence and capabilities when selecting a model.
   */
  intelligencePriority: optional(number2().min(0).max(1))
});
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: optional(_enum(["auto", "required", "none"]))
});
var ToolResultContentSchema = object2({
  type: literal("tool_result"),
  toolUseId: string2().describe("The unique identifier for the corresponding tool call."),
  content: array(ContentBlockSchema).default([]),
  structuredContent: object2({}).passthrough().optional(),
  isError: optional(boolean2()),
  /**
   * 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(object2({}).passthrough())
}).passthrough();
var SamplingMessageContentBlockSchema = discriminatedUnion("type", [
  TextContentSchema,
  ImageContentSchema,
  AudioContentSchema,
  ToolUseContentSchema,
  ToolResultContentSchema
]);
var SamplingMessageSchema = object2({
  role: _enum(["user", "assistant"]),
  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: optional(object2({}).passthrough())
}).passthrough();
var CreateMessageRequestParamsSchema = BaseRequestParamsSchema.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: string2().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: _enum(["none", "thisServer", "allServers"]).optional(),
  temperature: number2().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: number2().int(),
  stopSequences: array(string2()).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: optional(array(ToolSchema)),
  /**
   * 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: optional(ToolChoiceSchema)
});
var CreateMessageRequestSchema = RequestSchema.extend({
  method: literal("sampling/createMessage"),
  params: CreateMessageRequestParamsSchema
});
var CreateMessageResultSchema = ResultSchema.extend({
  /**
   * The name of the model that generated the message.
   */
  model: string2(),
  /**
   * 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(_enum(["endTurn", "stopSequence", "maxTokens", "toolUse"]).or(string2())),
  role: _enum(["user", "assistant"]),
  /**
   * Response content. May be ToolUseContent if stopReason is "toolUse".
   */
  content: union([SamplingMessageContentBlockSchema, array(SamplingMessageContentBlockSchema)])
});
var BooleanSchemaSchema = object2({
  type: literal("boolean"),
  title: string2().optional(),
  description: string2().optional(),
  default: boolean2().optional()
});
var StringSchemaSchema = object2({
  type: literal("string"),
  title: string2().optional(),
  description: string2().optional(),
  minLength: number2().optional(),
  maxLength: number2().optional(),
  format: _enum(["email", "uri", "date", "date-time"]).optional(),
  default: string2().optional()
});
var NumberSchemaSchema = object2({
  type: _enum(["number", "integer"]),
  title: string2().optional(),
  description: string2().optional(),
  minimum: number2().optional(),
  maximum: number2().optional(),
  default: number2().optional()
});
var UntitledSingleSelectEnumSchemaSchema = object2({
  type: literal("string"),
  title: string2().optional(),
  description: string2().optional(),
  enum: array(string2()),
  default: string2().optional()
});
var TitledSingleSelectEnumSchemaSchema = object2({
  type: literal("string"),
  title: string2().optional(),
  description: string2().optional(),
  oneOf: array(object2({
    const: string2(),
    title: string2()
  })),
  default: string2().optional()
});
var LegacyTitledEnumSchemaSchema = object2({
  type: literal("string"),
  title: string2().optional(),
  description: string2().optional(),
  enum: array(string2()),
  enumNames: array(string2()).optional(),
  default: string2().optional()
});
var SingleSelectEnumSchemaSchema = union([UntitledSingleSelectEnumSchemaSchema, TitledSingleSelectEnumSchemaSchema]);
var UntitledMultiSelectEnumSchemaSchema = object2({
  type: literal("array"),
  title: string2().optional(),
  description: string2().optional(),
  minItems: number2().optional(),
  maxItems: number2().optional(),
  items: object2({
    type: literal("string"),
    enum: array(string2())
  }),
  default: array(string2()).optional()
});
var TitledMultiSelectEnumSchemaSchema = object2({
  type: literal("array"),
  title: string2().optional(),
  description: string2().optional(),
  minItems: number2().optional(),
  maxItems: number2().optional(),
  items: object2({
    anyOf: array(object2({
      const: string2(),
      title: string2()
    }))
  }),
  default: array(string2()).optional()
});
var MultiSelectEnumSchemaSchema = union([UntitledMultiSelectEnumSchemaSchema, TitledMultiSelectEnumSchemaSchema]);
var EnumSchemaSchema = union([LegacyTitledEnumSchemaSchema, SingleSelectEnumSchemaSchema, MultiSelectEnumSchemaSchema]);
var PrimitiveSchemaDefinitionSchema = union([EnumSchemaSchema, BooleanSchemaSchema, StringSchemaSchema, NumberSchemaSchema]);
var ElicitRequestFormParamsSchema = BaseRequestParamsSchema.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: string2(),
  /**
   * A restricted subset of JSON Schema.
   * Only top-level properties are allowed, without nesting.
   */
  requestedSchema: object2({
    type: literal("object"),
    properties: record(string2(), PrimitiveSchemaDefinitionSchema),
    required: array(string2()).optional()
  })
});
var ElicitRequestURLParamsSchema = BaseRequestParamsSchema.extend({
  /**
   * The elicitation mode.
   */
  mode: literal("url"),
  /**
   * The message to present to the user explaining why the interaction is needed.
   */
  message: string2(),
  /**
   * 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: string2(),
  /**
   * The URL that the user should navigate to.
   */
  url: string2().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: string2()
});
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: _enum(["accept", "decline", "cancel"]),
  /**
   * The submitted form data, only present when action is "accept".
   * Contains values matching the requested schema.
   */
  content: record(string2(), union([string2(), number2(), boolean2(), array(string2())])).optional()
});
var ResourceTemplateReferenceSchema = object2({
  type: literal("ref/resource"),
  /**
   * The URI or URI template of the resource.
   */
  uri: string2()
});
var PromptReferenceSchema = object2({
  type: literal("ref/prompt"),
  /**
   * The name of the prompt or prompt template
   */
  name: string2()
});
var CompleteRequestParamsSchema = BaseRequestParamsSchema.extend({
  ref: union([PromptReferenceSchema, ResourceTemplateReferenceSchema]),
  /**
   * The argument's information
   */
  argument: object2({
    /**
     * The name of the argument
     */
    name: string2(),
    /**
     * The value of the argument to use for completion matching.
     */
    value: string2()
  }),
  context: object2({
    /**
     * Previously-resolved variables in a URI template or prompt.
     */
    arguments: record(string2(), string2()).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(string2()).max(100),
    /**
     * The total number of completion options available. This can exceed the number of values actually sent in the response.
     */
    total: optional(number2().int()),
    /**
     * Indicates whether there are additional completion options beyond those provided in the current response, even if the exact total is unknown.
     */
    hasMore: optional(boolean2())
  })
});
var RootSchema = object2({
  /**
   * The URI identifying the root. This *must* start with file:// for now.
   */
  uri: string2().startsWith("file://"),
  /**
   * An optional name for the root.
   */
  name: string2().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(string2(), unknown()).optional()
});
var ListRootsRequestSchema = RequestSchema.extend({
  method: literal("roots/list")
});
var ListRootsResultSchema = ResultSchema.extend({
  roots: array(RootSchema)
});
var RootsListChangedNotificationSchema = NotificationSchema.extend({
  method: literal("notifications/roots/list_changed")
});
var ClientRequestSchema = union([
  PingRequestSchema,
  InitializeRequestSchema,
  CompleteRequestSchema,
  SetLevelRequestSchema,
  GetPromptRequestSchema,
  ListPromptsRequestSchema,
  ListResourcesRequestSchema,
  ListResourceTemplatesRequestSchema,
  ReadResourceRequestSchema,
  SubscribeRequestSchema,
  UnsubscribeRequestSchema,
  CallToolRequestSchema,
  ListToolsRequestSchema
]);
var ClientNotificationSchema = union([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  InitializedNotificationSchema,
  RootsListChangedNotificationSchema
]);
var ClientResultSchema = union([EmptyResultSchema, CreateMessageResultSchema, ElicitResultSchema, ListRootsResultSchema]);
var ServerRequestSchema = union([PingRequestSchema, CreateMessageRequestSchema, ElicitRequestSchema, ListRootsRequestSchema]);
var ServerNotificationSchema = union([
  CancelledNotificationSchema,
  ProgressNotificationSchema,
  LoggingMessageNotificationSchema,
  ResourceUpdatedNotificationSchema,
  ResourceListChangedNotificationSchema,
  ToolListChangedNotificationSchema,
  PromptListChangedNotificationSchema,
  ElicitationCompleteNotificationSchema
]);
var ServerResultSchema = union([
  EmptyResultSchema,
  InitializeResultSchema,
  CompleteResultSchema,
  GetPromptResultSchema,
  ListPromptsResultSchema,
  ListResourcesResultSchema,
  ListResourceTemplatesResultSchema,
  ReadResourceResultSchema,
  CallToolResultSchema,
  ListToolsResultSchema
]);
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 _a4, _b2;
    return (_b2 = (_a4 = this.data) === null || _a4 === void 0 ? void 0 : _a4.elicitations) !== null && _b2 !== void 0 ? _b2 : [];
  }
};

// packages/cli/node_modules/@modelcontextprotocol/sdk/dist/esm/server/zod-json-schema-compat.js
function getMethodLiteral(schema) {
  const shape = getObjectShape(schema);
  const methodSchema = shape === null || shape === void 0 ? 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;
}

// packages/cli/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.setNotificationHandler(CancelledNotificationSchema, (notification) => {
      const controller = this._requestHandlerAbortControllers.get(notification.params.requestId);
      controller === null || controller === void 0 ? void 0 : controller.abort(notification.params.reason);
    });
    this.setNotificationHandler(ProgressNotificationSchema, (notification) => {
      this._onprogress(notification);
    });
    this.setRequestHandler(
      PingRequestSchema,
      // Automatic pong by default.
      (_request) => ({})
    );
  }
  _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 _a4, _b2, _c2;
    this._transport = transport;
    const _onclose = (_a4 = this.transport) === null || _a4 === void 0 ? void 0 : _a4.onclose;
    this._transport.onclose = () => {
      _onclose === null || _onclose === void 0 ? void 0 : _onclose();
      this._onclose();
    };
    const _onerror = (_b2 = this.transport) === null || _b2 === void 0 ? void 0 : _b2.onerror;
    this._transport.onerror = (error) => {
      _onerror === null || _onerror === void 0 ? void 0 : _onerror(error);
      this._onerror(error);
    };
    const _onmessage = (_c2 = this._transport) === null || _c2 === void 0 ? void 0 : _c2.onmessage;
    this._transport.onmessage = (message, extra) => {
      _onmessage === null || _onmessage === void 0 ? void 0 : _onmessage(message, extra);
      if (isJSONRPCResponse(message) || isJSONRPCError(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 _a4;
    const responseHandlers = this._responseHandlers;
    this._responseHandlers = /* @__PURE__ */ new Map();
    this._progressHandlers.clear();
    this._pendingDebouncedNotifications.clear();
    this._transport = void 0;
    (_a4 = this.onclose) === null || _a4 === void 0 ? void 0 : _a4.call(this);
    const error = McpError.fromError(ErrorCode.ConnectionClosed, "Connection closed");
    for (const handler of responseHandlers.values()) {
      handler(error);
    }
  }
  _onerror(error) {
    var _a4;
    (_a4 = this.onerror) === null || _a4 === void 0 ? void 0 : _a4.call(this, error);
  }
  _onnotification(notification) {
    var _a4;
    const handler = (_a4 = this._notificationHandlers.get(notification.method)) !== null && _a4 !== void 0 ? _a4 : this.fallbackNotificationHandler;
    if (handler === void 0) {
      return;
    }
    Promise.resolve().then(() => handler(notification)).catch((error) => this._onerror(new Error(`Uncaught error in notification handler: ${error}`)));
  }
  _onrequest(request, extra) {
    var _a4, _b2;
    const handler = (_a4 = this._requestHandlers.get(request.method)) !== null && _a4 !== void 0 ? _a4 : this.fallbackRequestHandler;
    const capturedTransport = this._transport;
    if (handler === void 0) {
      capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
        jsonrpc: "2.0",
        id: request.id,
        error: {
          code: ErrorCode.MethodNotFound,
          message: "Method not found"
        }
      }).catch((error) => this._onerror(new Error(`Failed to send an error response: ${error}`)));
      return;
    }
    const abortController = new AbortController();
    this._requestHandlerAbortControllers.set(request.id, abortController);
    const fullExtra = {
      signal: abortController.signal,
      sessionId: capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.sessionId,
      _meta: (_b2 = request.params) === null || _b2 === void 0 ? void 0 : _b2._meta,
      sendNotification: (notification) => this.notification(notification, { relatedRequestId: request.id }),
      sendRequest: (r, resultSchema, options) => this.request(r, resultSchema, { ...options, relatedRequestId: request.id }),
      authInfo: extra === null || extra === void 0 ? void 0 : extra.authInfo,
      requestId: request.id,
      requestInfo: extra === null || extra === void 0 ? void 0 : extra.requestInfo
    };
    Promise.resolve().then(() => handler(request, fullExtra)).then((result) => {
      if (abortController.signal.aborted) {
        return;
      }
      return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
        result,
        jsonrpc: "2.0",
        id: request.id
      });
    }, (error) => {
      var _a5;
      if (abortController.signal.aborted) {
        return;
      }
      return capturedTransport === null || capturedTransport === void 0 ? void 0 : capturedTransport.send({
        jsonrpc: "2.0",
        id: request.id,
        error: {
          code: Number.isSafeInteger(error["code"]) ? error["code"] : ErrorCode.InternalError,
          message: (_a5 = error.message) !== null && _a5 !== void 0 ? _a5 : "Internal error",
          ...error["data"] !== void 0 && { data: error["data"] }
        }
      });
    }).catch((error) => this._onerror(new Error(`Failed to send response: ${error}`))).finally(() => {
      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 (error) {
        responseHandler(error);
        return;
      }
    }
    handler(params);
  }
  _onresponse(response) {
    const messageId = Number(response.id);
    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._progressHandlers.delete(messageId);
    this._cleanupTimeout(messageId);
    if (isJSONRPCResponse(response)) {
      handler(response);
    } else {
      const error = McpError.fromError(response.error.code, response.error.message, response.error.data);
      handler(error);
    }
  }
  get transport() {
    return this._transport;
  }
  /**
   * Closes the connection.
   */
  async close() {
    var _a4;
    await ((_a4 = this._transport) === null || _a4 === void 0 ? void 0 : _a4.close());
  }
  /**
   * Sends a request and wait for a response.
   *
   * Do not use this method to emit notifications! Use notification() instead.
   */
  request(request, resultSchema, options) {
    const { relatedRequestId, resumptionToken, onresumptiontoken } = options !== null && options !== void 0 ? options : {};
    return new Promise((resolve9, reject) => {
      var _a4, _b2, _c2, _d, _e, _f;
      if (!this._transport) {
        reject(new Error("Not connected"));
        return;
      }
      if (((_a4 = this._options) === null || _a4 === void 0 ? void 0 : _a4.enforceStrictCapabilities) === true) {
        this.assertCapabilityForMethod(request.method);
      }
      (_b2 = options === null || options === void 0 ? void 0 : options.signal) === null || _b2 === void 0 ? void 0 : _b2.throwIfAborted();
      const messageId = this._requestMessageId++;
      const jsonrpcRequest = {
        ...request,
        jsonrpc: "2.0",
        id: messageId
      };
      if (options === null || options === void 0 ? void 0 : options.onprogress) {
        this._progressHandlers.set(messageId, options.onprogress);
        jsonrpcRequest.params = {
          ...request.params,
          _meta: {
            ...((_c2 = request.params) === null || _c2 === void 0 ? void 0 : _c2._meta) || {},
            progressToken: messageId
          }
        };
      }
      const cancel = (reason) => {
        var _a5;
        this._responseHandlers.delete(messageId);
        this._progressHandlers.delete(messageId);
        this._cleanupTimeout(messageId);
        (_a5 = this._transport) === null || _a5 === void 0 ? void 0 : _a5.send({
          jsonrpc: "2.0",
          method: "notifications/cancelled",
          params: {
            requestId: messageId,
            reason: String(reason)
          }
        }, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => this._onerror(new Error(`Failed to send cancellation: ${error}`)));
        reject(reason);
      };
      this._responseHandlers.set(messageId, (response) => {
        var _a5;
        if ((_a5 = options === null || options === void 0 ? void 0 : options.signal) === null || _a5 === void 0 ? void 0 : _a5.aborted) {
          return;
        }
        if (response instanceof Error) {
          return reject(response);
        }
        try {
          const parseResult = safeParse2(resultSchema, response.result);
          if (!parseResult.success) {
            reject(parseResult.error);
          } else {
            resolve9(parseResult.data);
          }
        } catch (error) {
          reject(error);
        }
      });
      (_d = options === null || options === void 0 ? void 0 : options.signal) === null || _d === void 0 ? void 0 : _d.addEventListener("abort", () => {
        var _a5;
        cancel((_a5 = options === null || options === void 0 ? void 0 : options.signal) === null || _a5 === void 0 ? void 0 : _a5.reason);
      });
      const timeout = (_e = options === null || options === void 0 ? void 0 : options.timeout) !== null && _e !== void 0 ? _e : DEFAULT_REQUEST_TIMEOUT_MSEC;
      const timeoutHandler = () => cancel(McpError.fromError(ErrorCode.RequestTimeout, "Request timed out", { timeout }));
      this._setupTimeout(messageId, timeout, options === null || options === void 0 ? void 0 : options.maxTotalTimeout, timeoutHandler, (_f = options === null || options === void 0 ? void 0 : options.resetTimeoutOnProgress) !== null && _f !== void 0 ? _f : false);
      this._transport.send(jsonrpcRequest, { relatedRequestId, resumptionToken, onresumptiontoken }).catch((error) => {
        this._cleanupTimeout(messageId);
        reject(error);
      });
    });
  }
  /**
   * Emits a notification, which is a one-way message that does not expect a response.
   */
  async notification(notification, options) {
    var _a4, _b2;
    if (!this._transport) {
      throw new Error("Not connected");
    }
    this.assertNotificationCapability(notification.method);
    const debouncedMethods = (_b2 = (_a4 = this._options) === null || _a4 === void 0 ? void 0 : _a4.debouncedNotificationMethods) !== null && _b2 !== void 0 ? _b2 : [];
    const canDebounce = debouncedMethods.includes(notification.method) && !notification.params && !(options === null || options === void 0 ? void 0 : options.relatedRequestId);
    if (canDebounce) {
      if (this._pendingDebouncedNotifications.has(notification.method)) {
        return;
      }
      this._pendingDebouncedNotifications.add(notification.method);
      Promise.resolve().then(() => {
        var _a5;
        this._pendingDebouncedNotifications.delete(notification.method);
        if (!this._transport) {
          return;
        }
        const jsonrpcNotification2 = {
          ...notification,
          jsonrpc: "2.0"
        };
        (_a5 = this._transport) === null || _a5 === void 0 ? void 0 : _a5.send(jsonrpcNotification2, options).catch((error) => this._onerror(error));
      });
      return;
    }
    const jsonrpcNotification = {
      ...notification,
      jsonrpc: "2.0"
    };
    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);
  }
};
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 k = key;
    const addValue = additional[k];
    if (addValue === void 0)
      continue;
    const baseValue = result[k];
    if (isPlainObject2(baseValue) && isPlainObject2(addValue)) {
      result[k] = { ...baseValue, ...addValue };
    } else {
      result[k] = addValue;
    }
  }
  return result;
}

// packages/cli/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.Ajv({
    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 !== void 0 ? 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 _a4;
    const ajvValidator = "$id" in schema && typeof schema.$id === "string" ? (_a4 = this._ajv.getSchema(schema.$id)) !== null && _a4 !== void 0 ? _a4 : 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)
        };
      }
    };
  }
};

// packages/cli/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) {
      applyElicitationDefaults(sub, data);
    }
  }
  if (Array.isArray(schema.oneOf)) {
    for (const sub of schema.oneOf) {
      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 _a4, _b2;
    super(options);
    this._clientInfo = _clientInfo;
    this._cachedToolOutputValidators = /* @__PURE__ */ new Map();
    this._capabilities = (_a4 = options === null || options === void 0 ? void 0 : options.capabilities) !== null && _a4 !== void 0 ? _a4 : {};
    this._jsonSchemaValidator = (_b2 = options === null || options === void 0 ? void 0 : options.jsonSchemaValidator) !== null && _b2 !== void 0 ? _b2 : new AjvJsonSchemaValidator();
  }
  /**
   * 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 _a4, _b2, _c2;
    const shape = getObjectShape(requestSchema);
    const methodSchema = shape === null || shape === void 0 ? 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 = (_a4 = v4Schema._zod) === null || _a4 === void 0 ? void 0 : _a4.def;
      methodValue = (_b2 = v4Def === null || v4Def === void 0 ? void 0 : v4Def.value) !== null && _b2 !== void 0 ? _b2 : v4Schema.value;
    } else {
      const v3Schema = methodSchema;
      const legacyDef = v3Schema._def;
      methodValue = (_c2 = legacyDef === null || legacyDef === void 0 ? void 0 : legacyDef.value) !== null && _c2 !== void 0 ? _c2 : 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 _a5, _b3, _c3;
        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;
        const mode = (_a5 = params.mode) !== null && _a5 !== void 0 ? _a5 : "form";
        const { supportsFormMode, supportsUrlMode } = getSupportedElicitationModes(this._capabilities.elicitation);
        if (mode === "form" && !supportsFormMode) {
          throw new McpError(ErrorCode.InvalidParams, "Client does not support form-mode elicitation requests");
        }
        if (mode === "url" && !supportsUrlMode) {
          throw new McpError(ErrorCode.InvalidParams, "Client does not support URL-mode elicitation requests");
        }
        const result = await Promise.resolve(handler(request, extra));
        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 = mode === "form" ? params.requestedSchema : void 0;
        if (mode === "form" && validatedResult.action === "accept" && validatedResult.content && requestedSchema) {
          if ((_c3 = (_b3 = this._capabilities.elicitation) === null || _b3 === void 0 ? void 0 : _b3.form) === null || _c3 === void 0 ? void 0 : _c3.applyDefaults) {
            try {
              applyElicitationDefaults(requestedSchema, validatedResult.content);
            } catch (_d) {
            }
          }
        }
        return validatedResult;
      };
      return super.setRequestHandler(requestSchema, wrappedHandler);
    }
    return super.setRequestHandler(requestSchema, handler);
  }
  assertCapability(capability, method) {
    var _a4;
    if (!((_a4 = this._serverCapabilities) === null || _a4 === void 0 ? void 0 : _a4[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"
      });
    } catch (error) {
      void this.close();
      throw error;
    }
  }
  /**
   * 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 _a4, _b2, _c2, _d, _e;
    switch (method) {
      case "logging/setLevel":
        if (!((_a4 = this._serverCapabilities) === null || _a4 === void 0 ? void 0 : _a4.logging)) {
          throw new Error(`Server does not support logging (required for ${method})`);
        }
        break;
      case "prompts/get":
      case "prompts/list":
        if (!((_b2 = this._serverCapabilities) === null || _b2 === void 0 ? 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 (!((_c2 = this._serverCapabilities) === null || _c2 === void 0 ? void 0 : _c2.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 (!((_d = this._serverCapabilities) === null || _d === void 0 ? void 0 : _d.tools)) {
          throw new Error(`Server does not support tools (required for ${method})`);
        }
        break;
      case "completion/complete":
        if (!((_e = this._serverCapabilities) === null || _e === void 0 ? 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 _a4;
    switch (method) {
      case "notifications/roots/list_changed":
        if (!((_a4 = this._capabilities.roots) === null || _a4 === void 0 ? void 0 : _a4.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) {
    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 "ping":
        break;
    }
  }
  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);
  }
  async callTool(params, resultSchema = CallToolResultSchema, options) {
    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 (error) {
          if (error instanceof McpError) {
            throw error;
          }
          throw new McpError(ErrorCode.InvalidParams, `Failed to validate structured content: ${error instanceof Error ? error.message : String(error)}`);
        }
      }
    }
    return result;
  }
  /**
   * Cache validators for tool output schemas.
   * Called after listTools() to pre-compile validators for better performance.
   */
  cacheToolOutputSchemas(tools) {
    this._cachedToolOutputValidators.clear();
    for (const tool of tools) {
      if (tool.outputSchema) {
        const toolValidator = this._jsonSchemaValidator.getValidator(tool.outputSchema);
        this._cachedToolOutputValidators.set(tool.name, toolValidator);
      }
    }
  }
  /**
   * 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.cacheToolOutputSchemas(result.tools);
    return result;
  }
  async sendRootsListChanged() {
    return this.notification({ method: "notifications/roots/list_changed" });
  }
};

// packages/cli/src/commands/mcp/list.ts
var import_chalk = __toESM(require_source(), 1);
async function getMcpServersFromConfig(settings) {
  if (!settings) {
    settings = loadSettings().merged;
  }
  const extensionManager = new ExtensionManager({
    settings,
    workspaceDir: process.cwd(),
    requestConsent: requestConsentNonInteractive,
    requestSetting: promptForSetting
  });
  const extensions = await extensionManager.loadExtensions();
  const mcpServers = { ...settings.mcpServers };
  for (const extension of extensions) {
    Object.entries(extension.mcpServers || {}).forEach(([key, server]) => {
      if (mcpServers[key]) {
        return;
      }
      mcpServers[key] = {
        // eslint-disable-next-line @typescript-eslint/no-misused-spread
        ...server,
        extension
      };
    });
  }
  const adminAllowlist = settings.admin?.mcp?.config;
  const filteredResult = applyAdminAllowlist(mcpServers, adminAllowlist);
  return filteredResult;
}
var MCP_LIST_DEFAULT_TIMEOUT_MSEC = 5e3;
async function testMCPConnection(serverName, config2, isTrusted, activeSettings) {
  const isStdio = !!config2.command;
  if (isStdio && !isTrusted) {
    return "disconnected" /* DISCONNECTED */;
  }
  const client = new Client({
    name: "mcp-test-client",
    version: "0.0.1"
  });
  const mcpContext = {
    sanitizationConfig: {
      enableEnvironmentVariableRedaction: true,
      allowedEnvironmentVariables: [],
      blockedEnvironmentVariables: activeSettings.advanced.excludedEnvVars
    },
    emitMcpDiagnostic: (severity, message, error, serverName2) => {
      if (severity === "error") {
        debugLogger.error(
          import_chalk.default.red(`Error${serverName2 ? ` (${serverName2})` : ""}: ${message}`),
          error
        );
      } else if (severity === "warning") {
        debugLogger.warn(
          import_chalk.default.yellow(
            `Warning${serverName2 ? ` (${serverName2})` : ""}: ${message}`
          ),
          error
        );
      } else {
        debugLogger.log(message, error);
      }
    },
    isTrustedFolder: () => isTrusted
  };
  let transport;
  try {
    transport = await createTransport(serverName, config2, false, mcpContext);
  } catch {
    await client.close();
    return "disconnected" /* DISCONNECTED */;
  }
  try {
    const timeout = config2.timeout ?? MCP_LIST_DEFAULT_TIMEOUT_MSEC;
    await client.connect(transport, { timeout });
    try {
      await client.ping({ timeout });
    } catch (e) {
      debugLogger.debug(
        `MCP ping failed for ${serverName}, but connect succeeded:`,
        e
      );
    }
    await client.close();
    return "connected" /* CONNECTED */;
  } catch {
    await transport.close();
    return "disconnected" /* DISCONNECTED */;
  }
}
async function getServerStatus(serverName, server, isTrusted, activeSettings, consolidatedExcluded, consolidatedAllowed) {
  const mcpEnablementManager = McpServerEnablementManager.getInstance();
  const loadResult = await canLoadServer(serverName, {
    adminMcpEnabled: activeSettings.admin?.mcp?.enabled ?? true,
    allowedList: consolidatedAllowed,
    excludedList: consolidatedExcluded.length > 0 ? consolidatedExcluded : void 0,
    enablement: mcpEnablementManager.getEnablementCallbacks()
  });
  if (!loadResult.allowed) {
    if (loadResult.blockType === "admin" || loadResult.blockType === "allowlist" || loadResult.blockType === "excludelist") {
      return "blocked" /* BLOCKED */;
    }
    return "disabled" /* DISABLED */;
  }
  if (!isTrusted) {
    return "disabled" /* DISABLED */;
  }
  return testMCPConnection(serverName, server, isTrusted, activeSettings);
}
async function listMcpServers(loadedSettingsArg) {
  const loadedSettings = loadedSettingsArg ?? loadSettings();
  const activeSettings = loadedSettings.merged;
  const allSettings = !loadedSettings.isTrusted ? loadedSettings.getMergedSettingsAsIfTrusted() : activeSettings;
  const { mcpServers, blockedServerNames } = await getMcpServersFromConfig(allSettings);
  const serverNames = Object.keys(mcpServers);
  if (blockedServerNames.length > 0) {
    const message = getAdminBlockedMcpServersMessage(
      blockedServerNames,
      void 0
    );
    debugLogger.log(import_chalk.default.yellow(message + "\n"));
  }
  if (serverNames.length === 0) {
    if (blockedServerNames.length === 0) {
      debugLogger.log("No MCP servers configured.");
    }
    return;
  }
  if (!loadedSettings.isTrusted) {
    debugLogger.log(
      import_chalk.default.yellow(
        "Warning: MCP servers are configured but disabled because this folder is untrusted.\nUser-level servers are also suppressed in untrusted folders to prevent accidental side-effects.\n"
      )
    );
  }
  const consolidatedExcluded = loadedSettings.getConsolidatedExcludedMcpServers();
  const consolidatedAllowed = loadedSettings.getConsolidatedAllowedMcpServers();
  debugLogger.log("Configured MCP servers:\n");
  for (const serverName of serverNames) {
    const server = mcpServers[serverName];
    const status = await getServerStatus(
      serverName,
      server,
      loadedSettings.isTrusted,
      activeSettings,
      consolidatedExcluded,
      consolidatedAllowed
    );
    let statusIndicator = "";
    let statusText = "";
    switch (status) {
      case "connected" /* CONNECTED */:
        statusIndicator = import_chalk.default.green("\u2713");
        statusText = "Connected";
        break;
      case "connecting" /* CONNECTING */:
        statusIndicator = import_chalk.default.yellow("\u2026");
        statusText = "Connecting";
        break;
      case "blocked" /* BLOCKED */:
        statusIndicator = import_chalk.default.red("\u26D4");
        statusText = "Blocked";
        break;
      case "disabled" /* DISABLED */:
        statusIndicator = import_chalk.default.gray("\u25CB");
        statusText = "Disabled";
        break;
      case "disconnected" /* DISCONNECTED */:
      default:
        statusIndicator = import_chalk.default.red("\u2717");
        statusText = "Disconnected";
        break;
    }
    let serverInfo = serverName + (server.extension?.name ? ` (from ${server.extension.name})` : "") + ": ";
    if (server.httpUrl) {
      serverInfo += `${server.httpUrl} (http)`;
    } else if (server.url) {
      const type = server.type || "http";
      serverInfo += `${server.url} (${type})`;
    } else if (server.command) {
      serverInfo += `${server.command} ${server.args?.join(" ") || ""} (stdio)`;
    }
    debugLogger.log(`${statusIndicator} ${serverInfo} - ${statusText}`);
  }
}
var listCommand = {
  command: "list",
  describe: "List all configured MCP servers",
  handler: async (argv) => {
    await listMcpServers(argv.loadedSettings);
    await exitCli();
  }
};

// packages/cli/src/commands/mcp/enableDisable.ts
var GREEN = "\x1B[32m";
var YELLOW = "\x1B[33m";
var RED = "\x1B[31m";
var RESET = "\x1B[0m";
async function handleEnable(args) {
  const manager = McpServerEnablementManager.getInstance();
  const name = normalizeServerId(args.name);
  const settings = loadSettings();
  const servers = await getMcpServersFromConfig();
  const normalizedServerNames = Object.keys(servers).map(normalizeServerId);
  if (!normalizedServerNames.includes(name)) {
    debugLogger.log(
      `${RED}Error:${RESET} Server '${args.name}' not found. Use 'gemini mcp' to see available servers.`
    );
    return;
  }
  const result = await canLoadServer(name, {
    adminMcpEnabled: settings.merged.admin?.mcp?.enabled ?? true,
    allowedList: settings.merged.mcp?.allowed,
    excludedList: settings.merged.mcp?.excluded
  });
  if (!result.allowed && (result.blockType === "allowlist" || result.blockType === "excludelist")) {
    debugLogger.log(`${RED}Error:${RESET} ${result.reason}`);
    return;
  }
  if (args.session) {
    manager.clearSessionDisable(name);
    debugLogger.log(`${GREEN}\u2713${RESET} Session disable cleared for '${name}'.`);
  } else {
    await manager.enable(name);
    debugLogger.log(`${GREEN}\u2713${RESET} MCP server '${name}' enabled.`);
  }
  if (result.blockType === "admin") {
    debugLogger.log(
      `${YELLOW}Warning:${RESET} MCP servers are disabled by administrator.`
    );
  }
}
async function handleDisable(args) {
  const manager = McpServerEnablementManager.getInstance();
  const name = normalizeServerId(args.name);
  const servers = await getMcpServersFromConfig();
  const normalizedServerNames = Object.keys(servers).map(normalizeServerId);
  if (!normalizedServerNames.includes(name)) {
    debugLogger.log(
      `${RED}Error:${RESET} Server '${args.name}' not found. Use 'gemini mcp' to see available servers.`
    );
    return;
  }
  if (args.session) {
    manager.disableForSession(name);
    debugLogger.log(
      `${GREEN}\u2713${RESET} MCP server '${name}' disabled for this session.`
    );
  } else {
    await manager.disable(name);
    debugLogger.log(`${GREEN}\u2713${RESET} MCP server '${name}' disabled.`);
  }
}
var enableCommand = {
  command: "enable <name>",
  describe: "Enable an MCP server",
  builder: (yargs) => yargs.positional("name", {
    describe: "MCP server name to enable",
    type: "string",
    demandOption: true
  }).option("session", {
    describe: "Clear session-only disable",
    type: "boolean",
    default: false
  }),
  handler: async (argv) => {
    await handleEnable(argv);
    await exitCli();
  }
};
var disableCommand = {
  command: "disable <name>",
  describe: "Disable an MCP server",
  builder: (yargs) => yargs.positional("name", {
    describe: "MCP server name to disable",
    type: "string",
    demandOption: true
  }).option("session", {
    describe: "Disable for current session only",
    type: "boolean",
    default: false
  }),
  handler: async (argv) => {
    await handleDisable(argv);
    await exitCli();
  }
};

// packages/cli/src/deferred.ts
import process3 from "node:process";
var deferredCommand;
function setDeferredCommand(command2) {
  deferredCommand = command2;
}
async function runDeferredCommand(settings) {
  if (!deferredCommand) {
    return;
  }
  const adminSettings = settings.admin;
  const commandName = deferredCommand.commandName;
  if (commandName === "mcp" && adminSettings?.mcp?.enabled === false) {
    coreEvents.emitFeedback(
      "error",
      getAdminErrorMessage(
        "MCP",
        void 0
        /* config */
      )
    );
    await runExitCleanup();
    process3.exit(ExitCodes.FATAL_CONFIG_ERROR);
  }
  if (commandName === "extensions" && adminSettings?.extensions?.enabled === false) {
    coreEvents.emitFeedback(
      "error",
      getAdminErrorMessage(
        "Extensions",
        void 0
        /* config */
      )
    );
    await runExitCleanup();
    process3.exit(ExitCodes.FATAL_CONFIG_ERROR);
  }
  if (commandName === "skills" && adminSettings?.skills?.enabled === false) {
    coreEvents.emitFeedback(
      "error",
      getAdminErrorMessage(
        "Agent skills",
        void 0
        /* config */
      )
    );
    await runExitCleanup();
    process3.exit(ExitCodes.FATAL_CONFIG_ERROR);
  }
  const argvWithSettings = {
    ...deferredCommand.argv,
    settings
  };
  await deferredCommand.handler(argvWithSettings);
  await runExitCleanup();
  process3.exit(ExitCodes.SUCCESS);
}
function defer(commandModule, parentCommandName) {
  return {
    ...commandModule,
    handler: (argv) => {
      setDeferredCommand({
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        handler: commandModule.handler,
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        argv,
        commandName: parentCommandName || "unknown"
      });
    }
  };
}

// packages/cli/src/commands/mcp.ts
var mcpCommand = {
  command: "mcp",
  describe: "Manage MCP servers",
  builder: (yargs) => yargs.middleware((argv) => {
    initializeOutputListenersAndFlush();
    argv["isCommand"] = true;
  }).command(defer(addCommand, "mcp")).command(defer(removeCommand, "mcp")).command(defer(listCommand, "mcp")).command(defer(enableCommand, "mcp")).command(defer(disableCommand, "mcp")).demandCommand(1, "You need at least one command before continuing.").version(false),
  handler: () => {
  }
};

// packages/cli/src/commands/extensions/install.ts
var import_chalk2 = __toESM(require_source(), 1);
import * as path from "node:path";
async function handleInstall(args) {
  try {
    const { source } = args;
    const installMetadata = await inferInstallMetadata(source, {
      ref: args.ref,
      autoUpdate: args.autoUpdate,
      allowPreRelease: args.allowPreRelease
    });
    const workspaceDir = process.cwd();
    const settings = loadSettings(workspaceDir).merged;
    if (installMetadata.type === "local" || installMetadata.type === "link") {
      const absolutePath = path.resolve(source);
      const realPath = getRealPath(absolutePath);
      installMetadata.source = absolutePath;
      const trustResult = isWorkspaceTrusted(settings, absolutePath);
      if (trustResult.isTrusted !== true) {
        const discoveryResults = await FolderTrustDiscoveryService.discover(realPath);
        const hasDiscovery = discoveryResults.commands.length > 0 || discoveryResults.mcps.length > 0 || discoveryResults.hooks.length > 0 || discoveryResults.skills.length > 0 || discoveryResults.settings.length > 0;
        const promptLines = [
          "",
          import_chalk2.default.bold("Do you trust the files in this folder?"),
          "",
          `The extension source at "${absolutePath}" is not trusted.`,
          "",
          "Trusting a folder allows Gemini CLI to load its local configurations,",
          "including custom commands, hooks, MCP servers, agent skills, and",
          "settings. These configurations could execute code on your behalf or",
          "change the behavior of the CLI.",
          ""
        ];
        if (discoveryResults.discoveryErrors.length > 0) {
          promptLines.push(import_chalk2.default.red("\u274C Discovery Errors:"));
          for (const error of discoveryResults.discoveryErrors) {
            promptLines.push(import_chalk2.default.red(`  \u2022 ${error}`));
          }
          promptLines.push("");
        }
        if (discoveryResults.securityWarnings.length > 0) {
          promptLines.push(import_chalk2.default.yellow("\u26A0\uFE0F  Security Warnings:"));
          for (const warning of discoveryResults.securityWarnings) {
            promptLines.push(import_chalk2.default.yellow(`  \u2022 ${warning}`));
          }
          promptLines.push("");
        }
        if (hasDiscovery) {
          promptLines.push(import_chalk2.default.bold("This folder contains:"));
          const groups = [
            { label: "Commands", items: discoveryResults.commands ?? [] },
            { label: "MCP Servers", items: discoveryResults.mcps ?? [] },
            { label: "Hooks", items: discoveryResults.hooks ?? [] },
            { label: "Skills", items: discoveryResults.skills ?? [] },
            { label: "Agents", items: discoveryResults.agents ?? [] },
            {
              label: "Setting overrides",
              items: discoveryResults.settings ?? []
            }
          ].filter((g) => g.items.length > 0);
          for (const group of groups) {
            promptLines.push(
              `  \u2022 ${import_chalk2.default.bold(group.label)} (${group.items.length}):`
            );
            for (const item of group.items) {
              promptLines.push(`    - ${item}`);
            }
          }
          promptLines.push("");
        }
        promptLines.push(
          import_chalk2.default.yellow(
            "Do you want to trust this folder and continue with the installation? [y/N]: "
          )
        );
        const confirmed = await promptForConsentNonInteractive(
          promptLines.join("\n"),
          false
        );
        if (confirmed) {
          const trustedFolders = loadTrustedFolders();
          await trustedFolders.setValue(realPath, "TRUST_FOLDER" /* TRUST_FOLDER */);
        } else {
          throw new Error(
            `Installation aborted: Folder "${absolutePath}" is not trusted.`
          );
        }
      }
    }
    const requestConsent = args.consent ? () => Promise.resolve(true) : requestConsentNonInteractive;
    if (args.consent) {
      debugLogger.log("You have consented to the following:");
      debugLogger.log(INSTALL_WARNING_MESSAGE);
    }
    const extensionManager = new ExtensionManager({
      workspaceDir,
      requestConsent,
      requestSetting: args.skipSettings ? null : promptForSetting,
      settings
    });
    await extensionManager.loadExtensions();
    const extension = await extensionManager.installOrUpdateExtension(installMetadata);
    debugLogger.log(
      `Extension "${extension.name}" installed successfully and enabled.`
    );
  } catch (error) {
    debugLogger.error(getErrorMessage(error));
    process.exit(1);
  }
}
var installCommand = {
  command: "install <source> [--auto-update] [--pre-release]",
  describe: "Installs an extension from a git repository URL or a local path.",
  builder: (yargs) => yargs.positional("source", {
    describe: "The github URL or local path of the extension to install.",
    type: "string",
    demandOption: true
  }).option("ref", {
    describe: "The git ref to install from.",
    type: "string"
  }).option("auto-update", {
    describe: "Enable auto-update for this extension.",
    type: "boolean"
  }).option("pre-release", {
    describe: "Enable pre-release versions for this extension.",
    type: "boolean"
  }).option("consent", {
    describe: "Acknowledge the security risks of installing an extension and skip the confirmation prompt.",
    type: "boolean",
    default: false
  }).option("skip-settings", {
    describe: "Skip the configuration on install process.",
    type: "boolean",
    default: false
  }).check((argv) => {
    if (!argv.source) {
      throw new Error("The source argument must be provided.");
    }
    return true;
  }),
  handler: async (argv) => {
    await handleInstall({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      source: argv["source"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      ref: argv["ref"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      autoUpdate: argv["auto-update"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      allowPreRelease: argv["pre-release"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      consent: argv["consent"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      skipSettings: argv["skip-settings"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/extensions/uninstall.ts
async function handleUninstall(args) {
  try {
    const workspaceDir = process.cwd();
    const extensionManager = new ExtensionManager({
      workspaceDir,
      requestConsent: requestConsentNonInteractive,
      requestSetting: promptForSetting,
      settings: loadSettings(workspaceDir).merged
    });
    await extensionManager.loadExtensions();
    let namesToUninstall = [];
    if (args.all) {
      namesToUninstall = extensionManager.getExtensions().map((ext) => ext.name);
    } else if (args.names) {
      namesToUninstall = [...new Set(args.names)];
    }
    if (namesToUninstall.length === 0) {
      if (args.all) {
        debugLogger.log("No extensions currently installed.");
      }
      return;
    }
    const errors = [];
    for (const name of namesToUninstall) {
      try {
        await extensionManager.uninstallExtension(name, false);
        debugLogger.log(`Extension "${name}" successfully uninstalled.`);
      } catch (error) {
        errors.push({ name, error: getErrorMessage(error) });
      }
    }
    if (errors.length > 0) {
      for (const { name, error } of errors) {
        debugLogger.error(`Failed to uninstall "${name}": ${error}`);
      }
      process.exit(1);
    }
  } catch (error) {
    debugLogger.error(getErrorMessage(error));
    process.exit(1);
  }
}
var uninstallCommand = {
  command: "uninstall [names..]",
  describe: "Uninstalls one or more extensions.",
  builder: (yargs) => yargs.positional("names", {
    describe: "The name(s) or source path(s) of the extension(s) to uninstall.",
    type: "string",
    array: true
  }).option("all", {
    type: "boolean",
    describe: "Uninstall all installed extensions.",
    default: false
  }).check((argv) => {
    if (!argv.all && (!argv.names || argv.names.length === 0)) {
      throw new Error(
        "Please include at least one extension name to uninstall as a positional argument, or use the --all flag."
      );
    }
    return true;
  }),
  handler: async (argv) => {
    await handleUninstall({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      names: argv["names"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      all: argv["all"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/extensions/list.ts
async function handleList(options) {
  try {
    const workspaceDir = process.cwd();
    const extensionManager = new ExtensionManager({
      workspaceDir,
      requestConsent: requestConsentNonInteractive,
      requestSetting: promptForSetting,
      settings: loadSettings(workspaceDir).merged
    });
    const extensions = await extensionManager.loadExtensions();
    if (extensions.length === 0) {
      if (options?.outputFormat === "json") {
        debugLogger.log("[]");
      } else {
        debugLogger.log("No extensions installed.");
      }
      return;
    }
    if (options?.outputFormat === "json") {
      debugLogger.log(JSON.stringify(extensions, null, 2));
    } else {
      debugLogger.log(
        extensions.map(
          (extension, _) => extensionManager.toOutputString(extension)
        ).join("\n\n")
      );
    }
  } catch (error) {
    debugLogger.error(getErrorMessage(error));
    process.exit(1);
  }
}
var listCommand2 = {
  command: "list",
  describe: "Lists installed extensions.",
  builder: (yargs) => yargs.option("output-format", {
    alias: "o",
    type: "string",
    describe: "The format of the CLI output.",
    choices: ["text", "json"],
    default: "text"
  }),
  handler: async (argv) => {
    await handleList({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      outputFormat: argv["output-format"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/extensions/update.ts
var updateOutput = (info) => `Extension "${info.name}" successfully updated: ${info.originalVersion} \u2192 ${info.updatedVersion}.`;
async function handleUpdate(args) {
  const workspaceDir = process.cwd();
  const settings = loadSettings(workspaceDir).merged;
  const extensionManager = new ExtensionManager({
    workspaceDir,
    requestConsent: requestConsentNonInteractive,
    requestSetting: promptForSetting,
    settings
  });
  const extensions = await extensionManager.loadExtensions();
  if (args.name) {
    try {
      const extension = extensions.find(
        (extension2) => extension2.name === args.name
      );
      if (!extension) {
        if (extensions.length === 0) {
          coreEvents.emitFeedback(
            "error",
            `Extension "${args.name}" not found.

No extensions installed.`
          );
          return;
        }
        const installedExtensions = extensions.map((extension2) => `${extension2.name} (${extension2.version})`).join("\n");
        coreEvents.emitFeedback(
          "error",
          `Extension "${args.name}" not found.

Installed extensions:
${installedExtensions}

Run "gemini extensions list" for details.`
        );
        return;
      }
      if (!extension.installMetadata) {
        debugLogger.log(
          `Unable to install extension "${args.name}" due to missing install metadata`
        );
        return;
      }
      const updateState = await checkForExtensionUpdate(
        extension,
        extensionManager
      );
      if (updateState !== "update available" /* UPDATE_AVAILABLE */) {
        debugLogger.log(`Extension "${args.name}" is already up to date.`);
        return;
      }
      const updatedExtensionInfo = await updateExtension(
        extension,
        extensionManager,
        updateState,
        () => {
        },
        settings.experimental?.extensionReloading
      );
      if (updatedExtensionInfo.originalVersion !== updatedExtensionInfo.updatedVersion) {
        debugLogger.log(
          `Extension "${args.name}" successfully updated: ${updatedExtensionInfo.originalVersion} \u2192 ${updatedExtensionInfo.updatedVersion}.`
        );
      } else {
        debugLogger.log(`Extension "${args.name}" is already up to date.`);
      }
    } catch (error) {
      debugLogger.error(getErrorMessage(error));
    }
  }
  if (args.all) {
    try {
      const extensionState = /* @__PURE__ */ new Map();
      await checkForAllExtensionUpdates(
        extensions,
        extensionManager,
        (action) => {
          if (action.type === "SET_STATE") {
            extensionState.set(action.payload.name, {
              status: action.payload.state
            });
          }
        }
      );
      let updateInfos = await updateAllUpdatableExtensions(
        extensions,
        extensionState,
        extensionManager,
        () => {
        }
      );
      updateInfos = updateInfos.filter(
        (info) => info.originalVersion !== info.updatedVersion
      );
      if (updateInfos.length === 0) {
        debugLogger.log("No extensions to update.");
        return;
      }
      debugLogger.log(updateInfos.map((info) => updateOutput(info)).join("\n"));
    } catch (error) {
      debugLogger.error(getErrorMessage(error));
    }
  }
}
var updateCommand = {
  command: "update [<name>] [--all]",
  describe: "Updates all extensions or a named extension to the latest version.",
  builder: (yargs) => yargs.positional("name", {
    describe: "The name of the extension to update.",
    type: "string"
  }).option("all", {
    describe: "Update all extensions.",
    type: "boolean"
  }).conflicts("name", "all").check((argv) => {
    if (!argv.all && !argv.name) {
      throw new Error("Either an extension name or --all must be provided");
    }
    return true;
  }),
  handler: async (argv) => {
    await handleUpdate({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      name: argv["name"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      all: argv["all"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/extensions/disable.ts
async function handleDisable2(args) {
  const workspaceDir = process.cwd();
  const extensionManager = new ExtensionManager({
    workspaceDir,
    requestConsent: requestConsentNonInteractive,
    requestSetting: promptForSetting,
    settings: loadSettings(workspaceDir).merged
  });
  await extensionManager.loadExtensions();
  try {
    if (args.scope?.toLowerCase() === "workspace") {
      await extensionManager.disableExtension(
        args.name,
        "Workspace" /* Workspace */
      );
    } else {
      await extensionManager.disableExtension(args.name, "User" /* User */);
    }
    debugLogger.log(
      `Extension "${args.name}" successfully disabled for scope "${args.scope}".`
    );
  } catch (error) {
    debugLogger.error(getErrorMessage(error));
    process.exit(1);
  }
}
var disableCommand2 = {
  command: "disable [--scope] <name>",
  describe: "Disables an extension.",
  builder: (yargs) => yargs.positional("name", {
    describe: "The name of the extension to disable.",
    type: "string"
  }).option("scope", {
    describe: "The scope to disable the extension in.",
    type: "string",
    default: "User" /* User */
  }).check((argv) => {
    if (argv.scope && !Object.values(SettingScope).map((s) => s.toLowerCase()).includes(argv.scope.toLowerCase())) {
      throw new Error(
        `Invalid scope: ${argv.scope}. Please use one of ${Object.values(
          SettingScope
        ).map((s) => s.toLowerCase()).join(", ")}.`
      );
    }
    return true;
  }),
  handler: async (argv) => {
    await handleDisable2({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      name: argv["name"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      scope: argv["scope"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/extensions/enable.ts
async function handleEnable2(args) {
  const workingDir = process.cwd();
  const extensionManager = new ExtensionManager({
    workspaceDir: workingDir,
    requestConsent: requestConsentNonInteractive,
    requestSetting: promptForSetting,
    settings: loadSettings(workingDir).merged
  });
  await extensionManager.loadExtensions();
  try {
    if (args.scope?.toLowerCase() === "workspace") {
      await extensionManager.enableExtension(args.name, "Workspace" /* Workspace */);
    } else {
      await extensionManager.enableExtension(args.name, "User" /* User */);
    }
    const extension = extensionManager.getExtensions().find((e) => e.name === args.name);
    if (extension?.mcpServers) {
      const mcpEnablementManager = McpServerEnablementManager.getInstance();
      const enabledServers = await mcpEnablementManager.autoEnableServers(
        Object.keys(extension.mcpServers ?? {})
      );
      for (const serverName of enabledServers) {
        debugLogger.log(
          `MCP server '${serverName}' was disabled - now enabled.`
        );
      }
    }
    if (args.scope) {
      debugLogger.log(
        `Extension "${args.name}" successfully enabled for scope "${args.scope}".`
      );
    } else {
      debugLogger.log(
        `Extension "${args.name}" successfully enabled in all scopes.`
      );
    }
  } catch (error) {
    throw new FatalConfigError(getErrorMessage(error));
  }
}
var enableCommand2 = {
  command: "enable [--scope] <name>",
  describe: "Enables an extension.",
  builder: (yargs) => yargs.positional("name", {
    describe: "The name of the extension to enable.",
    type: "string"
  }).option("scope", {
    describe: "The scope to enable the extension in. If not set, will be enabled in all scopes.",
    type: "string"
  }).check((argv) => {
    if (argv.scope && !Object.values(SettingScope).map((s) => s.toLowerCase()).includes(argv.scope.toLowerCase())) {
      throw new Error(
        `Invalid scope: ${argv.scope}. Please use one of ${Object.values(
          SettingScope
        ).map((s) => s.toLowerCase()).join(", ")}.`
      );
    }
    return true;
  }),
  handler: async (argv) => {
    await handleEnable2({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      name: argv["name"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      scope: argv["scope"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/extensions/link.ts
var import_chalk3 = __toESM(require_source(), 1);
async function handleLink(args) {
  try {
    const installMetadata = {
      source: args.path,
      type: "link"
    };
    const requestConsent = args.consent ? () => Promise.resolve(true) : requestConsentNonInteractive;
    if (args.consent) {
      debugLogger.log("You have consented to the following:");
      debugLogger.log(INSTALL_WARNING_MESSAGE);
    }
    const workspaceDir = process.cwd();
    const extensionManager = new ExtensionManager({
      workspaceDir,
      requestConsent,
      requestSetting: promptForSetting,
      settings: loadSettings(workspaceDir).merged
    });
    await extensionManager.loadExtensions();
    const extension = await extensionManager.installOrUpdateExtension(installMetadata);
    debugLogger.log(
      import_chalk3.default.green(
        `Extension "${extension.name}" linked successfully and enabled.`
      )
    );
  } catch (error) {
    debugLogger.error(getErrorMessage(error));
    process.exit(1);
  }
}
var linkCommand = {
  command: "link <path>",
  describe: "Links an extension from a local path. Updates made to the local path will always be reflected.",
  builder: (yargs) => yargs.positional("path", {
    describe: "The name of the extension to link.",
    type: "string"
  }).option("consent", {
    describe: "Acknowledge the security risks of installing an extension and skip the confirmation prompt.",
    type: "boolean",
    default: false
  }).check((_) => true),
  handler: async (argv) => {
    await handleLink({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      path: argv["path"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      consent: argv["consent"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/extensions/new.ts
import { access, cp, mkdir, readdir, writeFile as writeFile2 } from "node:fs/promises";
import { join, dirname as dirname3, basename as basename2 } from "node:path";
import { fileURLToPath as fileURLToPath2 } from "node:url";
var __filename = fileURLToPath2(import.meta.url);
var __dirname2 = dirname3(__filename);
var EXAMPLES_PATH = join(__dirname2, "examples");
async function pathExists(path16) {
  try {
    await access(path16);
    return true;
  } catch {
    return false;
  }
}
async function createDirectory(path16) {
  if (await pathExists(path16)) {
    throw new Error(`Path already exists: ${path16}`);
  }
  await mkdir(path16, { recursive: true });
}
async function copyDirectory(template, path16) {
  await createDirectory(path16);
  const examplePath = join(EXAMPLES_PATH, template);
  const entries = await readdir(examplePath, { withFileTypes: true });
  for (const entry of entries) {
    const srcPath = join(examplePath, entry.name);
    const destPath = join(path16, entry.name);
    await cp(srcPath, destPath, { recursive: true });
  }
}
async function handleNew(args) {
  if (args.template) {
    await copyDirectory(args.template, args.path);
    debugLogger.log(
      `Successfully created new extension from template "${args.template}" at ${args.path}.`
    );
  } else {
    await createDirectory(args.path);
    const extensionName = basename2(args.path);
    const manifest = {
      name: extensionName,
      version: "1.0.0"
    };
    await writeFile2(
      join(args.path, "gemini-extension.json"),
      JSON.stringify(manifest, null, 2)
    );
    debugLogger.log(`Successfully created new extension at ${args.path}.`);
  }
  debugLogger.log(
    `You can install this using "gemini extensions link ${args.path}" to test it out.`
  );
}
async function getBoilerplateChoices() {
  const entries = await readdir(EXAMPLES_PATH, { withFileTypes: true });
  return entries.filter((entry) => entry.isDirectory()).map((entry) => entry.name);
}
var newCommand = {
  command: "new <path> [template]",
  describe: "Create a new extension from a boilerplate example.",
  builder: async (yargs) => {
    const choices = await getBoilerplateChoices();
    return yargs.positional("path", {
      describe: "The path to create the extension in.",
      type: "string"
    }).positional("template", {
      describe: "The boilerplate template to use.",
      type: "string",
      choices
    });
  },
  handler: async (args) => {
    await handleNew({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      path: args["path"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      template: args["template"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/extensions/validate.ts
var import_semver = __toESM(require_semver(), 1);
import * as fs from "node:fs";
import * as path2 from "node:path";
async function handleValidate(args) {
  try {
    await validateExtension(args);
    debugLogger.log(`Extension ${args.path} has been successfully validated.`);
  } catch (error) {
    debugLogger.error(getErrorMessage(error));
    process.exit(1);
  }
}
async function validateExtension(args) {
  const workspaceDir = process.cwd();
  const extensionManager = new ExtensionManager({
    workspaceDir,
    requestConsent: requestConsentNonInteractive,
    requestSetting: promptForSetting,
    settings: loadSettings(workspaceDir).merged
  });
  const absoluteInputPath = path2.resolve(args.path);
  const extensionConfig = await extensionManager.loadExtensionConfig(absoluteInputPath);
  const warnings = [];
  const errors = [];
  if (extensionConfig.contextFileName) {
    const contextFileNames = Array.isArray(extensionConfig.contextFileName) ? extensionConfig.contextFileName : [extensionConfig.contextFileName];
    const missingContextFiles = [];
    for (const contextFilePath of contextFileNames) {
      const contextFileAbsolutePath = path2.resolve(
        absoluteInputPath,
        contextFilePath
      );
      if (!fs.existsSync(contextFileAbsolutePath)) {
        missingContextFiles.push(contextFilePath);
      }
    }
    if (missingContextFiles.length > 0) {
      errors.push(
        `The following context files referenced in gemini-extension.json are missing: ${missingContextFiles}`
      );
    }
  }
  if (!import_semver.default.valid(extensionConfig.version)) {
    warnings.push(
      `Warning: Version '${extensionConfig.version}' does not appear to be standard semver (e.g., 1.0.0).`
    );
  }
  if (warnings.length > 0) {
    debugLogger.warn("Validation warnings:");
    for (const warning of warnings) {
      debugLogger.warn(`  - ${warning}`);
    }
  }
  if (errors.length > 0) {
    debugLogger.error("Validation failed with the following errors:");
    for (const error of errors) {
      debugLogger.error(`  - ${error}`);
    }
    throw new Error("Extension validation failed.");
  }
}
var validateCommand = {
  command: "validate <path>",
  describe: "Validates an extension from a local path.",
  builder: (yargs) => yargs.positional("path", {
    describe: "The path of the extension to validate.",
    type: "string",
    demandOption: true
  }),
  handler: async (args) => {
    await handleValidate({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      path: args["path"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/extensions/configure.ts
var configureCommand = {
  command: "config [name] [setting]",
  describe: "Configure extension settings.",
  builder: (yargs) => yargs.positional("name", {
    describe: "Name of the extension to configure.",
    type: "string"
  }).positional("setting", {
    describe: "The specific setting to configure (name or env var).",
    type: "string"
  }).option("scope", {
    describe: "The scope to set the setting in.",
    type: "string",
    choices: ["user", "workspace"],
    default: "user"
  }),
  handler: async (args) => {
    const { name, setting, scope } = args;
    const settings = loadSettings(process.cwd()).merged;
    if (!(settings.experimental?.extensionConfig ?? true)) {
      coreEvents.emitFeedback(
        "error",
        'Extension configuration is currently disabled. Enable it by setting "experimental.extensionConfig" to true.'
      );
      await exitCli();
      return;
    }
    if (name) {
      if (name.includes("/") || name.includes("\\") || name.includes("..")) {
        debugLogger.error(
          'Invalid extension name. Names cannot contain path separators or "..".'
        );
        return;
      }
    }
    const extensionManager = await getExtensionManager();
    if (name && setting) {
      await configureSpecificSetting(
        extensionManager,
        name,
        setting,
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        scope
      );
    } else if (name) {
      await configureExtension(
        extensionManager,
        name,
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        scope
      );
    } else {
      await configureAllExtensions(
        extensionManager,
        // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
        scope
      );
    }
    await exitCli();
  }
};

// packages/cli/src/commands/extensions.tsx
var extensionsCommand = {
  command: "extensions <command>",
  aliases: ["extension"],
  describe: "Manage Gemini CLI extensions.",
  builder: (yargs) => yargs.middleware((argv) => {
    initializeOutputListenersAndFlush();
    argv["isCommand"] = true;
  }).command(defer(installCommand, "extensions")).command(defer(uninstallCommand, "extensions")).command(defer(listCommand2, "extensions")).command(defer(updateCommand, "extensions")).command(defer(disableCommand2, "extensions")).command(defer(enableCommand2, "extensions")).command(defer(linkCommand, "extensions")).command(defer(newCommand, "extensions")).command(defer(validateCommand, "extensions")).command(defer(configureCommand, "extensions")).demandCommand(1, "You need at least one command before continuing.").version(false),
  handler: () => {
  }
};

// packages/cli/src/commands/skills/list.ts
var import_chalk4 = __toESM(require_source(), 1);
async function handleList2(args) {
  const workspaceDir = process.cwd();
  const settings = loadSettings(workspaceDir);
  const config2 = await loadCliConfig(
    settings.merged,
    "skills-list-session",
    // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
    {
      debug: false
    },
    { cwd: workspaceDir }
  );
  await config2.initialize();
  const skillManager = config2.getSkillManager();
  const skills = args.all ? skillManager.getAllSkills() : skillManager.getAllSkills().filter((s) => !s.isBuiltin);
  skills.sort((a, b) => {
    if (a.isBuiltin === b.isBuiltin) {
      return a.name.localeCompare(b.name);
    }
    return a.isBuiltin ? 1 : -1;
  });
  if (skills.length === 0) {
    process.stdout.write("No skills discovered.\n");
    return;
  }
  process.stdout.write(import_chalk4.default.bold("Discovered Agent Skills:") + "\n\n");
  for (const skill of skills) {
    const status = skill.disabled ? import_chalk4.default.red("[Disabled]") : import_chalk4.default.green("[Enabled]");
    const builtinSuffix = skill.isBuiltin ? import_chalk4.default.gray(" [Built-in]") : "";
    process.stdout.write(
      `${import_chalk4.default.bold(skill.name)} ${status}${builtinSuffix}
`
    );
    process.stdout.write(`  Description: ${skill.description}
`);
    process.stdout.write(`  Location:    ${skill.location}

`);
  }
}
var listCommand3 = {
  command: "list [--all]",
  describe: "Lists discovered agent skills.",
  builder: (yargs) => yargs.option("all", {
    type: "boolean",
    description: "Show all skills, including built-in ones.",
    default: false
  }),
  handler: async (argv) => {
    await handleList2({ all: argv["all"] });
    await exitCli();
  }
};

// packages/cli/src/commands/skills/enable.ts
var import_chalk5 = __toESM(require_source(), 1);
async function handleEnable3(args) {
  const { name } = args;
  const workspaceDir = process.cwd();
  const settings = loadSettings(workspaceDir);
  const result = enableSkill(settings, name);
  const feedback = renderSkillActionFeedback(
    result,
    (label, path16) => `${import_chalk5.default.bold(label)} (${import_chalk5.default.dim(path16)})`
  );
  debugLogger.log(feedback);
}
var enableCommand3 = {
  command: "enable <name>",
  describe: "Enables an agent skill.",
  builder: (yargs) => yargs.positional("name", {
    describe: "The name of the skill to enable.",
    type: "string",
    demandOption: true
  }),
  handler: async (argv) => {
    await handleEnable3({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      name: argv["name"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/skills/disable.ts
var import_chalk6 = __toESM(require_source(), 1);
async function handleDisable3(args) {
  const { name, scope } = args;
  const workspaceDir = process.cwd();
  const settings = loadSettings(workspaceDir);
  const result = disableSkill(settings, name, scope);
  const feedback = renderSkillActionFeedback(
    result,
    (label, path16) => `${import_chalk6.default.bold(label)} (${import_chalk6.default.dim(path16)})`
  );
  debugLogger.log(feedback);
}
var disableCommand3 = {
  command: "disable <name> [--scope]",
  describe: "Disables an agent skill.",
  builder: (yargs) => yargs.positional("name", {
    describe: "The name of the skill to disable.",
    type: "string",
    demandOption: true
  }).option("scope", {
    alias: "s",
    describe: "The scope to disable the skill in (user or workspace).",
    type: "string",
    default: "workspace",
    choices: ["user", "workspace"]
  }),
  handler: async (argv) => {
    const scope = argv["scope"] === "workspace" ? "Workspace" /* Workspace */ : "User" /* User */;
    await handleDisable3({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      name: argv["name"],
      scope
    });
    await exitCli();
  }
};

// packages/cli/src/commands/skills/install.ts
var import_chalk7 = __toESM(require_source(), 1);
async function handleInstall2(args) {
  try {
    const { source, consent } = args;
    const scope = args.scope ?? "user";
    const subpath = args.path;
    const requestConsent = async (skills, targetDir) => {
      if (consent) {
        debugLogger.log("You have consented to the following:");
        debugLogger.log(await skillsConsentString(skills, source, targetDir));
        return true;
      }
      return requestConsentNonInteractive(
        await skillsConsentString(skills, source, targetDir)
      );
    };
    const installedSkills = await installSkill(
      source,
      scope,
      subpath,
      (msg) => {
        debugLogger.log(msg);
      },
      requestConsent
    );
    for (const skill of installedSkills) {
      debugLogger.log(
        import_chalk7.default.green(
          `Successfully installed skill: ${import_chalk7.default.bold(skill.name)} (scope: ${scope}, location: ${skill.location})`
        )
      );
    }
  } catch (error) {
    debugLogger.error(getErrorMessage(error));
    await exitCli(1);
  }
}
var installCommand2 = {
  command: "install <source> [--scope] [--path]",
  describe: "Installs an agent skill from a git repository URL or a local path.",
  builder: (yargs) => yargs.positional("source", {
    describe: "The git repository URL or local path of the skill to install.",
    type: "string",
    demandOption: true
  }).option("scope", {
    describe: 'The scope to install the skill into. Defaults to "user" (global).',
    choices: ["user", "workspace"],
    default: "user"
  }).option("path", {
    describe: "Sub-path within the repository to install from (only used for git repository sources).",
    type: "string"
  }).option("consent", {
    describe: "Acknowledge the security risks of installing a skill and skip the confirmation prompt.",
    type: "boolean",
    default: false
  }).check((argv) => {
    if (!argv.source) {
      throw new Error("The source argument must be provided.");
    }
    return true;
  }),
  handler: async (argv) => {
    await handleInstall2({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      source: argv["source"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      scope: argv["scope"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      path: argv["path"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      consent: argv["consent"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/skills/link.ts
var import_chalk8 = __toESM(require_source(), 1);
async function handleLink2(args) {
  try {
    const { scope = "user", consent } = args;
    await linkSkill(
      args.path,
      scope,
      (msg) => debugLogger.log(msg),
      async (skills, targetDir) => {
        const consentString = await skillsConsentString(
          skills,
          args.path,
          targetDir,
          true
        );
        if (consent) {
          debugLogger.log("You have consented to the following:");
          debugLogger.log(consentString);
          return true;
        }
        return requestConsentNonInteractive(consentString);
      }
    );
    debugLogger.log(import_chalk8.default.green("\nSuccessfully linked skills."));
  } catch (error) {
    debugLogger.error(getErrorMessage(error));
    await exitCli(1);
  }
}
var linkCommand2 = {
  command: "link <path>",
  describe: "Links an agent skill from a local path. Updates to the source will be reflected immediately.",
  builder: (yargs) => yargs.positional("path", {
    describe: "The local path of the skill to link.",
    type: "string",
    demandOption: true
  }).option("scope", {
    describe: 'The scope to link the skill into. Defaults to "user" (global).',
    choices: ["user", "workspace"],
    default: "user"
  }).option("consent", {
    describe: "Acknowledge the security risks of linking a skill and skip the confirmation prompt.",
    type: "boolean",
    default: false
  }).check((argv) => {
    if (!argv.path) {
      throw new Error("The path argument must be provided.");
    }
    return true;
  }),
  handler: async (argv) => {
    await handleLink2({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      path: argv["path"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      scope: argv["scope"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      consent: argv["consent"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/skills/uninstall.ts
var import_chalk9 = __toESM(require_source(), 1);
async function handleUninstall2(args) {
  try {
    const { name } = args;
    const scope = args.scope ?? "user";
    const result = await uninstallSkill(name, scope);
    if (result) {
      debugLogger.log(
        import_chalk9.default.green(
          `Successfully uninstalled skill: ${import_chalk9.default.bold(name)} (scope: ${scope}, location: ${result.location})`
        )
      );
    } else {
      debugLogger.error(
        `Skill "${name}" is not installed in the ${scope} scope.`
      );
    }
  } catch (error) {
    debugLogger.error(getErrorMessage(error));
    await exitCli(1);
  }
}
var uninstallCommand2 = {
  command: "uninstall <name> [--scope]",
  describe: "Uninstalls an agent skill by name.",
  builder: (yargs) => yargs.positional("name", {
    describe: "The name of the skill to uninstall.",
    type: "string",
    demandOption: true
  }).option("scope", {
    describe: 'The scope to uninstall the skill from. Defaults to "user" (global).',
    choices: ["user", "workspace"],
    default: "user"
  }).check((argv) => {
    if (!argv.name) {
      throw new Error("The skill name must be provided.");
    }
    return true;
  }),
  handler: async (argv) => {
    await handleUninstall2({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      name: argv["name"],
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      scope: argv["scope"]
    });
    await exitCli();
  }
};

// packages/cli/src/commands/skills.tsx
var skillsCommand = {
  command: "skills <command>",
  aliases: ["skill"],
  describe: "Manage agent skills.",
  builder: (yargs) => yargs.middleware((argv) => {
    initializeOutputListenersAndFlush();
    argv["isCommand"] = true;
  }).command(defer(listCommand3, "skills")).command(defer(enableCommand3, "skills")).command(defer(disableCommand3, "skills")).command(defer(installCommand2, "skills")).command(defer(linkCommand2, "skills")).command(defer(uninstallCommand2, "skills")).demandCommand(1, "You need at least one command before continuing.").version(false),
  handler: () => {
  }
};

// packages/cli/src/commands/hooks/migrate.ts
import * as fs2 from "node:fs";
import * as path3 from "node:path";
var import_strip_json_comments = __toESM(require_strip_json_comments(), 1);
var EVENT_MAPPING = {
  PreToolUse: "BeforeTool",
  PostToolUse: "AfterTool",
  UserPromptSubmit: "BeforeAgent",
  Stop: "AfterAgent",
  SubAgentStop: "AfterAgent",
  // Gemini doesn't have sub-agents, map to AfterAgent
  SessionStart: "SessionStart",
  SessionEnd: "SessionEnd",
  PreCompact: "PreCompress",
  Notification: "Notification"
};
var TOOL_NAME_MAPPING = {
  Edit: "replace",
  Bash: "run_shell_command",
  Read: "read_file",
  Write: "write_file",
  Glob: "glob",
  Grep: "grep",
  LS: "ls"
};
function transformMatcher(matcher) {
  if (!matcher) return matcher;
  let transformed = matcher;
  for (const [claudeName, geminiName] of Object.entries(TOOL_NAME_MAPPING)) {
    transformed = transformed.replace(
      new RegExp(`\\b${claudeName}\\b`, "g"),
      geminiName
    );
  }
  return transformed;
}
function migrateClaudeHook(claudeHook) {
  if (!claudeHook || typeof claudeHook !== "object") {
    return claudeHook;
  }
  const hook = claudeHook;
  const migrated = {};
  if ("command" in hook) {
    migrated["command"] = hook["command"];
    if (typeof migrated["command"] === "string") {
      migrated["command"] = migrated["command"].replace(
        /\$CLAUDE_PROJECT_DIR/g,
        "$GEMINI_PROJECT_DIR"
      );
    }
  }
  if ("type" in hook && hook["type"] === "command") {
    migrated["type"] = "command";
  }
  if ("timeout" in hook && typeof hook["timeout"] === "number") {
    migrated["timeout"] = hook["timeout"];
  }
  return migrated;
}
function migrateClaudeHooks(claudeConfig) {
  if (!claudeConfig || typeof claudeConfig !== "object") {
    return {};
  }
  const config2 = claudeConfig;
  const geminiHooks = {};
  const hooksSection = config2["hooks"];
  if (!hooksSection || typeof hooksSection !== "object") {
    return {};
  }
  for (const [eventName, eventConfig] of Object.entries(hooksSection)) {
    const geminiEventName = EVENT_MAPPING[eventName] || eventName;
    if (!Array.isArray(eventConfig)) {
      continue;
    }
    const migratedDefinitions = eventConfig.map((def) => {
      if (!def || typeof def !== "object") {
        return def;
      }
      const definition = def;
      const migratedDef = {};
      if ("matcher" in definition && // eslint-disable-next-line no-restricted-syntax
      typeof definition["matcher"] === "string") {
        migratedDef["matcher"] = transformMatcher(definition["matcher"]);
      }
      if ("sequential" in definition) {
        migratedDef["sequential"] = definition["sequential"];
      }
      if ("hooks" in definition && Array.isArray(definition["hooks"])) {
        migratedDef["hooks"] = definition["hooks"].map(migrateClaudeHook);
      }
      return migratedDef;
    });
    geminiHooks[geminiEventName] = migratedDefinitions;
  }
  return geminiHooks;
}
async function handleMigrateFromClaude() {
  const workingDir = process.cwd();
  const claudeDir = path3.join(workingDir, ".claude");
  const claudeSettingsPath = path3.join(claudeDir, "settings.json");
  const claudeLocalSettingsPath = path3.join(claudeDir, "settings.local.json");
  let claudeSettings = null;
  let sourceFile = "";
  if (fs2.existsSync(claudeLocalSettingsPath)) {
    sourceFile = claudeLocalSettingsPath;
    try {
      const content = fs2.readFileSync(claudeLocalSettingsPath, "utf-8");
      claudeSettings = JSON.parse((0, import_strip_json_comments.default)(content));
    } catch (error) {
      debugLogger.error(
        `Error reading ${claudeLocalSettingsPath}: ${getErrorMessage(error)}`
      );
    }
  } else if (fs2.existsSync(claudeSettingsPath)) {
    sourceFile = claudeSettingsPath;
    try {
      const content = fs2.readFileSync(claudeSettingsPath, "utf-8");
      claudeSettings = JSON.parse((0, import_strip_json_comments.default)(content));
    } catch (error) {
      debugLogger.error(
        `Error reading ${claudeSettingsPath}: ${getErrorMessage(error)}`
      );
    }
  } else {
    debugLogger.error(
      "No Claude Code settings found in .claude directory. Expected settings.json or settings.local.json"
    );
    return;
  }
  if (!claudeSettings) {
    return;
  }
  debugLogger.log(`Found Claude Code settings in: ${sourceFile}`);
  const migratedHooks = migrateClaudeHooks(claudeSettings);
  if (Object.keys(migratedHooks).length === 0) {
    debugLogger.log("No hooks found in Claude Code settings to migrate.");
    return;
  }
  debugLogger.log(
    `Migrating ${Object.keys(migratedHooks).length} hook event(s)...`
  );
  const settings = loadSettings(workingDir);
  const existingHooks = settings.merged?.hooks || {};
  const mergedHooks = { ...existingHooks, ...migratedHooks };
  try {
    settings.setValue("Workspace" /* Workspace */, "hooks", mergedHooks);
    debugLogger.log("\u2713 Hooks successfully migrated to .gemini/settings.json");
    debugLogger.log(
      "\nMigration complete! Please review the migrated hooks in .gemini/settings.json"
    );
  } catch (error) {
    debugLogger.error(`Error saving migrated hooks: ${getErrorMessage(error)}`);
  }
}
var migrateCommand = {
  command: "migrate",
  describe: "Migrate hooks from Claude Code to Gemini CLI",
  builder: (yargs) => yargs.option("from-claude", {
    describe: "Migrate from Claude Code hooks",
    type: "boolean",
    default: false
  }),
  handler: async (argv) => {
    const args = argv;
    if (args.fromClaude) {
      await handleMigrateFromClaude();
    } else {
      debugLogger.log(
        "Usage: gemini hooks migrate --from-claude\n\nMigrate hooks from Claude Code to Gemini CLI format."
      );
    }
    await exitCli();
  }
};

// packages/cli/src/commands/hooks.tsx
var hooksCommand = {
  command: "hooks <command>",
  aliases: ["hook"],
  describe: "Manage Gemini CLI hooks.",
  builder: (yargs) => yargs.middleware((argv) => {
    initializeOutputListenersAndFlush();
    argv["isCommand"] = true;
  }).command(migrateCommand).demandCommand(1, "You need at least one command before continuing.").version(false),
  handler: () => {
  }
};

// packages/cli/src/commands/gemma/setup.ts
var import_chalk10 = __toESM(require_source(), 1);
import { createHash } from "node:crypto";
import fs3 from "node:fs";
import path4 from "node:path";
import { execFileSync, spawn as nodeSpawn } from "node:child_process";
import readline from "node:readline";
var log = (msg) => debugLogger.log(msg);
var logError = (msg) => debugLogger.error(msg);
async function promptYesNo(question) {
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  return new Promise((resolve9) => {
    rl.question(`${question} (y/N): `, (answer) => {
      rl.close();
      resolve9(
        answer.trim().toLowerCase() === "y" || answer.trim().toLowerCase() === "yes"
      );
    });
  });
}
function formatBytes(bytes) {
  if (bytes < 1024) return `${bytes} B`;
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
  return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function renderProgress(downloaded, total) {
  const barWidth = 30;
  if (total && total > 0) {
    const pct = Math.min(downloaded / total, 1);
    const filled = Math.round(barWidth * pct);
    const bar = "\u2588".repeat(filled) + "\u2591".repeat(barWidth - filled);
    const pctStr = (pct * 100).toFixed(0).padStart(3);
    process.stderr.write(
      `\r  [${bar}] ${pctStr}% ${formatBytes(downloaded)} / ${formatBytes(total)}`
    );
  } else {
    process.stderr.write(`\r  Downloaded ${formatBytes(downloaded)}`);
  }
}
async function downloadFile(url, destPath) {
  const tmpPath = destPath + ".downloading";
  if (fs3.existsSync(tmpPath)) {
    fs3.unlinkSync(tmpPath);
  }
  const response = await fetch(url, { redirect: "follow" });
  if (!response.ok) {
    throw new Error(
      `Download failed: HTTP ${response.status} ${response.statusText}`
    );
  }
  if (!response.body) {
    throw new Error("Download failed: No response body");
  }
  const contentLength = response.headers.get("content-length");
  const totalBytes = contentLength ? parseInt(contentLength, 10) : null;
  let downloadedBytes = 0;
  const fileStream = fs3.createWriteStream(tmpPath);
  const reader = response.body.getReader();
  try {
    for (; ; ) {
      const { done, value } = await reader.read();
      if (done) break;
      const writeOk = fileStream.write(value);
      if (!writeOk) {
        await new Promise((resolve9) => fileStream.once("drain", resolve9));
      }
      downloadedBytes += value.byteLength;
      renderProgress(downloadedBytes, totalBytes);
    }
  } finally {
    fileStream.end();
    process.stderr.write("\r" + " ".repeat(80) + "\r");
  }
  await new Promise((resolve9, reject) => {
    fileStream.on("finish", resolve9);
    fileStream.on("error", reject);
  });
  fs3.renameSync(tmpPath, destPath);
}
async function computeFileSha256(filePath) {
  const hash = createHash("sha256");
  const fileStream = fs3.createReadStream(filePath);
  return new Promise((resolve9, reject) => {
    fileStream.on("data", (chunk) => {
      hash.update(chunk);
    });
    fileStream.on("error", reject);
    fileStream.on("end", () => {
      resolve9(hash.digest("hex"));
    });
  });
}
async function verifyFileSha256(filePath, expectedHash) {
  const actualHash = await computeFileSha256(filePath);
  return actualHash === expectedHash;
}
function spawnInherited(command2, args) {
  return new Promise((resolve9, reject) => {
    const child = nodeSpawn(command2, args, {
      stdio: "inherit"
    });
    child.on("close", (code) => resolve9(code ?? 1));
    child.on("error", reject);
  });
}
async function handleSetup(argv) {
  const { port, force } = argv;
  let settingsUpdated = false;
  let serverStarted = false;
  let autoStartServer = true;
  log("");
  log(import_chalk10.default.bold("Gemma Local Model Routing Setup"));
  log(import_chalk10.default.dim("\u2500".repeat(40)));
  log("");
  const platform2 = detectPlatform();
  if (!platform2) {
    logError(
      import_chalk10.default.red(`Unsupported platform: ${process.platform}-${process.arch}`)
    );
    logError(
      "LiteRT-LM binaries are available for: macOS (ARM64), Linux (x86_64), Windows (x86_64)"
    );
    return 1;
  }
  log(import_chalk10.default.dim(`  Platform: ${platform2.key} \u2192 ${platform2.binaryName}`));
  if (!argv.consent) {
    log("");
    log("This will download and install the LiteRT-LM runtime and the");
    log(
      `Gemma model (${GEMMA_MODEL_NAME}, ~1 GB). By proceeding, you agree to the`
    );
    log("Gemma Terms of Use: https://ai.google.dev/gemma/terms");
    log("");
    const accepted = await promptYesNo("Do you want to continue?");
    if (!accepted) {
      log("Setup cancelled.");
      return 0;
    }
  }
  const binaryPath = getBinaryPath(platform2.binaryName);
  const alreadyInstalled = isBinaryInstalled();
  if (alreadyInstalled && !force) {
    log("");
    log(import_chalk10.default.green("  \u2713 LiteRT-LM binary already installed at:"));
    log(import_chalk10.default.dim(`    ${binaryPath}`));
  } else {
    log("");
    log("  Downloading LiteRT-LM binary...");
    const downloadUrl = getBinaryDownloadUrl(platform2.binaryName);
    debugLogger.log(`Downloading from: ${downloadUrl}`);
    try {
      const binDir = path4.dirname(binaryPath);
      fs3.mkdirSync(binDir, { recursive: true });
      await downloadFile(downloadUrl, binaryPath);
      log(import_chalk10.default.green("  \u2713 Binary downloaded successfully"));
    } catch (error) {
      logError(
        import_chalk10.default.red(
          `  \u2717 Failed to download binary: ${error instanceof Error ? error.message : String(error)}`
        )
      );
      logError("  Check your internet connection and try again.");
      return 1;
    }
    const expectedHash = PLATFORM_BINARY_SHA256[platform2.binaryName];
    if (!expectedHash) {
      logError(
        import_chalk10.default.red(
          `  \u2717 No checksum is configured for ${platform2.binaryName}. Refusing to install the binary.`
        )
      );
      try {
        fs3.rmSync(binaryPath, { force: true });
      } catch {
      }
      return 1;
    }
    try {
      const checksumVerified = await verifyFileSha256(binaryPath, expectedHash);
      if (!checksumVerified) {
        logError(
          import_chalk10.default.red(
            "  \u2717 Downloaded binary checksum did not match the expected release hash."
          )
        );
        try {
          fs3.rmSync(binaryPath, { force: true });
        } catch {
        }
        return 1;
      }
      log(import_chalk10.default.green("  \u2713 Binary checksum verified"));
    } catch (error) {
      logError(
        import_chalk10.default.red(
          `  \u2717 Failed to verify binary checksum: ${error instanceof Error ? error.message : String(error)}`
        )
      );
      try {
        fs3.rmSync(binaryPath, { force: true });
      } catch {
      }
      return 1;
    }
    if (process.platform !== "win32") {
      try {
        fs3.chmodSync(binaryPath, 493);
      } catch (error) {
        logError(
          import_chalk10.default.red(
            `  \u2717 Failed to set executable permission: ${error instanceof Error ? error.message : String(error)}`
          )
        );
        return 1;
      }
    }
    if (process.platform === "darwin") {
      try {
        execFileSync("xattr", ["-d", "com.apple.quarantine", binaryPath], {
          stdio: "ignore"
        });
        log(import_chalk10.default.green("  \u2713 macOS quarantine attribute removed"));
      } catch {
      }
    }
  }
  if (!argv.skipModel) {
    const modelAlreadyDownloaded = isModelDownloaded(binaryPath);
    if (modelAlreadyDownloaded && !force) {
      log("");
      log(import_chalk10.default.green(`  \u2713 Model ${GEMMA_MODEL_NAME} already downloaded`));
    } else {
      log("");
      log(`  Downloading model ${GEMMA_MODEL_NAME}...`);
      log(import_chalk10.default.dim("  You may be prompted to accept the Gemma Terms of Use."));
      log("");
      const exitCode = await spawnInherited(binaryPath, [
        "pull",
        GEMMA_MODEL_NAME
      ]);
      if (exitCode !== 0) {
        logError("");
        logError(
          import_chalk10.default.red(`  \u2717 Model download failed (exit code ${exitCode})`)
        );
        return 1;
      }
      log("");
      log(import_chalk10.default.green(`  \u2713 Model ${GEMMA_MODEL_NAME} downloaded`));
    }
  }
  log("");
  log("  Configuring settings...");
  try {
    const settings = loadSettings(process.cwd());
    const existingUserGemma = settings.forScope("User" /* User */).settings.experimental?.gemmaModelRouter ?? {};
    autoStartServer = existingUserGemma.autoStartServer ?? true;
    const existingUserExperimental = settings.forScope("User" /* User */).settings.experimental ?? {};
    settings.setValue("User" /* User */, "experimental", {
      ...existingUserExperimental,
      gemmaModelRouter: {
        autoStartServer,
        ...existingUserGemma.binaryPath !== void 0 ? { binaryPath: existingUserGemma.binaryPath } : {}
      }
    });
    const existingWorkspaceGemma = settings.forScope("Workspace" /* Workspace */).settings.experimental?.gemmaModelRouter ?? {};
    const existingWorkspaceExperimental = settings.forScope("Workspace" /* Workspace */).settings.experimental ?? {};
    settings.setValue("Workspace" /* Workspace */, "experimental", {
      ...existingWorkspaceExperimental,
      gemmaModelRouter: {
        ...existingWorkspaceGemma,
        enabled: true,
        classifier: {
          ...existingWorkspaceGemma.classifier,
          host: `http://localhost:${port}`,
          model: GEMMA_MODEL_NAME
        }
      }
    });
    log(import_chalk10.default.green("  \u2713 Settings updated"));
    log(import_chalk10.default.dim("    User (~/.gemini/settings.json): autoStartServer"));
    log(
      import_chalk10.default.dim("    Workspace (.gemini/settings.json): enabled, classifier")
    );
    settingsUpdated = true;
  } catch (error) {
    logError(
      import_chalk10.default.red(
        `  \u2717 Failed to update settings: ${error instanceof Error ? error.message : String(error)}`
      )
    );
    logError(
      "  You can manually add the configuration to ~/.gemini/settings.json"
    );
  }
  if (argv.start) {
    log("");
    log("  Starting LiteRT server...");
    serverStarted = await startServer(binaryPath, port);
    if (serverStarted) {
      log(import_chalk10.default.green(`  \u2713 Server started on port ${port}`));
    } else {
      log(
        import_chalk10.default.yellow(
          `  ! Server may not have started correctly. Check: gemini gemma status`
        )
      );
    }
  }
  const routingActive = settingsUpdated && serverStarted;
  const setupSucceeded = settingsUpdated && (!argv.start || serverStarted);
  log("");
  log(import_chalk10.default.dim("\u2500".repeat(40)));
  if (routingActive) {
    log(import_chalk10.default.bold.green("  Setup complete! Local model routing is active."));
  } else if (settingsUpdated) {
    log(
      import_chalk10.default.bold.green("  Setup complete! Local model routing is configured.")
    );
  } else {
    log(
      import_chalk10.default.bold.yellow(
        "  Setup incomplete. Manual settings changes are still required."
      )
    );
  }
  log("");
  log("  How it works: Every request is classified by the local Gemma model.");
  log(
    "  Simple tasks (file reads, quick edits) route to " + import_chalk10.default.cyan("Flash") + " for speed."
  );
  log(
    "  Complex tasks (debugging, architecture) route to " + import_chalk10.default.cyan("Pro") + " for quality."
  );
  log("  This happens automatically \u2014 just use the CLI as usual.");
  log("");
  if (!settingsUpdated) {
    log(
      import_chalk10.default.yellow(
        '  Fix the settings update above, then rerun "gemini gemma status".'
      )
    );
    log("");
  } else if (!argv.start) {
    log(import_chalk10.default.yellow('  Note: Run "gemini gemma start" to start the server.'));
    if (autoStartServer) {
      log(
        import_chalk10.default.yellow(
          "  Or restart the CLI to auto-start it on the next launch."
        )
      );
    }
    log("");
  } else if (!serverStarted) {
    log(
      import_chalk10.default.yellow(
        '  Review the server logs and rerun "gemini gemma start" after fixing the issue.'
      )
    );
    log("");
  }
  log("  Useful commands:");
  log(import_chalk10.default.dim("    gemini gemma status   Check routing status"));
  log(import_chalk10.default.dim("    gemini gemma start    Start the LiteRT server"));
  log(import_chalk10.default.dim("    gemini gemma stop     Stop the LiteRT server"));
  log(import_chalk10.default.dim("    /gemma               Check status inside a session"));
  log("");
  return setupSucceeded ? 0 : 1;
}
var setupCommand = {
  command: "setup",
  describe: "Download and configure Gemma local model routing",
  builder: (yargs) => yargs.option("port", {
    type: "number",
    default: DEFAULT_PORT,
    description: "Port for the LiteRT server"
  }).option("skip-model", {
    type: "boolean",
    default: false,
    description: "Skip model download (binary only)"
  }).option("start", {
    type: "boolean",
    default: true,
    description: "Start the server after setup"
  }).option("force", {
    type: "boolean",
    default: false,
    description: "Re-download binary and model even if already present"
  }).option("consent", {
    type: "boolean",
    default: false,
    description: "Skip interactive consent prompt (implies acceptance)"
  }),
  handler: async (argv) => {
    const exitCode = await handleSetup({
      port: Number(argv["port"]),
      skipModel: Boolean(argv["skipModel"]),
      start: Boolean(argv["start"]),
      force: Boolean(argv["force"]),
      consent: Boolean(argv["consent"])
    });
    await exitCli(exitCode);
  }
};

// packages/cli/src/commands/gemma/stop.ts
var import_chalk11 = __toESM(require_source(), 1);
import fs4 from "node:fs";
async function stopServer(expectedPort) {
  const processInfo = readServerProcessInfo();
  const pidPath = getPidFilePath();
  if (!processInfo) {
    return "not-running";
  }
  const { pid } = processInfo;
  if (!isProcessRunning(pid)) {
    debugLogger.log(
      `Stale PID file found (PID ${pid} is not running), removing ${pidPath}`
    );
    try {
      fs4.unlinkSync(pidPath);
    } catch {
    }
    return "not-running";
  }
  const binaryPath = processInfo.binaryPath ?? getBinaryPath();
  const port = processInfo.port ?? expectedPort;
  if (!isExpectedLiteRtServerProcess(pid, { binaryPath, port })) {
    debugLogger.warn(
      `Refusing to stop PID ${pid} because it does not match the expected LiteRT server process.`
    );
    return "unexpected-process";
  }
  try {
    process.kill(pid, "SIGTERM");
  } catch {
    return "failed";
  }
  await new Promise((resolve9) => setTimeout(resolve9, 1e3));
  if (isProcessRunning(pid)) {
    try {
      process.kill(pid, "SIGKILL");
    } catch {
    }
    await new Promise((resolve9) => setTimeout(resolve9, 500));
    if (isProcessRunning(pid)) {
      return "failed";
    }
  }
  try {
    fs4.unlinkSync(pidPath);
  } catch {
  }
  return "stopped";
}
var stopCommand = {
  command: "stop",
  describe: "Stop the LiteRT-LM server",
  builder: (yargs) => yargs.option("port", {
    type: "number",
    description: "Port where the LiteRT server is running"
  }),
  handler: async (argv) => {
    let port;
    if (argv["port"] !== void 0) {
      port = Number(argv["port"]);
    }
    if (!port) {
      const { configuredPort } = resolveGemmaConfig(DEFAULT_PORT);
      port = configuredPort;
    }
    const processInfo = readServerProcessInfo();
    const pid = processInfo?.pid ?? readServerPid();
    if (pid !== null && isProcessRunning(pid)) {
      debugLogger.log(`Stopping LiteRT server (PID ${pid})...`);
      const result = await stopServer(port);
      if (result === "stopped") {
        debugLogger.log(import_chalk11.default.green("LiteRT server stopped."));
        await exitCli(0);
      } else if (result === "unexpected-process") {
        debugLogger.error(
          import_chalk11.default.red(
            `Refusing to stop PID ${pid} because it does not match the expected LiteRT server process.`
          )
        );
        debugLogger.error(
          import_chalk11.default.dim(
            "Remove the stale pid file after verifying the process, or stop the process manually."
          )
        );
        await exitCli(1);
      } else {
        debugLogger.error(import_chalk11.default.red("Failed to stop LiteRT server."));
        await exitCli(1);
      }
      return;
    }
    const running = await isServerRunning(port);
    if (running) {
      debugLogger.log(
        import_chalk11.default.yellow(
          `A server is responding on port ${port}, but it was not started by "gemini gemma start".`
        )
      );
      debugLogger.log(
        import_chalk11.default.dim(
          "If you started it manually, stop it from the terminal where it is running."
        )
      );
      await exitCli(1);
    } else {
      debugLogger.log("No LiteRT server is currently running.");
      await exitCli(0);
    }
  }
};

// packages/cli/src/commands/gemma/logs.ts
import fs5 from "node:fs";
import { spawn } from "node:child_process";
async function readLastLines(filePath, count) {
  if (count <= 0) {
    return "";
  }
  const CHUNK_SIZE = 64 * 1024;
  const fileHandle = await fs5.promises.open(filePath, fs5.constants.O_RDONLY);
  try {
    const stats = await fileHandle.stat();
    if (stats.size === 0) {
      return "";
    }
    const chunks = [];
    let totalBytes = 0;
    let newlineCount = 0;
    let position = stats.size;
    while (position > 0 && newlineCount <= count) {
      const readSize = Math.min(CHUNK_SIZE, position);
      position -= readSize;
      const buffer = Buffer.allocUnsafe(readSize);
      const { bytesRead } = await fileHandle.read(
        buffer,
        0,
        readSize,
        position
      );
      if (bytesRead === 0) {
        break;
      }
      const chunk = bytesRead === readSize ? buffer : buffer.subarray(0, bytesRead);
      chunks.unshift(chunk);
      totalBytes += chunk.length;
      for (const byte of chunk) {
        if (byte === 10) {
          newlineCount += 1;
        }
      }
    }
    const content = Buffer.concat(chunks, totalBytes).toString("utf-8");
    const lines = content.split("\n");
    if (position > 0 && lines.length > 0) {
      const boundary = Buffer.allocUnsafe(1);
      const { bytesRead } = await fileHandle.read(boundary, 0, 1, position - 1);
      if (bytesRead === 1 && boundary[0] !== 10) {
        lines.shift();
      }
    }
    if (lines.length > 0 && lines[lines.length - 1] === "") {
      lines.pop();
    }
    if (lines.length === 0) {
      return "";
    }
    return lines.slice(-count).join("\n") + "\n";
  } finally {
    await fileHandle.close();
  }
}
function waitForChild(child) {
  return new Promise((resolve9, reject) => {
    child.once("error", reject);
    child.once("close", (code) => resolve9(code ?? 1));
  });
}
async function runTail(logPath, lines, follow) {
  const tailArgs = follow ? ["-f", "-n", String(lines), logPath] : ["-n", String(lines), logPath];
  const child = spawn("tail", tailArgs, { stdio: "inherit" });
  if (!follow) {
    return waitForChild(child);
  }
  const handleSigint = () => {
    child.kill("SIGTERM");
  };
  process.once("SIGINT", handleSigint);
  try {
    return await waitForChild(child);
  } finally {
    process.off("SIGINT", handleSigint);
  }
}
var logsCommand = {
  command: "logs",
  describe: "View LiteRT-LM server logs",
  builder: (yargs) => yargs.option("lines", {
    alias: "n",
    type: "number",
    description: "Show the last N lines and exit (omit to follow live)"
  }).option("follow", {
    alias: "f",
    type: "boolean",
    description: "Follow log output (defaults to true when --lines is omitted)"
  }),
  handler: async (argv) => {
    const logPath = getLogFilePath();
    try {
      await fs5.promises.access(logPath, fs5.constants.F_OK);
    } catch {
      debugLogger.log(`No log file found at ${logPath}`);
      debugLogger.log(
        "Is the LiteRT server running? Start it with: gemini gemma start"
      );
      await exitCli(1);
      return;
    }
    const lines = argv.lines;
    const follow = argv.follow ?? lines === void 0;
    const requestedLines = lines ?? 20;
    if (follow && process.platform === "win32") {
      debugLogger.log(
        "Live log following is not supported on Windows. Use --lines N to view recent logs."
      );
      await exitCli(1);
      return;
    }
    if (process.platform === "win32") {
      process.stdout.write(await readLastLines(logPath, requestedLines));
      await exitCli(0);
      return;
    }
    try {
      if (follow) {
        debugLogger.log(`Tailing ${logPath} (Ctrl+C to stop)
`);
      }
      const exitCode = await runTail(logPath, requestedLines, follow);
      await exitCli(exitCode);
    } catch (error) {
      if (error instanceof Error && "code" in error && error.code === "ENOENT") {
        if (!follow) {
          process.stdout.write(await readLastLines(logPath, requestedLines));
          await exitCli(0);
        } else {
          debugLogger.error(
            '"tail" command not found. Use --lines N to view recent logs without tail.'
          );
          await exitCli(1);
        }
      } else {
        debugLogger.error(
          `Failed to read log output: ${error instanceof Error ? error.message : String(error)}`
        );
        await exitCli(1);
      }
    }
  }
};

// packages/cli/src/commands/gemma.ts
var gemmaCommand = {
  command: "gemma",
  describe: "Manage local Gemma model routing",
  builder: (yargs) => yargs.middleware((argv) => {
    initializeOutputListenersAndFlush();
    argv["isCommand"] = true;
  }).command(defer(setupCommand, "gemma")).command(defer(startCommand, "gemma")).command(defer(stopCommand, "gemma")).command(defer(statusCommand, "gemma")).command(defer(logsCommand, "gemma")).demandCommand(1, "You need at least one command before continuing.").version(false),
  handler: () => {
  }
};

// packages/cli/src/config/sandboxConfig.ts
var import_command_exists = __toESM(require_command_exists(), 1);
import * as os from "node:os";
import { fileURLToPath as fileURLToPath3 } from "node:url";
import path5 from "node:path";
var __filename2 = fileURLToPath3(import.meta.url);
var __dirname3 = path5.dirname(__filename2);
var VALID_SANDBOX_COMMANDS = [
  "docker",
  "podman",
  "sandbox-exec",
  "runsc",
  "lxc",
  "windows-native"
];
function isSandboxCommand(value) {
  return VALID_SANDBOX_COMMANDS.includes(
    value
  );
}
function getSandboxCommand(sandbox) {
  if (process.env["SANDBOX"]) {
    return "";
  }
  const environmentConfiguredSandbox = process.env["GEMINI_SANDBOX"]?.toLowerCase().trim() ?? "";
  sandbox = environmentConfiguredSandbox?.length > 0 ? environmentConfiguredSandbox : sandbox;
  if (sandbox === "1" || sandbox === "true") sandbox = true;
  else if (sandbox === "0" || sandbox === "false" || !sandbox) sandbox = false;
  if (sandbox === false) {
    return "";
  }
  if (typeof sandbox === "string" && sandbox) {
    if (!isSandboxCommand(sandbox)) {
      throw new FatalSandboxError(
        `Invalid sandbox command '${sandbox}'. Must be one of ${VALID_SANDBOX_COMMANDS.join(
          ", "
        )}`
      );
    }
    if (sandbox === "runsc" && os.platform() !== "linux") {
      throw new FatalSandboxError(
        "gVisor (runsc) sandboxing is only supported on Linux"
      );
    }
    if (sandbox === "windows-native" && os.platform() !== "win32") {
      throw new FatalSandboxError(
        "Windows native sandboxing is only supported on Windows"
      );
    }
    if (sandbox !== "windows-native" && !import_command_exists.default.sync(sandbox)) {
      throw new FatalSandboxError(
        `Missing sandbox command '${sandbox}' (from GEMINI_SANDBOX)`
      );
    }
    if (sandbox === "runsc" && !import_command_exists.default.sync("docker")) {
      throw new FatalSandboxError(
        "runsc (gVisor) requires Docker. Install Docker, or use sandbox: 'docker'."
      );
    }
    return sandbox;
  }
  if (os.platform() === "darwin" && import_command_exists.default.sync("sandbox-exec")) {
    return "sandbox-exec";
  } else if (import_command_exists.default.sync("docker") && sandbox === true) {
    return "docker";
  } else if (import_command_exists.default.sync("podman") && sandbox === true) {
    return "podman";
  }
  if (sandbox === true) {
    throw new FatalSandboxError(
      "GEMINI_SANDBOX is true but failed to determine command for sandbox; install docker or podman or specify command in GEMINI_SANDBOX"
    );
  }
  return "";
}
async function loadSandboxConfig(settings, argv) {
  const sandboxOption = argv.sandbox ?? settings.tools?.sandbox;
  let sandboxValue;
  let allowedPaths = [];
  let networkAccess = true;
  let customImage;
  if (typeof sandboxOption === "object" && sandboxOption !== null && !Array.isArray(sandboxOption)) {
    const config2 = sandboxOption;
    sandboxValue = config2.enabled ? config2.command ?? true : false;
    allowedPaths = config2.allowedPaths ?? [];
    networkAccess = config2.networkAccess ?? true;
    customImage = config2.image;
  } else if (typeof sandboxOption !== "object" || sandboxOption === null) {
    sandboxValue = sandboxOption;
  }
  const command2 = getSandboxCommand(sandboxValue);
  const packageJson = await getPackageJson(__dirname3);
  const image = process.env["GEMINI_SANDBOX_IMAGE"] ?? "us-docker.pkg.dev/gemini-code-dev/gemini-cli/sandbox:0.50.0-preview.1" ?? customImage ?? packageJson?.config?.sandboxImageUri;
  const isNative = command2 === "windows-native" || command2 === "sandbox-exec" || command2 === "lxc";
  return command2 && (image || isNative) ? { enabled: true, allowedPaths, networkAccess, command: command2, image } : void 0;
}

// packages/cli/src/utils/resolvePath.ts
import * as path6 from "node:path";
function resolvePath(p) {
  if (!p) {
    return "";
  }
  let expandedPath = p;
  if (p.toLowerCase().startsWith("%userprofile%")) {
    expandedPath = homedir() + p.substring("%userprofile%".length);
  } else if (p === "~" || p.startsWith("~/")) {
    expandedPath = homedir() + p.substring(1);
  }
  return path6.normalize(expandedPath);
}

// packages/cli/src/config/policy.ts
var autoAcceptWorkspacePolicies = true;
var disableWorkspacePolicies = true;
async function createPolicyEngineConfig2(settings, approvalMode, workspacePoliciesDir, interactive = true) {
  const policySettings = {
    mcp: settings.mcp,
    tools: settings.tools,
    mcpServers: settings.mcpServers,
    policyPaths: settings.policyPaths,
    adminPolicyPaths: settings.adminPolicyPaths,
    workspacePoliciesDir,
    disableAlwaysAllow: settings.security?.disableAlwaysAllow || settings.admin?.secureModeEnabled
  };
  return createPolicyEngineConfig(
    policySettings,
    approvalMode,
    void 0,
    interactive
  );
}
function createPolicyUpdater2(policyEngine, messageBus, storage) {
  return createPolicyUpdater(policyEngine, messageBus, storage);
}
async function resolveWorkspacePolicyState(options) {
  const { cwd, trustedFolder, interactive } = options;
  let workspacePoliciesDir;
  let policyUpdateConfirmationRequest;
  if (trustedFolder && !disableWorkspacePolicies) {
    const storage = new Storage(cwd);
    if (storage.isWorkspaceHomeDir()) {
      return { workspacePoliciesDir: void 0 };
    }
    const potentialWorkspacePoliciesDir = storage.getWorkspacePoliciesDir();
    const integrityManager = new PolicyIntegrityManager();
    const integrityResult = await integrityManager.checkIntegrity(
      "workspace",
      cwd,
      potentialWorkspacePoliciesDir
    );
    if (integrityResult.status === "MATCH" /* MATCH */) {
      workspacePoliciesDir = potentialWorkspacePoliciesDir;
    } else if (integrityResult.status === "NEW" /* NEW */ && integrityResult.fileCount === 0) {
      workspacePoliciesDir = void 0;
    } else if (interactive && !autoAcceptWorkspacePolicies) {
      policyUpdateConfirmationRequest = {
        scope: "workspace",
        identifier: cwd,
        policyDir: potentialWorkspacePoliciesDir,
        newHash: integrityResult.hash
      };
    } else {
      await integrityManager.acceptIntegrity(
        "workspace",
        cwd,
        integrityResult.hash
      );
      workspacePoliciesDir = potentialWorkspacePoliciesDir;
      if (!interactive) {
        writeToStderr(
          "WARNING: Workspace policies changed or are new. Automatically accepting and loading them.\n"
        );
      } else {
        debugLogger.warn(
          "Workspace policies changed or are new. Automatically accepting and loading them."
        );
      }
    }
  }
  return { workspacePoliciesDir, policyUpdateConfirmationRequest };
}

// packages/cli/src/config/config.ts
var coerceCommaSeparated = (values) => {
  if (values.length === 1 && values[0] === "") {
    return [""];
  }
  return values.flatMap(
    (v) => v.split(",").map((s) => s.trim()).filter(Boolean)
  );
};
function getWorktreeArg(argv) {
  const result = yargs_default(hideBin(argv)).help(false).version(false).option("worktree", { alias: "w", type: "string" }).strict(false).exitProcess(false).parseSync();
  if (result.worktree === void 0) return void 0;
  return typeof result.worktree === "string" ? result.worktree.trim() : "";
}
function getRequestedWorktreeName(settings) {
  if (!isWorktreeEnabled(settings)) {
    return void 0;
  }
  return getWorktreeArg(process4.argv);
}
async function parseArguments(settings) {
  const rawArgv = hideBin(process4.argv);
  const startupMessages = [];
  const yargsInstance = yargs_default(rawArgv).locale("en").scriptName("gemini").usage(
    "Usage: gemini [options] [command]\n\nGemini CLI - Defaults to interactive mode. Use -p/--prompt for non-interactive (headless) mode."
  ).option("isCommand", {
    type: "boolean",
    hidden: true,
    description: "Internal flag to indicate if a subcommand is being run"
  }).option("debug", {
    alias: "d",
    type: "boolean",
    description: "Run in debug mode (open debug console with F12)",
    default: false
  }).middleware((argv) => {
    const commandModules = [
      mcpCommand,
      extensionsCommand,
      skillsCommand,
      hooksCommand,
      gemmaCommand
    ];
    const subcommands = commandModules.flatMap((mod) => {
      const names = [];
      const cmd = mod.command;
      if (cmd) {
        if (Array.isArray(cmd)) {
          for (const c of cmd) {
            names.push(String(c).split(" ")[0]);
          }
        } else {
          names.push(String(cmd).split(" ")[0]);
        }
      }
      const aliases = mod.aliases;
      if (aliases) {
        if (Array.isArray(aliases)) {
          for (const a of aliases) {
            names.push(String(a).split(" ")[0]);
          }
        } else {
          names.push(String(aliases).split(" ")[0]);
        }
      }
      return names;
    });
    const firstArg = argv._[0];
    if (typeof firstArg === "string" && subcommands.includes(firstArg)) {
      argv["isCommand"] = true;
    }
  }, true).fail((msg, err) => {
    if (err) throw err;
    throw new Error(msg);
  }).check((argv) => {
    const queryArg2 = argv["query"];
    const query = typeof queryArg2 === "string" || Array.isArray(queryArg2) ? queryArg2 : void 0;
    const hasPositionalQuery = Array.isArray(query) ? query.length > 0 : !!query;
    const sessionFlags = [
      argv["resume"] !== void 0,
      argv["session-id"] !== void 0,
      argv["session-file"] !== void 0
    ].filter(Boolean).length;
    if (sessionFlags > 1) {
      return "The flags --resume, --session-id, and --session-file are mutually exclusive. Please provide only one.";
    }
    if (argv["prompt"] && hasPositionalQuery) {
      return "Cannot use both a positional prompt and the --prompt (-p) flag together";
    }
    if (argv["prompt"] && argv["promptInteractive"]) {
      return "Cannot use both --prompt (-p) and --prompt-interactive (-i) together";
    }
    if (argv["yolo"] && argv["approvalMode"]) {
      return "Cannot use both --yolo (-y) and --approval-mode together. Use --approval-mode=yolo instead.";
    }
    const outputFormat = argv["outputFormat"];
    if (typeof outputFormat === "string" && !["text", "json", "stream-json"].includes(outputFormat)) {
      return `Invalid values:
  Argument: output-format, Given: "${outputFormat}", Choices: "text", "json", "stream-json"`;
    }
    if (argv["worktree"] && !settings.experimental?.worktrees) {
      return "The --worktree flag is only available when experimental.worktrees is enabled in your settings.";
    }
    return true;
  });
  yargsInstance.command(mcpCommand);
  yargsInstance.command(extensionsCommand);
  yargsInstance.command(skillsCommand);
  yargsInstance.command(hooksCommand);
  yargsInstance.command(gemmaCommand);
  yargsInstance.command(
    "$0 [query..]",
    "Launch Gemini CLI",
    (yargsInstance2) => yargsInstance2.positional("query", {
      description: "Initial prompt. Runs in interactive mode by default; use -p/--prompt for non-interactive."
    }).option("model", {
      alias: "m",
      type: "string",
      nargs: 1,
      description: `Model`
    }).option("prompt", {
      alias: "p",
      type: "string",
      nargs: 1,
      description: "Run in non-interactive (headless) mode with the given prompt. Appended to input on stdin (if any)."
    }).option("prompt-interactive", {
      alias: "i",
      type: "string",
      nargs: 1,
      description: "Execute the provided prompt and continue in interactive mode"
    }).option("skip-trust", {
      type: "boolean",
      description: "Trust the current workspace for this session.",
      default: false
    }).option("worktree", {
      alias: "w",
      type: "string",
      skipValidation: true,
      description: "Start Gemini in a new git worktree. If no name is provided, one is generated automatically.",
      coerce: (value) => {
        const trimmed = typeof value === "string" ? value.trim() : "";
        if (trimmed === "") {
          return Math.random().toString(36).substring(2, 10);
        }
        return trimmed;
      }
    }).option("sandbox", {
      alias: "s",
      type: "boolean",
      description: "Run in sandbox?"
    }).option("yolo", {
      alias: "y",
      type: "boolean",
      description: "Automatically accept all actions (aka YOLO mode, see https://www.youtube.com/watch?v=xvFZjo5PgG0 for more details)?",
      default: false
    }).option("approval-mode", {
      type: "string",
      nargs: 1,
      choices: ["default", "auto_edit", "yolo", "plan"],
      description: "Set the approval mode: default (prompt for approval), auto_edit (auto-approve edit tools), yolo (auto-approve all tools), plan (read-only mode)"
    }).option("policy", {
      type: "array",
      string: true,
      nargs: 1,
      description: "Additional policy files or directories to load (comma-separated or multiple --policy)",
      coerce: coerceCommaSeparated
    }).option("admin-policy", {
      type: "array",
      string: true,
      nargs: 1,
      description: "Additional admin policy files or directories to load (comma-separated or multiple --admin-policy)",
      coerce: coerceCommaSeparated
    }).option("acp", {
      type: "boolean",
      description: "Starts the agent in ACP mode"
    }).option("experimental-acp", {
      type: "boolean",
      description: "Starts the agent in ACP mode (deprecated, use --acp instead)"
    }).option("allowed-mcp-server-names", {
      type: "array",
      string: true,
      nargs: 1,
      description: "Allowed MCP server names",
      coerce: coerceCommaSeparated
    }).option("allowed-tools", {
      type: "array",
      string: true,
      nargs: 1,
      description: "[DEPRECATED: Use Policy Engine instead See https://geminicli.com/docs/core/policy-engine] Tools that are allowed to run without confirmation",
      coerce: coerceCommaSeparated
    }).option("extensions", {
      alias: "e",
      type: "array",
      string: true,
      nargs: 1,
      description: "A list of extensions to use. If not provided, all extensions are used.",
      coerce: coerceCommaSeparated
    }).option("list-extensions", {
      alias: "l",
      type: "boolean",
      description: "List all available extensions and exit."
    }).option("resume", {
      alias: "r",
      type: "string",
      // `skipValidation` so that we can distinguish between it being passed with a value, without
      // one, and not being passed at all.
      skipValidation: true,
      description: 'Resume a previous session. Use "latest" for most recent or index number (e.g. --resume 5)',
      coerce: (value) => {
        const trimmed = value.trim();
        if (trimmed === "") {
          return RESUME_LATEST;
        }
        return trimmed;
      }
    }).option("session-file", {
      type: "string",
      nargs: 1,
      description: "Load a session from a JSON file"
    }).option("session-id", {
      type: "string",
      nargs: 1,
      description: "Start a new session with a manually provided UUID.",
      coerce: (value) => {
        const trimmed = value.trim();
        if (!trimmed) {
          throw new Error("The --session-id option cannot be empty.");
        }
        if (!/^[a-zA-Z0-9-_]+$/.test(trimmed)) {
          throw new Error(
            'Invalid session ID "' + trimmed + '": Only alphanumeric characters, dashes, and underscores are allowed.'
          );
        }
        return trimmed;
      }
    }).option("list-sessions", {
      type: "boolean",
      description: "List available sessions for the current project and exit."
    }).option("delete-session", {
      type: "string",
      description: "Delete a session by index number (use --list-sessions to see available sessions)."
    }).option("include-directories", {
      type: "array",
      string: true,
      nargs: 1,
      description: "Additional directories to include in the workspace (comma-separated or multiple --include-directories)",
      coerce: coerceCommaSeparated
    }).option("screen-reader", {
      type: "boolean",
      description: "Enable screen reader mode for accessibility."
    }).option("output-format", {
      alias: "o",
      type: "string",
      nargs: 1,
      description: "The format of the CLI output.",
      choices: ["text", "json", "stream-json"]
    }).option("fake-responses", {
      type: "string",
      description: "Path to a file with fake model responses for testing.",
      hidden: true
    }).option("fake-responses-non-strict", {
      type: "string",
      description: "Path to a file with fake model responses for testing (non-strict mode).",
      hidden: true
    }).option("record-responses", {
      type: "string",
      description: "Path to a file to record model responses for testing.",
      hidden: true
    }).option("raw-output", {
      type: "boolean",
      description: "Disable sanitization of model output (e.g. allow ANSI escape sequences). WARNING: This can be a security risk if the model output is untrusted."
    }).option("accept-raw-output-risk", {
      type: "boolean",
      description: "Suppress the security warning when using --raw-output."
    })
  ).version(await getVersion()).alias("v", "version").help().alias("h", "help").strict().demandCommand(0, 0).exitProcess(false);
  yargsInstance.wrap(yargsInstance.terminalWidth());
  let result;
  try {
    const parsed = await yargsInstance.parse();
    if (!isRecord(parsed)) {
      throw new Error("Failed to parse arguments");
    }
    result = parsed;
    if (result["skip-trust"]) {
      process4.env["GEMINI_CLI_TRUST_WORKSPACE"] = "true";
    }
  } catch (e) {
    const msg = getErrorMessage(e);
    debugLogger.error(msg);
    yargsInstance.showHelp();
    await runExitCleanup();
    process4.exit(1);
  }
  if (result["help"] || result["version"]) {
    await runExitCleanup();
    process4.exit(0);
  }
  const queryArg = result["query"];
  let q;
  if (Array.isArray(queryArg)) {
    q = queryArg.join(" ");
  } else if (typeof queryArg === "string") {
    q = queryArg;
  }
  if (q && !result["prompt"]) {
    if (!isHeadlessMode()) {
      startupMessages.push(
        "Positional arguments now default to interactive mode. To run in non-interactive mode, use the --prompt (-p) flag."
      );
      result["promptInteractive"] = q;
    } else {
      result["prompt"] = q;
    }
  }
  result["query"] = q || void 0;
  result["startupMessages"] = startupMessages;
  return result;
}
function isDebugMode(argv) {
  return argv.debug || [process4.env["DEBUG"], process4.env["DEBUG_MODE"]].some(
    (v) => v === "true" || v === "1"
  );
}
async function loadCliConfig(settings, sessionId, argv, options = {}) {
  const {
    cwd = process4.cwd(),
    projectHooks,
    skipExtensions = false,
    loadedSettings
  } = options;
  const debugMode = isDebugMode(argv);
  const worktreeSettings = options.worktreeSettings ?? await resolveWorktreeSettings(cwd);
  if (argv.sandbox) {
    process4.env["GEMINI_SANDBOX"] = "true";
  }
  const includeDirectoryTree = settings.context?.includeDirectoryTree ?? true;
  const ideMode = settings.ide?.enabled ?? false;
  const folderTrust = process4.env["GEMINI_CLI_INTEGRATION_TEST"] === "true" || process4.env["VITEST"] === "true" ? false : settings.security?.folderTrust?.enabled ?? false;
  const trustedFolder = isWorkspaceTrusted(settings, cwd, {
    prompt: argv.prompt,
    query: argv.query
  })?.isTrusted ?? false;
  if (settings.context?.fileName) {
    setGeminiMdFilename(settings.context.fileName);
  } else {
    resetGeminiMdFilename(DEFAULT_CONTEXT_FILENAME);
  }
  const fileService = new FileDiscoveryService(cwd);
  const fileFiltering = {
    ...DEFAULT_FILE_FILTERING_OPTIONS,
    ...settings.context?.fileFiltering
  };
  const includeDirectories = (settings.context?.includeDirectories || []).map(resolvePath).concat((argv.includeDirectories || []).map(resolvePath));
  const ideWorkspacePath = process4.env["GEMINI_CLI_IDE_WORKSPACE_PATH"];
  if (ideWorkspacePath) {
    const realCwd = resolveToRealPath(cwd);
    const ideFolders = ideWorkspacePath.split(path7.delimiter).filter((p) => {
      const trimmedPath = p.trim();
      if (!trimmedPath) return false;
      try {
        return resolveToRealPath(trimmedPath) !== realCwd;
      } catch (e) {
        debugLogger.debug(
          `[IDE] Skipping inaccessible workspace folder: ${trimmedPath} (${getErrorMessage(e)})`
        );
        return false;
      }
    });
    includeDirectories.push(...ideFolders);
  }
  let extensionManager;
  if (!skipExtensions) {
    extensionManager = new ExtensionManager({
      settings,
      requestConsent: requestConsentNonInteractive,
      requestSetting: promptForSetting,
      workspaceDir: cwd,
      enabledExtensionOverrides: argv.extensions,
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      eventEmitter: coreEvents,
      clientVersion: await getVersion()
    });
    await extensionManager.loadExtensions();
  }
  const extensionPlanSettings = extensionManager?.getExtensions()?.find((ext) => ext.isActive && ext.plan?.directory)?.plan;
  let extensionRegistryURI = process4.env["GEMINI_CLI_EXTENSION_REGISTRY_URI"] ?? (trustedFolder ? settings.experimental?.extensionRegistryURI : void 0);
  if (extensionRegistryURI && !extensionRegistryURI.startsWith("http")) {
    extensionRegistryURI = resolveToRealPath(
      path7.resolve(cwd, resolvePath(extensionRegistryURI))
    );
  }
  const finalExtensionLoader = extensionManager ?? new SimpleExtensionLoader([]);
  const question = argv.promptInteractive || argv.prompt || "";
  let approvalMode;
  const rawApprovalMode = argv.approvalMode || (argv.yolo ? "yolo" : void 0) || (settings.general?.defaultApprovalMode !== "yolo" ? settings.general?.defaultApprovalMode : void 0);
  if (rawApprovalMode) {
    switch (rawApprovalMode) {
      case "yolo":
        approvalMode = "yolo" /* YOLO */;
        break;
      case "auto_edit":
        approvalMode = "autoEdit" /* AUTO_EDIT */;
        break;
      case "plan":
        if (!(settings.general?.plan?.enabled ?? true)) {
          debugLogger.warn(
            'Approval mode "plan" is disabled in your settings. Falling back to "default".'
          );
          approvalMode = "default" /* DEFAULT */;
        } else {
          approvalMode = "plan" /* PLAN */;
        }
        break;
      case "default":
        approvalMode = "default" /* DEFAULT */;
        break;
      default:
        throw new Error(
          `Invalid approval mode: ${rawApprovalMode}. Valid values are: yolo, auto_edit, plan, default`
        );
    }
  } else {
    approvalMode = "default" /* DEFAULT */;
  }
  if (settings.security?.disableYoloMode || settings.admin?.secureModeEnabled) {
    if (approvalMode === "yolo" /* YOLO */) {
      if (settings.admin?.secureModeEnabled) {
        debugLogger.error(
          'YOLO mode is disabled by "secureModeEnabled" setting.'
        );
      } else {
        debugLogger.error(
          'YOLO mode is disabled by the "disableYolo" setting.'
        );
      }
      throw new FatalConfigError(
        getAdminErrorMessage(
          "YOLO mode",
          void 0
          /* config */
        )
      );
    }
  } else if (approvalMode === "yolo" /* YOLO */) {
    debugLogger.warn(
      "YOLO mode is enabled. All tool calls will be automatically approved."
    );
  }
  if (!trustedFolder && approvalMode !== "default" /* DEFAULT */) {
    debugLogger.warn(
      `Approval mode overridden to "default" because the current folder is not trusted.`
    );
    approvalMode = "default" /* DEFAULT */;
  }
  let telemetrySettings;
  try {
    telemetrySettings = await resolveTelemetrySettings({
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      env: process4.env,
      settings: settings.telemetry
    });
  } catch (err) {
    if (err instanceof FatalConfigError) {
      throw new FatalConfigError(
        `Invalid telemetry configuration: ${err.message}.`
      );
    }
    throw err;
  }
  const interactive = !!argv.promptInteractive || !!argv.acp || !!argv.experimentalAcp || !isHeadlessMode({ prompt: argv.prompt, query: argv.query }) && !argv.isCommand;
  const allowedTools = argv.allowedTools || settings.tools?.allowed || [];
  const isAcpMode = !!argv.acp || !!argv.experimentalAcp;
  const extraExcludes = [];
  if (!interactive || isAcpMode) {
    extraExcludes.push(ASK_USER_TOOL_NAME);
  }
  const excludeTools = mergeExcludeTools(settings, extraExcludes);
  const effectiveSettings = {
    ...settings,
    tools: {
      ...settings.tools,
      allowed: allowedTools,
      exclude: excludeTools
    },
    mcp: {
      ...settings.mcp,
      allowed: argv.allowedMcpServerNames ?? settings.mcp?.allowed
    },
    policyPaths: (argv.policy ?? settings.policyPaths)?.map(
      (p) => resolvePath(p)
    ),
    adminPolicyPaths: (argv.adminPolicy ?? settings.adminPolicyPaths)?.map(
      (p) => resolvePath(p)
    )
  };
  const { workspacePoliciesDir, policyUpdateConfirmationRequest } = await resolveWorkspacePolicyState({
    cwd,
    trustedFolder,
    interactive
  });
  const policyEngineConfig = await createPolicyEngineConfig2(
    effectiveSettings,
    approvalMode,
    workspacePoliciesDir,
    interactive
  );
  const defaultModel = GEMINI_MODEL_ALIAS_AUTO;
  const rawModel = argv.model || process4.env["GEMINI_MODEL"] || settings.model?.name;
  const specifiedModel = Array.isArray(rawModel) ? String(rawModel.at(-1) ?? "").trim() || "" : rawModel === void 0 ? void 0 : String(rawModel ?? "").trim() || "";
  const resolvedModel = specifiedModel === GEMINI_MODEL_ALIAS_AUTO ? defaultModel : specifiedModel || defaultModel;
  const sandboxConfig = await loadSandboxConfig(settings, argv);
  if (sandboxConfig) {
    const existingPaths = sandboxConfig.allowedPaths || [];
    if (settings.tools.sandboxAllowedPaths?.length) {
      sandboxConfig.allowedPaths = [
        .../* @__PURE__ */ new Set([...existingPaths, ...settings.tools.sandboxAllowedPaths])
      ];
    }
    if (settings.tools.sandboxNetworkAccess !== void 0) {
      sandboxConfig.networkAccess = sandboxConfig.networkAccess || settings.tools.sandboxNetworkAccess;
    }
  }
  const screenReader = argv.screenReader !== void 0 ? argv.screenReader : settings.ui?.accessibility?.screenReader ?? false;
  const ptyInfo = await getPty();
  const mcpEnabled = settings.admin?.mcp?.enabled ?? true;
  const extensionsEnabled = settings.admin?.extensions?.enabled ?? true;
  const adminSkillsEnabled = settings.admin?.skills?.enabled ?? true;
  const mcpEnablementManager = McpServerEnablementManager.getInstance();
  const mcpEnablementCallbacks = mcpEnabled ? mcpEnablementManager.getEnablementCallbacks() : void 0;
  const adminAllowlist = settings.admin?.mcp?.config;
  let mcpServerCommand = mcpEnabled ? settings.mcp?.serverCommand : void 0;
  let mcpServers = mcpEnabled ? settings.mcpServers : {};
  if (mcpEnabled && adminAllowlist && Object.keys(adminAllowlist).length > 0) {
    const result = applyAdminAllowlist(mcpServers, adminAllowlist);
    mcpServers = result.mcpServers;
    mcpServerCommand = void 0;
    if (result.blockedServerNames && result.blockedServerNames.length > 0) {
      const message = getAdminBlockedMcpServersMessage(
        result.blockedServerNames,
        void 0
      );
      coreEvents.emitConsoleLog("warn", message);
    }
  }
  if (mcpEnabled) {
    const requiredMcpConfig = settings.admin?.mcp?.requiredConfig;
    if (requiredMcpConfig && Object.keys(requiredMcpConfig).length > 0) {
      const requiredResult = applyRequiredServers(
        mcpServers ?? {},
        requiredMcpConfig
      );
      mcpServers = requiredResult.mcpServers;
      if (requiredResult.requiredServerNames.length > 0) {
        coreEvents.emitConsoleLog(
          "info",
          `Admin-required MCP servers injected: ${requiredResult.requiredServerNames.join(", ")}`
        );
      }
    }
  }
  let clientName = void 0;
  if (isAcpMode) {
    const ide = detectIdeFromEnv();
    if (ide && (ide.name !== "vscode" || process4.env["TERM_PROGRAM"] === "vscode")) {
      clientName = `acp-${ide.name}`;
    } else {
      clientName = "acp";
    }
  } else if (argv.isCommand) {
    clientName = "cli-command";
  } else {
    clientName = "tui";
  }
  let profileSelector = void 0;
  if (settings.experimental?.stressTestProfile) {
    profileSelector = "stressTestProfile";
  } else if (settings.experimental?.powerUserProfile) {
    profileSelector = "powerUserProfile";
  } else if (settings.experimental?.generalistProfile || settings.experimental?.contextManagement) {
    profileSelector = "generalistProfile";
  }
  const contextManagement = {
    enabled: !!profileSelector
  };
  return new Config({
    acpMode: isAcpMode,
    clientName,
    sessionId,
    clientVersion: await getVersion(),
    embeddingModel: DEFAULT_GEMINI_EMBEDDING_MODEL,
    sandbox: sandboxConfig,
    toolSandboxing: settings.security?.toolSandboxing ?? false,
    targetDir: cwd,
    includeDirectoryTree,
    includeDirectories,
    loadMemoryFromIncludeDirectories: settings.context?.loadMemoryFromIncludeDirectories || false,
    discoveryMaxDirs: settings.context?.discoveryMaxDirs,
    memoryBoundaryMarkers: settings.context?.memoryBoundaryMarkers,
    importFormat: settings.context?.importFormat,
    debugMode,
    question,
    worktreeSettings,
    coreTools: settings.tools?.core || void 0,
    experimentalContextManagementConfig: profileSelector,
    allowedTools: allowedTools.length > 0 ? allowedTools : void 0,
    policyEngineConfig,
    policyUpdateConfirmationRequest,
    excludeTools,
    toolDiscoveryCommand: settings.tools?.discoveryCommand,
    toolCallCommand: settings.tools?.callCommand,
    mcpServerCommand,
    mcpServers,
    mcpEnablementCallbacks,
    mcpEnabled,
    extensionsEnabled,
    agents: settings.agents,
    adminSkillsEnabled,
    allowedMcpServers: mcpEnabled ? argv.allowedMcpServerNames ?? (loadedSettings ? loadedSettings.getConsolidatedAllowedMcpServers() : settings.mcp?.allowed) : void 0,
    blockedMcpServers: mcpEnabled ? argv.allowedMcpServerNames ? void 0 : loadedSettings ? loadedSettings.getConsolidatedExcludedMcpServers() : settings.mcp?.excluded : void 0,
    blockedEnvironmentVariables: settings.security?.environmentVariableRedaction?.blocked,
    allowedEnvironmentVariables: settings.security?.environmentVariableRedaction?.allowed,
    enableEnvironmentVariableRedaction: settings.security?.environmentVariableRedaction?.enabled,
    approvalMode,
    disableYoloMode: settings.security?.disableYoloMode || settings.admin?.secureModeEnabled,
    disableAlwaysAllow: settings.security?.disableAlwaysAllow || settings.admin?.secureModeEnabled,
    showMemoryUsage: settings.ui?.showMemoryUsage || false,
    accessibility: {
      ...settings.ui?.accessibility,
      screenReader
    },
    telemetry: telemetrySettings,
    usageStatisticsEnabled: settings.privacy?.usageStatisticsEnabled,
    fileFiltering,
    checkpointing: settings.general?.checkpointing?.enabled,
    proxy: process4.env["HTTPS_PROXY"] || process4.env["https_proxy"] || process4.env["HTTP_PROXY"] || process4.env["http_proxy"],
    cwd,
    fileDiscoveryService: fileService,
    bugCommand: settings.advanced?.bugCommand,
    model: resolvedModel,
    maxSessionTurns: settings.model?.maxSessionTurns,
    listExtensions: argv.listExtensions || false,
    listSessions: argv.listSessions || false,
    deleteSession: argv.deleteSession,
    enabledExtensions: argv.extensions,
    extensionLoader: finalExtensionLoader,
    extensionRegistryURI,
    enableExtensionReloading: settings.experimental?.extensionReloading,
    enableAgents: settings.experimental?.enableAgents,
    plan: settings.general?.plan?.enabled ?? true,
    voiceMode: settings.experimental?.voiceMode,
    tracker: settings.experimental?.taskTracker,
    directWebFetch: settings.experimental?.directWebFetch,
    planSettings: settings.general?.plan?.directory ? settings.general.plan : extensionPlanSettings ?? settings.general?.plan,
    enableEventDrivenScheduler: true,
    skillsSupport: settings.skills?.enabled ?? true,
    disabledSkills: settings.skills?.disabled,
    experimentalAutoMemory: settings.experimental?.autoMemory,
    experimentalGemma: settings.experimental?.gemma,
    contextManagement,
    modelSteering: settings.experimental?.modelSteering,
    topicUpdateNarration: settings.general?.topicUpdateNarration ?? settings.experimental?.topicUpdateNarration,
    noBrowser: !!process4.env["NO_BROWSER"],
    summarizeToolOutput: settings.model?.summarizeToolOutput,
    ideMode,
    disableLoopDetection: settings.model?.disableLoopDetection,
    compressionThreshold: settings.model?.compressionThreshold,
    folderTrust,
    interactive,
    trustedFolder,
    useBackgroundColor: settings.ui?.useBackgroundColor,
    useAlternateBuffer: settings.ui?.useAlternateBuffer,
    useTerminalBuffer: settings.ui?.terminalBuffer,
    useRenderProcess: settings.ui?.renderProcess,
    useRipgrep: settings.tools?.useRipgrep,
    enableInteractiveShell: settings.tools?.shell?.enableInteractiveShell,
    shellBackgroundCompletionBehavior: settings.tools?.shell?.backgroundCompletionBehavior,
    shellToolInactivityTimeout: settings.tools?.shell?.inactivityTimeout,
    enableShellOutputEfficiency: settings.tools?.shell?.enableShellOutputEfficiency ?? true,
    // In ACP mode, always skip the next-speaker check. This check triggers
    // recursive continuation turns inside GeminiClient.processTurn() that
    // conflict with ACP's explicit turn management via session/prompt,
    // causing infinite agent_thought_chunk loops.
    skipNextSpeakerCheck: isAcpMode || settings.model?.skipNextSpeakerCheck,
    truncateToolOutputThreshold: settings.tools?.truncateToolOutputThreshold,
    eventEmitter: coreEvents,
    useWriteTodos: argv.useWriteTodos ?? settings.useWriteTodos,
    output: {
      // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
      format: argv.outputFormat ?? settings.output?.format
    },
    gemmaModelRouter: settings.experimental?.gemmaModelRouter,
    adk: settings.experimental?.adk,
    fakeResponses: argv.fakeResponses,
    fakeResponsesNonStrict: argv.fakeResponsesNonStrict,
    recordResponses: argv.recordResponses,
    retryFetchErrors: settings.general?.retryFetchErrors,
    billing: settings.billing,
    vertexAiRouting: settings.billing?.vertexAi,
    maxAttempts: settings.general?.maxAttempts,
    ptyInfo: ptyInfo?.name,
    disableLLMCorrection: settings.tools?.disableLLMCorrection,
    rawOutput: argv.rawOutput,
    acceptRawOutputRisk: argv.acceptRawOutputRisk,
    dynamicModelConfiguration: settings.experimental?.dynamicModelConfiguration,
    modelConfigServiceConfig: settings.modelConfigs,
    // TODO: loading of hooks based on workspace trust
    enableHooks: settings.hooksConfig.enabled,
    enableHooksUI: settings.hooksConfig.enabled,
    hooks: settings.hooks || {},
    disabledHooks: settings.hooksConfig?.disabled || [],
    projectHooks: projectHooks || {},
    onModelChange: (model) => saveModelChange(loadSettings(cwd), model),
    onReload: async () => {
      const refreshedSettings = loadSettings(cwd);
      return {
        disabledSkills: refreshedSettings.merged.skills.disabled,
        agents: refreshedSettings.merged.agents
      };
    },
    enableConseca: settings.security?.enableConseca
  });
}
function mergeExcludeTools(settings, extraExcludes = []) {
  const allExcludeTools = /* @__PURE__ */ new Set([
    ...settings.tools.exclude || [],
    ...extraExcludes
  ]);
  return Array.from(allExcludeTools);
}
async function resolveWorktreeSettings(cwd) {
  let worktreePath;
  try {
    const { stdout } = await execa("git", ["rev-parse", "--show-toplevel"], {
      cwd
    });
    const toplevel = stdout.trim();
    const projectRoot = await getProjectRootForWorktree(toplevel);
    if (isGeminiWorktree(toplevel, projectRoot)) {
      worktreePath = toplevel;
    }
  } catch {
    return void 0;
  }
  if (!worktreePath) {
    return void 0;
  }
  let worktreeBaseSha;
  try {
    const { stdout } = await execa("git", ["rev-parse", "HEAD"], {
      cwd: worktreePath
    });
    worktreeBaseSha = stdout.trim();
  } catch (e) {
    debugLogger.debug(
      `Failed to resolve worktree base SHA at ${worktreePath}: ${getErrorMessage(e)}`
    );
  }
  if (!worktreeBaseSha) {
    return void 0;
  }
  return {
    name: path7.basename(worktreePath),
    path: worktreePath,
    baseSha: worktreeBaseSha
  };
}

// packages/cli/src/utils/readStdin.ts
function truncateUtf8Bytes(str, maxBytes) {
  const buf = Buffer.from(str, "utf8");
  if (buf.length <= maxBytes) return str;
  let end = maxBytes;
  while (end > 0 && (buf[end] & 192) === 128) {
    end--;
  }
  return buf.subarray(0, end).toString("utf8");
}
async function readStdin() {
  const MAX_STDIN_SIZE = 8 * 1024 * 1024;
  return new Promise((resolve9, reject) => {
    let data = "";
    let totalSize = 0;
    process.stdin.setEncoding("utf8");
    const pipedInputShouldBeAvailableInMs = 500;
    let pipedInputTimerId = setTimeout(() => {
      onEnd();
    }, pipedInputShouldBeAvailableInMs);
    const onReadable = () => {
      let chunk;
      while ((chunk = process.stdin.read()) !== null) {
        if (pipedInputTimerId) {
          clearTimeout(pipedInputTimerId);
          pipedInputTimerId = null;
        }
        const chunkByteLength = Buffer.byteLength(chunk, "utf8");
        if (totalSize + chunkByteLength > MAX_STDIN_SIZE) {
          const remainingBytes = MAX_STDIN_SIZE - totalSize;
          data += truncateUtf8Bytes(chunk, remainingBytes);
          debugLogger.warn(
            `Warning: stdin input truncated to ${MAX_STDIN_SIZE} bytes.`
          );
          process.stdin.destroy();
          onEnd();
          break;
        }
        data += chunk;
        totalSize += chunkByteLength;
      }
    };
    const onEnd = () => {
      cleanup();
      resolve9(data);
    };
    const onError = (err) => {
      cleanup();
      reject(err);
    };
    const cleanup = () => {
      if (pipedInputTimerId) {
        clearTimeout(pipedInputTimerId);
        pipedInputTimerId = null;
      }
      process.stdin.removeListener("readable", onReadable);
      process.stdin.removeListener("end", onEnd);
      process.stdin.removeListener("error", onError);
      if (process.stdin.listenerCount("error") === 0) {
        process.stdin.on("error", noopErrorHandler);
      }
    };
    process.stdin.on("readable", onReadable);
    process.stdin.on("end", onEnd);
    process.stdin.on("error", onError);
  });
}
function noopErrorHandler() {
}

// packages/cli/src/gemini.tsx
import { createHash as createHash2 } from "node:crypto";
import v8 from "node:v8";
import os6 from "node:os";
import dns from "node:dns";
import * as path15 from "node:path";
import * as fsPromises from "node:fs/promises";

// packages/cli/src/utils/sandbox.ts
var import_shell_quote2 = __toESM(require_shell_quote(), 1);
import {
  exec,
  execFile,
  execSync,
  spawn as spawn2,
  spawnSync
} from "node:child_process";
import path8 from "node:path";
import fs7 from "node:fs";
import os3 from "node:os";
import { fileURLToPath as fileURLToPath4 } from "node:url";
import { promisify } from "node:util";
import { randomBytes } from "node:crypto";

// packages/cli/src/utils/sandboxUtils.ts
var import_shell_quote = __toESM(require_shell_quote(), 1);
import os2 from "node:os";
import fs6 from "node:fs";
import { readFile } from "node:fs/promises";
var LOCAL_DEV_SANDBOX_IMAGE_NAME = "gemini-cli-sandbox";
var SANDBOX_NETWORK_NAME = "gemini-cli-sandbox";
var SANDBOX_PROXY_NAME = "gemini-cli-sandbox-proxy";
var BUILTIN_SEATBELT_PROFILES = [
  "permissive-open",
  "permissive-proxied",
  "restrictive-open",
  "restrictive-proxied",
  "strict-open",
  "strict-proxied"
];
function getContainerPath(hostPath) {
  if (os2.platform() !== "win32") {
    return hostPath;
  }
  const withForwardSlashes = hostPath.replace(/\\/g, "/");
  const match = withForwardSlashes.match(/^([A-Z]):\/(.*)/i);
  if (match) {
    return `/${match[1].toLowerCase()}/${match[2]}`;
  }
  return withForwardSlashes;
}
async function shouldUseCurrentUserInSandbox() {
  const envVar = process.env["SANDBOX_SET_UID_GID"]?.toLowerCase().trim();
  if (envVar === "1" || envVar === "true") {
    return true;
  }
  if (envVar === "0" || envVar === "false") {
    return false;
  }
  if (os2.platform() === "linux") {
    try {
      const osReleaseContent = await readFile("/etc/os-release", "utf8");
      const isSupportedDistro = osReleaseContent.match(
        /^ID=["']?(?:debian|ubuntu|nixos|arch|fedora|suse|opensuse)/m
      ) || osReleaseContent.match(
        /^ID_LIKE=["']?.*(?:debian|ubuntu|arch|fedora|suse).*/m
      );
      if (isSupportedDistro) {
        debugLogger.log(
          "Defaulting to use current user UID/GID for supported Linux distribution."
        );
        return true;
      }
      const uid = os2.userInfo().uid;
      if (uid !== 1e3 && uid !== 0) {
        debugLogger.warn(
          `Warning: Host UID mismatch detected (current UID: ${uid}). If you encounter permission errors in the sandbox, try setting SANDBOX_SET_UID_GID=true.`
        );
      }
    } catch {
      debugLogger.warn(
        "Warning: Could not read /etc/os-release to auto-detect Linux distribution for UID/GID default."
      );
    }
  }
  return false;
}
function parseImageName(image) {
  const [fullName, tag] = image.split(":");
  const name = fullName.split("/").at(-1) ?? "unknown-image";
  return tag ? `${name}-${tag}` : name;
}
function ports() {
  return (process.env["SANDBOX_PORTS"] ?? "").split(",").filter((p) => p.trim()).map((p) => p.trim());
}
function entrypoint(workdir, cliArgs) {
  const isWindows = os2.platform() === "win32";
  const containerWorkdir = getContainerPath(workdir);
  const shellCmds = [];
  const pathSeparator = isWindows ? ";" : ":";
  let pathSuffix = "";
  if (process.env["PATH"]) {
    const paths = process.env["PATH"].split(pathSeparator);
    for (const p of paths) {
      const containerPath = getContainerPath(p);
      if (containerPath.toLowerCase().startsWith(containerWorkdir.toLowerCase())) {
        pathSuffix += `:${containerPath}`;
      }
    }
  }
  if (pathSuffix) {
    shellCmds.push(`export PATH="$PATH${pathSuffix}";`);
  }
  let pythonPathSuffix = "";
  if (process.env["PYTHONPATH"]) {
    const paths = process.env["PYTHONPATH"].split(pathSeparator);
    for (const p of paths) {
      const containerPath = getContainerPath(p);
      if (containerPath.toLowerCase().startsWith(containerWorkdir.toLowerCase())) {
        pythonPathSuffix += `:${containerPath}`;
      }
    }
  }
  if (pythonPathSuffix) {
    shellCmds.push(`export PYTHONPATH="$PYTHONPATH${pythonPathSuffix}";`);
  }
  const projectSandboxBashrc = `${GEMINI_DIR}/sandbox.bashrc`;
  if (fs6.existsSync(projectSandboxBashrc)) {
    shellCmds.push(`source ${getContainerPath(projectSandboxBashrc)};`);
  }
  ports().forEach(
    (p) => shellCmds.push(
      `socat TCP4-LISTEN:${p},bind=$(hostname -i),fork,reuseaddr TCP4:127.0.0.1:${p} 2> /dev/null &`
    )
  );
  const quotedCliArgs = cliArgs.slice(2).map((arg) => (0, import_shell_quote.quote)([arg]));
  const isDebugMode2 = process.env["DEBUG"] === "true" || process.env["DEBUG"] === "1";
  const cliCmd = false ? isDebugMode2 ? "npm run debug --" : "npm rebuild && npm run start --" : isDebugMode2 ? `node --inspect-brk=0.0.0.0:${process.env["DEBUG_PORT"] || "9229"} $(which gemini)` : "gemini";
  const args = [...shellCmds, cliCmd, ...quotedCliArgs];
  return ["bash", "-c", args.join(" ")];
}

// packages/cli/src/utils/sandbox.ts
var execAsync = promisify(exec);
var execFileAsync = promisify(execFile);
async function start_sandbox(config2, nodeArgs = [], cliConfig, cliArgs = []) {
  const patcher = new ConsolePatcher({
    debugMode: cliConfig?.getDebugMode() || !!process.env["DEBUG"],
    stderr: true
  });
  patcher.patch();
  let stopProxy = void 0;
  try {
    if (config2.command === "sandbox-exec") {
      if (process.env["BUILD_SANDBOX"]) {
        throw new FatalSandboxError(
          "Cannot BUILD_SANDBOX when using macOS Seatbelt"
        );
      }
      const profile = process.env["SEATBELT_PROFILE"] ??= "permissive-open";
      let profileFile = fileURLToPath4(
        new URL(`sandbox-macos-${profile}.sb`, import.meta.url)
      );
      if (!BUILTIN_SEATBELT_PROFILES.includes(profile)) {
        const safeProfile = path8.basename(profile);
        const fileName = `sandbox-macos-${safeProfile}.sb`;
        const userProfileFile = path8.join(homedir(), GEMINI_DIR, fileName);
        const projectProfileFile = path8.join(GEMINI_DIR, fileName);
        profileFile = fs7.existsSync(userProfileFile) ? userProfileFile : projectProfileFile;
      }
      if (!fs7.existsSync(profileFile)) {
        throw new FatalSandboxError(
          `Missing macos seatbelt profile file '${profileFile}'`
        );
      }
      debugLogger.log(`using macos seatbelt (profile: ${profile}) ...`);
      const nodeOptions = [
        ...process.env["DEBUG"] ? ["--inspect-brk"] : [],
        ...nodeArgs
      ].join(" ");
      const args2 = [
        "-D",
        `TARGET_DIR=${fs7.realpathSync(process.cwd())}`,
        "-D",
        `TMP_DIR=${fs7.realpathSync(os3.tmpdir())}`,
        "-D",
        `HOME_DIR=${fs7.realpathSync(homedir())}`,
        "-D",
        `CACHE_DIR=${fs7.realpathSync((await execAsync("getconf DARWIN_USER_CACHE_DIR")).stdout.trim())}`
      ];
      const MAX_INCLUDE_DIRS = 5;
      const targetDir = fs7.realpathSync(cliConfig?.getTargetDir() || "");
      const includedDirs = [];
      if (cliConfig) {
        const workspaceContext = cliConfig.getWorkspaceContext();
        const directories = workspaceContext.getDirectories();
        for (const dir of directories) {
          const realDir = fs7.realpathSync(dir);
          if (realDir !== targetDir) {
            includedDirs.push(realDir);
          }
        }
      }
      if (config2.allowedPaths) {
        for (const hostPath of config2.allowedPaths) {
          if (hostPath && path8.isAbsolute(hostPath) && fs7.existsSync(hostPath)) {
            const realDir = fs7.realpathSync(hostPath);
            if (!includedDirs.includes(realDir) && realDir !== targetDir) {
              includedDirs.push(realDir);
            }
          }
        }
      }
      for (let i = 0; i < MAX_INCLUDE_DIRS; i++) {
        let dirPath = "/dev/null";
        if (i < includedDirs.length) {
          dirPath = includedDirs[i];
        }
        args2.push("-D", `INCLUDE_DIR_${i}=${dirPath}`);
      }
      const finalArgv = cliArgs;
      args2.push(
        "-f",
        profileFile,
        "sh",
        "-c",
        [
          `SANDBOX=sandbox-exec`,
          `NODE_OPTIONS="${nodeOptions}"`,
          ...finalArgv.map((arg) => (0, import_shell_quote2.quote)([arg]))
        ].join(" ")
      );
      const proxyCommand2 = process.env["GEMINI_SANDBOX_PROXY_COMMAND"];
      let proxyProcess2 = void 0;
      let sandboxProcess2 = void 0;
      const sandboxEnv = { ...process.env };
      if (proxyCommand2) {
        const proxy = process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"] || "http://localhost:8877";
        sandboxEnv["HTTPS_PROXY"] = proxy;
        sandboxEnv["https_proxy"] = proxy;
        sandboxEnv["HTTP_PROXY"] = proxy;
        sandboxEnv["http_proxy"] = proxy;
        const noProxy = process.env["NO_PROXY"] || process.env["no_proxy"];
        if (noProxy) {
          sandboxEnv["NO_PROXY"] = noProxy;
          sandboxEnv["no_proxy"] = noProxy;
        }
        proxyProcess2 = spawn2(proxyCommand2, {
          stdio: ["ignore", "pipe", "pipe"],
          shell: true,
          detached: true
        });
        stopProxy = () => {
          debugLogger.log("stopping proxy ...");
          if (proxyProcess2?.pid) {
            try {
              process.kill(-proxyProcess2.pid, "SIGTERM");
            } catch {
            }
          }
        };
        process.on("exit", stopProxy);
        process.on("SIGINT", stopProxy);
        process.on("SIGTERM", stopProxy);
        proxyProcess2.stderr?.on("data", (data) => {
          debugLogger.debug(`[PROXY STDERR]: ${data.toString().trim()}`);
        });
        proxyProcess2.on("close", (code, signal) => {
          if (sandboxProcess2?.pid) {
            process.kill(-sandboxProcess2.pid, "SIGTERM");
          }
          throw new FatalSandboxError(
            `Proxy command '${proxyCommand2}' exited with code ${code}, signal ${signal}`
          );
        });
        debugLogger.log("waiting for proxy to start ...");
        await execAsync(
          `until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`
        );
      }
      process.stdin.pause();
      sandboxProcess2 = spawn2(config2.command, args2, {
        stdio: "inherit"
      });
      return await new Promise((resolve9, reject) => {
        sandboxProcess2?.on("error", reject);
        sandboxProcess2?.on("close", (code) => {
          process.stdin.resume();
          resolve9(code ?? 1);
        });
      });
    }
    if (config2.command === "lxc") {
      return await start_lxc_sandbox(config2, nodeArgs, cliArgs);
    }
    const command2 = config2.command === "runsc" ? "docker" : config2.command;
    if (!command2) throw new FatalSandboxError("Sandbox command is required");
    debugLogger.log(`hopping into sandbox (command: ${command2}) ...`);
    const gcPath = process.argv[1] ? fs7.realpathSync(process.argv[1]) : "";
    const projectSandboxDockerfile = path8.join(
      GEMINI_DIR,
      "sandbox.Dockerfile"
    );
    const isCustomProjectSandbox = fs7.existsSync(projectSandboxDockerfile);
    const image = config2.image;
    if (!image) throw new FatalSandboxError("Sandbox image is required");
    if (!/^[a-zA-Z0-9_.:/-]+$/.test(image))
      throw new FatalSandboxError("Invalid sandbox image name");
    const workdir = path8.resolve(process.cwd());
    const containerWorkdir = getContainerPath(workdir);
    if (process.env["BUILD_SANDBOX"]) {
      if (!gcPath.includes("gemini-cli/packages/")) {
        throw new FatalSandboxError(
          "Cannot build sandbox using installed gemini binary; run `npm link ./packages/cli` under gemini-cli repo to switch to linked binary."
        );
      } else {
        debugLogger.log("building sandbox ...");
        const gcRoot = gcPath.split("/packages/")[0];
        let buildArgs = "";
        const projectSandboxDockerfile2 = path8.join(
          GEMINI_DIR,
          "sandbox.Dockerfile"
        );
        if (isCustomProjectSandbox) {
          debugLogger.log(`using ${projectSandboxDockerfile2} for sandbox`);
          buildArgs += `-f ${path8.resolve(projectSandboxDockerfile2)} -i ${image}`;
        }
        execSync(
          `cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`,
          {
            stdio: "inherit",
            env: {
              ...process.env,
              GEMINI_SANDBOX: command2
              // in case sandbox is enabled via flags (see config.ts under cli package)
            }
          }
        );
      }
    }
    if (!await ensureSandboxImageIsPresent(command2, image, cliConfig)) {
      const remedy = image === LOCAL_DEV_SANDBOX_IMAGE_NAME ? "Try running `npm run build:all` or `npm run build:sandbox` under the gemini-cli repo to build it locally, or check the image name and your network connection." : "Please check the image name, your network connection, or notify gemini-cli-dev@google.com if the issue persists.";
      throw new FatalSandboxError(
        `Sandbox image '${image}' is missing or could not be pulled. ${remedy}`
      );
    }
    const args = ["run", "-i", "--rm", "--init", "--workdir", containerWorkdir];
    args.push("--entrypoint", "");
    if (config2.command === "runsc") {
      args.push("--runtime=runsc");
    }
    if (process.env["SANDBOX_FLAGS"]) {
      const flags = (0, import_shell_quote2.parse)(process.env["SANDBOX_FLAGS"], process.env).filter(
        (f) => typeof f === "string"
      );
      args.push(...flags);
    }
    if (process.stdin.isTTY) {
      args.push("-t");
    }
    args.push("--add-host", "host.docker.internal:host-gateway");
    args.push("--volume", `${workdir}:${containerWorkdir}`);
    const userHomeDirOnHost = homedir();
    const userSettingsDirInSandbox = getContainerPath(
      `/home/node/${GEMINI_DIR}`
    );
    if (!fs7.existsSync(userHomeDirOnHost)) {
      fs7.mkdirSync(userHomeDirOnHost, { recursive: true });
    }
    const userSettingsDirOnHost = path8.join(userHomeDirOnHost, GEMINI_DIR);
    if (!fs7.existsSync(userSettingsDirOnHost)) {
      fs7.mkdirSync(userSettingsDirOnHost, { recursive: true });
    }
    args.push(
      "--volume",
      `${userSettingsDirOnHost}:${userSettingsDirInSandbox}`
    );
    if (userSettingsDirInSandbox !== getContainerPath(userSettingsDirOnHost)) {
      args.push(
        "--volume",
        `${userSettingsDirOnHost}:${getContainerPath(userSettingsDirOnHost)}`
      );
    }
    args.push("--volume", `${os3.tmpdir()}:${getContainerPath(os3.tmpdir())}`);
    if (userHomeDirOnHost !== os3.homedir()) {
      args.push(
        "--volume",
        `${userHomeDirOnHost}:${getContainerPath(userHomeDirOnHost)}`
      );
    }
    const gcloudConfigDir = path8.join(homedir(), ".config", "gcloud");
    if (fs7.existsSync(gcloudConfigDir)) {
      args.push(
        "--volume",
        `${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`
      );
    }
    if (process.env["GOOGLE_APPLICATION_CREDENTIALS"]) {
      const adcFile = process.env["GOOGLE_APPLICATION_CREDENTIALS"];
      if (fs7.existsSync(adcFile)) {
        args.push("--volume", `${adcFile}:${getContainerPath(adcFile)}:ro`);
        args.push(
          "--env",
          `GOOGLE_APPLICATION_CREDENTIALS=${getContainerPath(adcFile)}`
        );
      }
    }
    if (process.env["SANDBOX_MOUNTS"]) {
      for (let mount of process.env["SANDBOX_MOUNTS"].split(",")) {
        if (mount.trim()) {
          let [from, to, opts] = mount.trim().split(":");
          to = to || from;
          opts = opts || "ro";
          mount = `${from}:${to}:${opts}`;
          if (!path8.isAbsolute(from)) {
            throw new FatalSandboxError(
              `Path '${from}' listed in SANDBOX_MOUNTS must be absolute`
            );
          }
          if (!fs7.existsSync(from)) {
            throw new FatalSandboxError(
              `Missing mount path '${from}' listed in SANDBOX_MOUNTS`
            );
          }
          debugLogger.log(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`);
          args.push("--volume", mount);
        }
      }
    }
    if (config2.allowedPaths) {
      for (const hostPath of config2.allowedPaths) {
        if (hostPath && path8.isAbsolute(hostPath) && fs7.existsSync(hostPath)) {
          const containerPath = getContainerPath(hostPath);
          debugLogger.log(
            `Config allowedPath: ${hostPath} -> ${containerPath} (ro)`
          );
          args.push("--volume", `${hostPath}:${containerPath}:ro`);
        }
      }
    }
    ports().forEach((p) => args.push("--publish", `${p}:${p}`));
    if (process.env["DEBUG"]) {
      const debugPort = process.env["DEBUG_PORT"] || "9229";
      args.push(`--publish`, `${debugPort}:${debugPort}`);
    }
    const proxyCommand = process.env["GEMINI_SANDBOX_PROXY_COMMAND"];
    if (proxyCommand) {
      let proxy = process.env["HTTPS_PROXY"] || process.env["https_proxy"] || process.env["HTTP_PROXY"] || process.env["http_proxy"] || "http://localhost:8877";
      proxy = proxy.replace("localhost", SANDBOX_PROXY_NAME);
      if (proxy) {
        args.push("--env", `HTTPS_PROXY=${proxy}`);
        args.push("--env", `https_proxy=${proxy}`);
        args.push("--env", `HTTP_PROXY=${proxy}`);
        args.push("--env", `http_proxy=${proxy}`);
      }
      const noProxy = process.env["NO_PROXY"] || process.env["no_proxy"];
      if (noProxy) {
        args.push("--env", `NO_PROXY=${noProxy}`);
        args.push("--env", `no_proxy=${noProxy}`);
      }
    }
    if (!config2.networkAccess || proxyCommand) {
      const isInternal = !config2.networkAccess || !!proxyCommand;
      const networkFlags = isInternal ? "--internal" : "";
      execSync(
        `${command2} network inspect ${SANDBOX_NETWORK_NAME} || ${command2} network create ${networkFlags} ${SANDBOX_NETWORK_NAME}`,
        { stdio: "ignore" }
      );
      args.push("--network", SANDBOX_NETWORK_NAME);
      if (proxyCommand) {
        execSync(
          `${command2} network inspect ${SANDBOX_PROXY_NAME} || ${command2} network create ${SANDBOX_PROXY_NAME}`,
          { stdio: "ignore" }
        );
      }
    }
    const imageName = parseImageName(image);
    const isIntegrationTest = process.env["GEMINI_CLI_INTEGRATION_TEST"] === "true";
    const containerNamePrefix = isIntegrationTest ? "gemini-cli-integration-test" : imageName;
    const containerName = `${containerNamePrefix}-${randomBytes(6).toString(
      "hex"
    )}`;
    debugLogger.log(`ContainerName: ${containerName}`);
    args.push("--name", containerName, "--hostname", containerName);
    if (process.env["GEMINI_CLI_TEST_VAR"]) {
      args.push(
        "--env",
        `GEMINI_CLI_TEST_VAR=${process.env["GEMINI_CLI_TEST_VAR"]}`
      );
    }
    if (process.env["GEMINI_API_KEY"]) {
      args.push("--env", `GEMINI_API_KEY=${process.env["GEMINI_API_KEY"]}`);
    }
    if (process.env["GOOGLE_API_KEY"]) {
      args.push("--env", `GOOGLE_API_KEY=${process.env["GOOGLE_API_KEY"]}`);
    }
    if (process.env["GOOGLE_GEMINI_BASE_URL"]) {
      args.push(
        "--env",
        `GOOGLE_GEMINI_BASE_URL=${process.env["GOOGLE_GEMINI_BASE_URL"]}`
      );
    }
    if (process.env["GOOGLE_VERTEX_BASE_URL"]) {
      args.push(
        "--env",
        `GOOGLE_VERTEX_BASE_URL=${process.env["GOOGLE_VERTEX_BASE_URL"]}`
      );
    }
    if (process.env["GOOGLE_GENAI_USE_VERTEXAI"]) {
      args.push(
        "--env",
        `GOOGLE_GENAI_USE_VERTEXAI=${process.env["GOOGLE_GENAI_USE_VERTEXAI"]}`
      );
    }
    if (process.env["GOOGLE_GENAI_USE_GCA"]) {
      args.push(
        "--env",
        `GOOGLE_GENAI_USE_GCA=${process.env["GOOGLE_GENAI_USE_GCA"]}`
      );
    }
    if (process.env["GOOGLE_CLOUD_PROJECT"]) {
      args.push(
        "--env",
        `GOOGLE_CLOUD_PROJECT=${process.env["GOOGLE_CLOUD_PROJECT"]}`
      );
    }
    if (process.env["GOOGLE_CLOUD_LOCATION"]) {
      args.push(
        "--env",
        `GOOGLE_CLOUD_LOCATION=${process.env["GOOGLE_CLOUD_LOCATION"]}`
      );
    }
    if (process.env["GEMINI_MODEL"]) {
      args.push("--env", `GEMINI_MODEL=${process.env["GEMINI_MODEL"]}`);
    }
    if (process.env["TERM"]) {
      args.push("--env", `TERM=${process.env["TERM"]}`);
    }
    if (process.env["COLORTERM"]) {
      args.push("--env", `COLORTERM=${process.env["COLORTERM"]}`);
    }
    for (const envVar of [
      "GEMINI_CLI_IDE_SERVER_PORT",
      "GEMINI_CLI_IDE_WORKSPACE_PATH",
      "TERM_PROGRAM"
    ]) {
      if (process.env[envVar]) {
        args.push("--env", `${envVar}=${process.env[envVar]}`);
      }
    }
    if (process.env["VIRTUAL_ENV"]?.toLowerCase().startsWith(workdir.toLowerCase())) {
      const sandboxVenvPath = path8.resolve(GEMINI_DIR, "sandbox.venv");
      if (!fs7.existsSync(sandboxVenvPath)) {
        fs7.mkdirSync(sandboxVenvPath, { recursive: true });
      }
      args.push(
        "--volume",
        `${sandboxVenvPath}:${getContainerPath(process.env["VIRTUAL_ENV"])}`
      );
      args.push(
        "--env",
        `VIRTUAL_ENV=${getContainerPath(process.env["VIRTUAL_ENV"])}`
      );
    }
    if (process.env["SANDBOX_ENV"]) {
      for (let env2 of process.env["SANDBOX_ENV"].split(",")) {
        if (env2 = env2.trim()) {
          if (env2.includes("=")) {
            debugLogger.log(`SANDBOX_ENV: ${env2}`);
            args.push("--env", env2);
          } else {
            throw new FatalSandboxError(
              "SANDBOX_ENV must be a comma-separated list of key=value pairs"
            );
          }
        }
      }
    }
    const existingNodeOptions = process.env["NODE_OPTIONS"] || "";
    const allNodeOptions = [
      ...existingNodeOptions ? [existingNodeOptions] : [],
      ...nodeArgs
    ].join(" ");
    if (allNodeOptions.length > 0) {
      args.push("--env", `NODE_OPTIONS="${allNodeOptions}"`);
    }
    args.push("--env", `SANDBOX=${containerName}`);
    if (command2 === "podman") {
      const emptyAuthFilePath = path8.join(os3.tmpdir(), "empty_auth.json");
      fs7.writeFileSync(emptyAuthFilePath, "{}", "utf-8");
      args.push("--authfile", emptyAuthFilePath);
    }
    let userFlag = "";
    const finalEntrypoint = entrypoint(workdir, cliArgs);
    if (process.env["GEMINI_CLI_INTEGRATION_TEST"] === "true") {
      args.push("--user", "root");
      userFlag = "--user root";
    } else if (await shouldUseCurrentUserInSandbox()) {
      args.push("--user", "root");
      const uid = (await execAsync("id -u")).stdout.trim();
      const gid = (await execAsync("id -g")).stdout.trim();
      const username = "gemini";
      const homeDir = getContainerPath(homedir());
      const quotedHomeDir = (0, import_shell_quote2.quote)([homeDir]);
      const originalCommand = finalEntrypoint[2];
      const escapedOriginalCommand = originalCommand.replace(/'/g, "'\\''");
      const defensiveEntrypoint = [
        `if command -v useradd >/dev/null 2>&1; then`,
        `  (groupadd -g ${gid} -o ${username} 2>/dev/null || true) &&`,
        `  (id ${uid} >/dev/null 2>&1 || useradd -o -u ${uid} -g ${gid} -d ${quotedHomeDir} -s /bin/bash ${username} 2>/dev/null || true) &&`,
        `  USER_NAME=$(id -nu ${uid} 2>/dev/null);`,
        `  if [ -n "$USER_NAME" ]; then`,
        `    su -p "$USER_NAME" -c '${escapedOriginalCommand}';`,
        `  else`,
        `    echo "Error: Failed to map host UID ${uid} to a user in the container." >&2;`,
        `    exit 1;`,
        `  fi`,
        `else`,
        `  echo "Error: 'useradd' not found in container. UID/GID mapping is required for Linux distros like NixOS/Arch to avoid permission issues. Please use a container image that includes standard user management tools (like 'ubuntu' or 'debian')." >&2;`,
        `  exit 1;`,
        `fi`
      ].join("\n");
      finalEntrypoint[2] = defensiveEntrypoint;
      userFlag = `--user ${uid}:${gid}`;
      args.push("--env", `HOME=${homedir()}`);
    }
    args.push(image);
    args.push(...finalEntrypoint);
    let proxyProcess = void 0;
    let sandboxProcess = void 0;
    if (proxyCommand) {
      const proxyContainerArgs = [
        "run",
        "--rm",
        "--init",
        "--entrypoint",
        "",
        ...userFlag ? userFlag.split(" ") : [],
        "--name",
        SANDBOX_PROXY_NAME,
        "--network",
        SANDBOX_PROXY_NAME,
        "-p",
        "8877:8877",
        "-v",
        `${process.cwd()}:${workdir}`,
        "--workdir",
        workdir,
        image,
        // proxyCommand may be a shell string, so parse it into tokens safely
        ...(0, import_shell_quote2.parse)(proxyCommand, process.env).filter(
          (f) => typeof f === "string"
        )
      ];
      proxyProcess = spawn2(command2, proxyContainerArgs, {
        stdio: ["ignore", "pipe", "pipe"],
        shell: false,
        // <-- no shell; args are passed directly
        detached: true
      });
      stopProxy = () => {
        debugLogger.log("stopping proxy container ...");
        try {
          spawnSync(command2, ["rm", "-f", SANDBOX_PROXY_NAME], {
            stdio: "ignore"
          });
        } catch {
        }
      };
      process.on("exit", stopProxy);
      process.on("SIGINT", stopProxy);
      process.on("SIGTERM", stopProxy);
      proxyProcess.stderr?.on("data", (data) => {
        debugLogger.debug(`[PROXY STDERR]: ${data.toString().trim()}`);
      });
      proxyProcess.on("close", (code, signal) => {
        if (sandboxProcess?.pid) {
          process.kill(-sandboxProcess.pid, "SIGTERM");
        }
        throw new FatalSandboxError(
          `Proxy container command '${command2} ${proxyContainerArgs.join(" ")}' exited with code ${code}, signal ${signal}`
        );
      });
      debugLogger.log("waiting for proxy to start ...");
      await execAsync(
        `until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`
      );
      await execAsync(
        `${command2} network connect ${SANDBOX_NETWORK_NAME} ${SANDBOX_PROXY_NAME}`
      );
    }
    process.stdin.pause();
    sandboxProcess = spawn2(command2, args, {
      stdio: "inherit"
    });
    return await new Promise((resolve9, reject) => {
      sandboxProcess?.on("error", (err) => {
        coreEvents.emitFeedback("error", "Sandbox process error", err);
        reject(err);
      });
      sandboxProcess?.on("close", (code, signal) => {
        process.stdin.resume();
        if (code !== 0 && code !== null) {
          debugLogger.log(
            `Sandbox process exited with code: ${code}, signal: ${signal}`
          );
        }
        resolve9(code ?? 1);
      });
    });
  } finally {
    if (stopProxy) {
      stopProxy();
      process.off("exit", stopProxy);
      process.off("SIGINT", stopProxy);
      process.off("SIGTERM", stopProxy);
    }
    patcher.cleanup();
  }
}
async function start_lxc_sandbox(config2, nodeArgs = [], cliArgs = []) {
  const containerName = config2.image || "gemini-sandbox";
  const workdir = path8.resolve(process.cwd());
  debugLogger.log(
    `starting lxc sandbox (container: ${containerName}, workdir: ${workdir}) ...`
  );
  let listOutput;
  try {
    const { stdout } = await execFileAsync("lxc", [
      "list",
      containerName,
      "--format=json"
    ]);
    listOutput = stdout.trim();
  } catch (err) {
    throw new FatalSandboxError(
      `Failed to query LXC container '${containerName}': ${err instanceof Error ? err.message : String(err)}. Make sure LXC/LXD is installed and '${containerName}' container exists. Create one with: lxc launch ubuntu:24.04 ${containerName}`
    );
  }
  let containers = [];
  try {
    const parsed = JSON.parse(listOutput);
    if (Array.isArray(parsed)) {
      containers = parsed.filter(
        (item) => item !== null && typeof item === "object" && "name" in item && "status" in item
      ).map((item) => ({
        name: String(item["name"]),
        status: String(item["status"])
      }));
    }
  } catch {
    containers = [];
  }
  const container = containers.find((c) => c.name === containerName);
  if (!container) {
    throw new FatalSandboxError(
      `LXC container '${containerName}' not found. Create one with: lxc launch ubuntu:24.04 ${containerName}`
    );
  }
  if (container.status.toLowerCase() !== "running") {
    throw new FatalSandboxError(
      `LXC container '${containerName}' is not running (current status: ${container.status}). Start it with: lxc start ${containerName}`
    );
  }
  const devicesToRemove = [];
  const removeDevices = () => {
    for (const deviceName of devicesToRemove) {
      try {
        spawnSync(
          "lxc",
          ["config", "device", "remove", containerName, deviceName],
          { timeout: 1e3, killSignal: "SIGKILL", stdio: "ignore" }
        );
      } catch {
      }
    }
  };
  try {
    const workspaceDeviceName = `gemini-workspace-${randomBytes(4).toString(
      "hex"
    )}`;
    devicesToRemove.push(workspaceDeviceName);
    try {
      await execFileAsync("lxc", [
        "config",
        "device",
        "add",
        containerName,
        workspaceDeviceName,
        "disk",
        `source=${workdir}`,
        `path=${workdir}`
      ]);
      debugLogger.log(
        `mounted workspace '${workdir}' into container as device '${workspaceDeviceName}'`
      );
    } catch (err) {
      throw new FatalSandboxError(
        `Failed to mount workspace into LXC container '${containerName}': ${err instanceof Error ? err.message : String(err)}`
      );
    }
    if (config2.allowedPaths) {
      for (const hostPath of config2.allowedPaths) {
        if (hostPath && path8.isAbsolute(hostPath) && fs7.existsSync(hostPath)) {
          const allowedDeviceName = `gemini-allowed-${randomBytes(4).toString(
            "hex"
          )}`;
          devicesToRemove.push(allowedDeviceName);
          try {
            await execFileAsync("lxc", [
              "config",
              "device",
              "add",
              containerName,
              allowedDeviceName,
              "disk",
              `source=${hostPath}`,
              `path=${hostPath}`,
              "readonly=true"
            ]);
            debugLogger.log(
              `mounted allowed path '${hostPath}' into container as device '${allowedDeviceName}' (ro)`
            );
          } catch (err) {
            debugLogger.warn(
              `Failed to mount allowed path '${hostPath}' into LXC container: ${err instanceof Error ? err.message : String(err)}`
            );
          }
        }
      }
    }
    process.on("exit", removeDevices);
    const envArgs = [];
    const envVarsToForward = {
      GEMINI_API_KEY: process.env["GEMINI_API_KEY"],
      GOOGLE_API_KEY: process.env["GOOGLE_API_KEY"],
      GOOGLE_GEMINI_BASE_URL: process.env["GOOGLE_GEMINI_BASE_URL"],
      GOOGLE_VERTEX_BASE_URL: process.env["GOOGLE_VERTEX_BASE_URL"],
      GOOGLE_GENAI_USE_VERTEXAI: process.env["GOOGLE_GENAI_USE_VERTEXAI"],
      GOOGLE_GENAI_USE_GCA: process.env["GOOGLE_GENAI_USE_GCA"],
      GOOGLE_CLOUD_PROJECT: process.env["GOOGLE_CLOUD_PROJECT"],
      GOOGLE_CLOUD_LOCATION: process.env["GOOGLE_CLOUD_LOCATION"],
      GEMINI_MODEL: process.env["GEMINI_MODEL"],
      TERM: process.env["TERM"],
      COLORTERM: process.env["COLORTERM"],
      GEMINI_CLI_IDE_SERVER_PORT: process.env["GEMINI_CLI_IDE_SERVER_PORT"],
      GEMINI_CLI_IDE_WORKSPACE_PATH: process.env["GEMINI_CLI_IDE_WORKSPACE_PATH"],
      TERM_PROGRAM: process.env["TERM_PROGRAM"]
    };
    for (const [key, value] of Object.entries(envVarsToForward)) {
      if (value) {
        envArgs.push("--env", `${key}=${value}`);
      }
    }
    if (process.env["SANDBOX_ENV"]) {
      for (let env2 of process.env["SANDBOX_ENV"].split(",")) {
        if (env2 = env2.trim()) {
          if (env2.includes("=")) {
            envArgs.push("--env", env2);
          } else {
            throw new FatalSandboxError(
              "SANDBOX_ENV must be a comma-separated list of key=value pairs"
            );
          }
        }
      }
    }
    const existingNodeOptions = process.env["NODE_OPTIONS"] || "";
    const allNodeOptions = [
      ...existingNodeOptions ? [existingNodeOptions] : [],
      ...nodeArgs
    ].join(" ");
    if (allNodeOptions.length > 0) {
      envArgs.push("--env", `NODE_OPTIONS=${allNodeOptions}`);
    }
    envArgs.push("--env", `SANDBOX=${containerName}`);
    const finalEntrypoint = entrypoint(workdir, cliArgs);
    const args = [
      "exec",
      containerName,
      "--cwd",
      workdir,
      ...envArgs,
      "--",
      ...finalEntrypoint
    ];
    debugLogger.log(`lxc exec args: ${args.join(" ")}`);
    process.stdin.pause();
    const sandboxProcess = spawn2("lxc", args, {
      stdio: "inherit"
    });
    return await new Promise((resolve9, reject) => {
      sandboxProcess.on("error", (err) => {
        coreEvents.emitFeedback("error", "LXC sandbox process error", err);
        reject(err);
      });
      sandboxProcess.on("close", (code, signal) => {
        process.stdin.resume();
        if (code !== 0 && code !== null) {
          debugLogger.log(
            `LXC sandbox process exited with code: ${code}, signal: ${signal}`
          );
        }
        resolve9(code ?? 1);
      });
    });
  } finally {
    process.off("exit", removeDevices);
    removeDevices();
  }
}
async function imageExists(sandbox, image) {
  return new Promise((resolve9) => {
    const args = ["images", "-q", image];
    const checkProcess = spawn2(sandbox, args);
    let stdoutData = "";
    if (checkProcess.stdout) {
      checkProcess.stdout.on("data", (data) => {
        stdoutData += data.toString();
      });
    }
    checkProcess.on("error", (err) => {
      debugLogger.warn(
        `Failed to start '${sandbox}' command for image check: ${err.message}`
      );
      resolve9(false);
    });
    checkProcess.on("close", (code) => {
      if (code !== 0) {
      }
      resolve9(stdoutData.trim() !== "");
    });
  });
}
async function pullImage(sandbox, image, cliConfig) {
  debugLogger.debug(`Attempting to pull image ${image} using ${sandbox}...`);
  return new Promise((resolve9) => {
    const args = ["pull", image];
    const pullProcess = spawn2(sandbox, args, { stdio: "pipe" });
    let stderrData = "";
    const onStdoutData = (data) => {
      if (cliConfig?.getDebugMode() || process.env["DEBUG"]) {
        debugLogger.log(data.toString().trim());
      }
    };
    const onStderrData = (data) => {
      stderrData += data.toString();
      console.error(data.toString().trim());
    };
    const onError = (err) => {
      debugLogger.warn(
        `Failed to start '${sandbox} pull ${image}' command: ${err.message}`
      );
      cleanup();
      resolve9(false);
    };
    const onClose = (code) => {
      if (code === 0) {
        debugLogger.log(`Successfully pulled image ${image}.`);
        cleanup();
        resolve9(true);
      } else {
        debugLogger.warn(
          `Failed to pull image ${image}. '${sandbox} pull ${image}' exited with code ${code}.`
        );
        if (stderrData.trim()) {
        }
        cleanup();
        resolve9(false);
      }
    };
    const cleanup = () => {
      if (pullProcess.stdout) {
        pullProcess.stdout.removeListener("data", onStdoutData);
      }
      if (pullProcess.stderr) {
        pullProcess.stderr.removeListener("data", onStderrData);
      }
      pullProcess.removeListener("error", onError);
      pullProcess.removeListener("close", onClose);
      if (pullProcess.connected) {
        pullProcess.disconnect();
      }
    };
    if (pullProcess.stdout) {
      pullProcess.stdout.on("data", onStdoutData);
    }
    if (pullProcess.stderr) {
      pullProcess.stderr.on("data", onStderrData);
    }
    pullProcess.on("error", onError);
    pullProcess.on("close", onClose);
  });
}
async function ensureSandboxImageIsPresent(sandbox, image, cliConfig) {
  debugLogger.log(`Checking for sandbox image: ${image}`);
  if (await imageExists(sandbox, image)) {
    debugLogger.log(`Sandbox image ${image} found locally.`);
    return true;
  }
  debugLogger.log(`Sandbox image ${image} not found locally.`);
  if (image === LOCAL_DEV_SANDBOX_IMAGE_NAME) {
    return false;
  }
  if (await pullImage(sandbox, image, cliConfig)) {
    if (await imageExists(sandbox, image)) {
      debugLogger.log(`Sandbox image ${image} is now available after pulling.`);
      return true;
    } else {
      debugLogger.warn(
        `Sandbox image ${image} still not found after a pull attempt. This might indicate an issue with the image name or registry, or the pull command reported success but failed to make the image available.`
      );
      return false;
    }
  }
  coreEvents.emitFeedback(
    "error",
    `Failed to obtain sandbox image ${image} after check and pull attempt.`
  );
  return false;
}

// packages/cli/src/utils/startupWarnings.ts
import fs8 from "node:fs/promises";
import os4 from "node:os";
import { join as pathJoin } from "node:path";
var warningsFilePath = pathJoin(os4.tmpdir(), "gemini-cli-warnings.txt");
async function getStartupWarnings() {
  try {
    await fs8.access(warningsFilePath);
    const warningsContent = await fs8.readFile(warningsFilePath, "utf-8");
    const warnings = warningsContent.split("\n").filter((line) => line.trim() !== "");
    try {
      await fs8.unlink(warningsFilePath);
    } catch {
      warnings.push("Warning: Could not delete temporary warnings file.");
    }
    return warnings;
  } catch (err) {
    if (err instanceof Error && "code" in err && err.code === "ENOENT") {
      return [];
    }
    return [`Error checking/reading warnings file: ${getErrorMessage(err)}`];
  }
}

// packages/cli/src/utils/userStartupWarnings.ts
import fs9 from "node:fs/promises";
import { homedir as osHomedir } from "node:os";
import path9 from "node:path";
import process5 from "node:process";
var homeDirectoryCheck = {
  id: "home-directory",
  priority: "low" /* Low */,
  check: async (workspaceRoot, settings) => {
    if (settings.ui?.showHomeDirectoryWarning === false) {
      return null;
    }
    try {
      const [workspaceRealPath, homeRealPath] = await Promise.all([
        fs9.realpath(workspaceRoot),
        fs9.realpath(osHomedir())
      ]);
      if (path9.resolve(workspaceRealPath) === path9.resolve(homeRealPath)) {
        if (isFolderTrustEnabled(settings) && isWorkspaceTrusted(settings).isTrusted) {
          return null;
        }
        return "Warning you are running Gemini CLI in your home directory.\nThis warning can be disabled in /settings";
      }
      return null;
    } catch {
      return "Could not verify the current directory due to a file system error.";
    }
  }
};
var rootDirectoryCheck = {
  id: "root-directory",
  priority: "high" /* High */,
  check: async (workspaceRoot, _settings) => {
    try {
      const workspaceRealPath = await fs9.realpath(workspaceRoot);
      const errorMessage = "Warning: You are running Gemini CLI in the root directory. Your entire folder structure will be used for context. It is strongly recommended to run in a project-specific directory.";
      if (path9.dirname(workspaceRealPath) === workspaceRealPath) {
        return errorMessage;
      }
      return null;
    } catch {
      return "Could not verify the current directory due to a file system error.";
    }
  }
};
var folderTrustCheck = {
  id: "folder-trust",
  priority: "high" /* High */,
  check: async (workspaceRoot, settings) => {
    if (!isFolderTrustEnabled(settings)) {
      return null;
    }
    const { isTrusted } = isWorkspaceTrusted(settings, workspaceRoot);
    if (isTrusted === true) {
      return null;
    }
    if (isHeadlessMode()) {
      throw new FatalUntrustedWorkspaceError(
        "Gemini CLI is not running in a trusted directory. To proceed, either use `--skip-trust`, set the `GEMINI_CLI_TRUST_WORKSPACE=true` environment variable, or trust this directory in interactive mode. For more details, see https://geminicli.com/docs/cli/trusted-folders/#headless-and-automated-environments"
      );
    }
    return null;
  }
};
var WARNING_CHECKS = [
  homeDirectoryCheck,
  rootDirectoryCheck,
  folderTrustCheck
];
async function getUserStartupWarnings(settings, workspaceRoot = process5.cwd(), options) {
  const results = await Promise.all(
    WARNING_CHECKS.map(async (check) => {
      const message = await check.check(workspaceRoot, settings);
      if (message) {
        return {
          id: check.id,
          message,
          priority: check.priority
        };
      }
      return null;
    })
  );
  const warnings = results.filter((w) => w !== null);
  if (settings.ui?.showCompatibilityWarnings !== false) {
    warnings.push(
      ...getCompatibilityWarnings({
        isAlternateBuffer: options?.isAlternateBuffer
      })
    );
  }
  return warnings;
}

// packages/cli/src/nonInteractiveCli.ts
import readline3 from "node:readline";

// packages/cli/src/ui/noninteractive/nonInteractiveUi.ts
function createNonInteractiveUI() {
  return {
    addItem: (item, _timestamp) => {
      if ("text" in item && item.text) {
        if (item.type === "error") {
          process.stderr.write(`Error: ${item.text}
`);
        } else if (item.type === "warning") {
          process.stderr.write(`Warning: ${item.text}
`);
        } else if (item.type === "info") {
          process.stdout.write(`${item.text}
`);
        }
      }
      return 0;
    },
    clear: () => {
    },
    setDebugMessage: (_message) => {
    },
    loadHistory: (_newHistory) => {
    },
    pendingItem: null,
    setPendingItem: (_item) => {
    },
    toggleCorgiMode: () => {
    },
    toggleDebugProfiler: () => {
    },
    toggleVimEnabled: async () => false,
    reloadCommands: () => {
    },
    openAgentConfigDialog: () => {
    },
    extensionsUpdateState: /* @__PURE__ */ new Map(),
    dispatchExtensionStateUpdate: (_action) => {
    },
    addConfirmUpdateExtensionRequest: (_request) => {
    },
    setConfirmationRequest: (_request) => {
    },
    removeComponent: () => {
    },
    toggleBackgroundTasks: () => {
    },
    toggleShortcutsHelp: () => {
    },
    toggleVoiceMode: () => {
    }
  };
}

// packages/cli/src/nonInteractiveCliCommands.ts
var handleSlashCommand = async (rawQuery, abortController, config2, settings) => {
  const trimmed = rawQuery.trim();
  if (!trimmed.startsWith("/")) {
    return;
  }
  const commandService = await CommandService.create(
    [
      new BuiltinCommandLoader(config2),
      new McpPromptLoader(config2),
      new FileCommandLoader(config2)
    ],
    abortController.signal
  );
  const commands = commandService.getCommands();
  const { commandToExecute, args } = parseSlashCommand(rawQuery, commands);
  if (commandToExecute) {
    if (commandToExecute.action) {
      const sessionStats = {
        sessionId: config2?.getSessionId(),
        sessionStartTime: /* @__PURE__ */ new Date(),
        metrics: uiTelemetryService.getMetrics(),
        lastPromptTokenCount: 0,
        promptCount: 1
      };
      const logger = new Logger(config2?.getSessionId() || "", config2?.storage);
      const commandContext = {
        services: {
          agentContext: config2,
          settings,
          git: void 0,
          logger
        },
        ui: createNonInteractiveUI(),
        session: {
          stats: sessionStats,
          sessionShellAllowlist: /* @__PURE__ */ new Set()
        },
        invocation: {
          raw: trimmed,
          name: commandToExecute.name,
          args
        }
      };
      const result = await commandToExecute.action(commandContext, args);
      if (result) {
        switch (result.type) {
          case "submit_prompt":
            return result.content;
          case "confirm_shell_commands":
            throw new FatalInputError(
              "Exiting due to a confirmation prompt requested by the command."
            );
          default:
            throw new FatalInputError(
              "Exiting due to command result that is not supported in non-interactive mode."
            );
        }
      }
    }
  }
  return;
};

// packages/cli/src/utils/errors.ts
function extractErrorCode(error) {
  const errorWithCode = error;
  if (typeof errorWithCode.exitCode === "number") {
    return errorWithCode.exitCode;
  }
  if (errorWithCode.code !== void 0) {
    return errorWithCode.code;
  }
  if (errorWithCode.status !== void 0) {
    return errorWithCode.status;
  }
  return 1;
}
function getNumericExitCode(errorCode) {
  return typeof errorCode === "number" ? errorCode : 1;
}
function handleError(error, config2, customErrorCode) {
  const errorMessage = parseAndFormatApiError(
    error,
    config2.getContentGeneratorConfig()?.authType
  );
  if (config2.getOutputFormat() === "stream-json" /* STREAM_JSON */) {
    const streamFormatter = new StreamJsonFormatter();
    const errorCode = customErrorCode ?? extractErrorCode(error);
    const metrics = uiTelemetryService.getMetrics();
    streamFormatter.emitEvent({
      type: "result" /* RESULT */,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      status: "error",
      error: {
        type: getErrorType(error),
        message: errorMessage
      },
      stats: streamFormatter.convertToStreamStats(metrics, 0)
    });
    runSyncCleanup();
    process.exit(getNumericExitCode(errorCode));
  } else if (config2.getOutputFormat() === "json" /* JSON */) {
    const formatter = new JsonFormatter();
    const errorCode = customErrorCode ?? extractErrorCode(error);
    const formattedError = formatter.formatError(
      error instanceof Error ? error : new Error(getErrorMessage(error)),
      errorCode,
      config2.getSessionId()
    );
    coreEvents.emitFeedback("error", formattedError);
    runSyncCleanup();
    process.exit(getNumericExitCode(errorCode));
  } else {
    throw error;
  }
}
function handleToolError(toolName, toolError, config2, errorType, resultDisplay) {
  const errorMessage = `Error executing tool ${toolName}: ${resultDisplay || toolError.message}`;
  const isFatal = isFatalToolError(errorType);
  if (isFatal) {
    const toolExecutionError = new FatalToolExecutionError(errorMessage);
    if (config2.getOutputFormat() === "stream-json" /* STREAM_JSON */) {
      const streamFormatter = new StreamJsonFormatter();
      const metrics = uiTelemetryService.getMetrics();
      streamFormatter.emitEvent({
        type: "result" /* RESULT */,
        timestamp: (/* @__PURE__ */ new Date()).toISOString(),
        status: "error",
        error: {
          type: errorType ?? "FatalToolExecutionError",
          message: toolExecutionError.message
        },
        stats: streamFormatter.convertToStreamStats(metrics, 0)
      });
    } else if (config2.getOutputFormat() === "json" /* JSON */) {
      const formatter = new JsonFormatter();
      const formattedError = formatter.formatError(
        toolExecutionError,
        errorType ?? toolExecutionError.exitCode,
        config2.getSessionId()
      );
      coreEvents.emitFeedback("error", formattedError);
    } else {
      coreEvents.emitFeedback("error", errorMessage);
    }
    runSyncCleanup();
    process.exit(toolExecutionError.exitCode);
  }
  debugLogger.warn(errorMessage);
}
function handleCancellationError(config2) {
  const cancellationError = new FatalCancellationError("Operation cancelled.");
  if (config2.getOutputFormat() === "stream-json" /* STREAM_JSON */) {
    const streamFormatter = new StreamJsonFormatter();
    const metrics = uiTelemetryService.getMetrics();
    streamFormatter.emitEvent({
      type: "result" /* RESULT */,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      status: "error",
      error: {
        type: getErrorType(cancellationError),
        message: cancellationError.message
      },
      stats: streamFormatter.convertToStreamStats(metrics, 0)
    });
    runSyncCleanup();
    process.exit(cancellationError.exitCode);
  } else if (config2.getOutputFormat() === "json" /* JSON */) {
    const formatter = new JsonFormatter();
    const formattedError = formatter.formatError(
      cancellationError,
      cancellationError.exitCode,
      config2.getSessionId()
    );
    coreEvents.emitFeedback("error", formattedError);
    runSyncCleanup();
    process.exit(cancellationError.exitCode);
  } else {
    coreEvents.emitFeedback("error", cancellationError.message);
    runSyncCleanup();
    process.exit(cancellationError.exitCode);
  }
}
function handleMaxTurnsExceededError(config2) {
  const maxTurnsError = new FatalTurnLimitedError(
    "Reached max session turns for this session. Increase the number of turns by specifying maxSessionTurns in settings.json."
  );
  if (config2.getOutputFormat() === "stream-json" /* STREAM_JSON */) {
    const streamFormatter = new StreamJsonFormatter();
    const metrics = uiTelemetryService.getMetrics();
    streamFormatter.emitEvent({
      type: "result" /* RESULT */,
      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
      status: "error",
      error: {
        type: getErrorType(maxTurnsError),
        message: maxTurnsError.message
      },
      stats: streamFormatter.convertToStreamStats(metrics, 0)
    });
    runSyncCleanup();
    process.exit(maxTurnsError.exitCode);
  } else if (config2.getOutputFormat() === "json" /* JSON */) {
    const formatter = new JsonFormatter();
    const formattedError = formatter.formatError(
      maxTurnsError,
      maxTurnsError.exitCode,
      config2.getSessionId()
    );
    coreEvents.emitFeedback("error", formattedError);
    runSyncCleanup();
    process.exit(maxTurnsError.exitCode);
  } else {
    coreEvents.emitFeedback("error", maxTurnsError.message);
    runSyncCleanup();
    process.exit(maxTurnsError.exitCode);
  }
}

// packages/cli/src/ui/utils/textOutput.ts
var TextOutput = class {
  atStartOfLine = true;
  outputStream;
  constructor(outputStream = process.stdout) {
    this.outputStream = outputStream;
  }
  /**
   * Writes a string to stdout.
   * @param str The string to write.
   */
  write(str) {
    if (str.length === 0) {
      return;
    }
    this.outputStream.write(str);
    const strippedStr = stripAnsi(str);
    if (strippedStr.length > 0) {
      this.atStartOfLine = strippedStr.endsWith("\n");
    }
  }
  /**
   * Writes a string to stdout, ensuring it starts on a new line.
   * If the previous output did not end with a newline, one will be added.
   * This prevents adding extra blank lines if a newline already exists.
   * @param str The string to write.
   */
  writeOnNewLine(str) {
    if (!this.atStartOfLine) {
      this.write("\n");
    }
    this.write(str);
  }
  /**
   * Ensures that the output ends with a newline. If the last character
   * written was not a newline, one will be added.
   */
  ensureTrailingNewline() {
    if (!this.atStartOfLine) {
      this.write("\n");
    }
  }
};

// packages/cli/src/nonInteractiveCliAgentSession.ts
import readline2 from "node:readline";
async function runNonInteractive({
  config: config2,
  settings,
  input,
  prompt_id,
  resumedSessionData
}) {
  return promptIdContext.run(prompt_id, async () => {
    const consolePatcher = new ConsolePatcher({
      stderr: true,
      interactive: false,
      debugMode: config2.getDebugMode(),
      onNewMessage: (msg) => {
        coreEvents.emitConsoleLog(msg.type, msg.content);
      }
    });
    if (process.env["GEMINI_CLI_ACTIVITY_LOG_TARGET"]) {
      const { setupInitialActivityLogger } = await import("./devtoolsService-RMCGNCQO.js");
      setupInitialActivityLogger(config2);
    }
    const { stdout: workingStdout } = createWorkingStdio();
    const textOutput = new TextOutput(workingStdout);
    const handleUserFeedback = (payload) => {
      const prefix = payload.severity.toUpperCase();
      process.stderr.write(`[${prefix}] ${payload.message}
`);
      if (payload.error && config2.getDebugMode()) {
        const errorToLog = payload.error instanceof Error ? payload.error.stack || payload.error.message : String(payload.error);
        process.stderr.write(`${errorToLog}
`);
      }
    };
    const startTime = Date.now();
    const streamFormatter = config2.getOutputFormat() === "stream-json" /* STREAM_JSON */ ? new StreamJsonFormatter() : null;
    const abortController = new AbortController();
    let isAborting = false;
    let cancelMessageTimer = null;
    let stdinWasRaw = false;
    let rl = null;
    const setupStdinCancellation = () => {
      if (!process.stdin.isTTY) {
        return;
      }
      stdinWasRaw = process.stdin.isRaw || false;
      process.stdin.setRawMode(true);
      process.stdin.resume();
      rl = readline2.createInterface({
        input: process.stdin,
        escapeCodeTimeout: 0
      });
      readline2.emitKeypressEvents(process.stdin, rl);
      const keypressHandler = (str, key) => {
        if (key && key.ctrl && key.name === "c" || str === "") {
          if (isAborting) {
            return;
          }
          isAborting = true;
          cancelMessageTimer = setTimeout(() => {
            process.stderr.write("\nCancelling...\n");
          }, 200);
          abortController.abort();
        }
      };
      process.stdin.on("keypress", keypressHandler);
    };
    const cleanupStdinCancellation = () => {
      if (cancelMessageTimer) {
        clearTimeout(cancelMessageTimer);
        cancelMessageTimer = null;
      }
      if (rl) {
        rl.close();
        rl = null;
      }
      process.stdin.removeAllListeners("keypress");
      if (process.stdin.isTTY) {
        process.stdin.setRawMode(stdinWasRaw);
        process.stdin.pause();
      }
    };
    let errorToHandle;
    let scheduler;
    let abortSession = () => {
    };
    try {
      consolePatcher.patch();
      if (config2.getRawOutput() && !config2.getAcceptRawOutputRisk() && config2.getOutputFormat() === "text" /* TEXT */) {
        process.stderr.write(
          "[WARNING] --raw-output is enabled. Model output is not sanitized and may contain harmful ANSI sequences (e.g. for phishing or command injection). Use --accept-raw-output-risk to suppress this warning.\n"
        );
      }
      setupStdinCancellation();
      coreEvents.on("user-feedback" /* UserFeedback */, handleUserFeedback);
      coreEvents.drainBacklogs();
      process.stdout.on("error", (err) => {
        if (err.code === "EPIPE") {
          cleanupStdinCancellation();
          consolePatcher.cleanup();
          process.exit(0);
        }
      });
      const geminiClient = config2.getGeminiClient();
      scheduler = new Scheduler({
        context: config2,
        messageBus: config2.getMessageBus(),
        getPreferredEditor: () => void 0,
        schedulerId: ROOT_SCHEDULER_ID
      });
      if (resumedSessionData) {
        await geminiClient.resumeChat(
          convertSessionToClientHistory(
            resumedSessionData.conversation.messages
          ),
          resumedSessionData
        );
      }
      if (streamFormatter) {
        streamFormatter.emitEvent({
          type: "init" /* INIT */,
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          session_id: config2.getSessionId(),
          model: config2.getModel()
        });
      }
      let query;
      if (isSlashCommand(input)) {
        const slashCommandResult = await handleSlashCommand(
          input,
          abortController,
          config2,
          settings
        );
        if (slashCommandResult) {
          query = slashCommandResult;
        }
      }
      if (!query) {
        const { processedQuery, error } = await handleAtCommand({
          query: input,
          config: config2,
          addItem: (_item, _timestamp) => 0,
          onDebugMessage: () => {
          },
          messageId: Date.now(),
          signal: abortController.signal,
          escapePastedAtSymbols: false
        });
        if (error || !processedQuery) {
          throw new FatalInputError(
            error || "Exiting due to an error processing the @ command."
          );
        }
        query = processedQuery;
      }
      if (streamFormatter) {
        streamFormatter.emitEvent({
          type: "message" /* MESSAGE */,
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          role: "user",
          content: input
        });
      }
      const session = new LegacyAgentSession({
        client: geminiClient,
        scheduler,
        config: config2,
        promptId: prompt_id
      });
      abortSession = () => {
        void session.abort();
      };
      abortController.signal.addEventListener("abort", abortSession);
      if (abortController.signal.aborted) {
        throw new FatalCancellationError("Operation cancelled.");
      }
      const { streamId } = await session.send({
        message: {
          content: geminiPartsToContentParts(query),
          displayContent: input
        }
      });
      if (streamId === null) {
        throw new Error(
          "LegacyAgentSession.send() unexpectedly returned no stream for a message send."
        );
      }
      const getTextContent = (parts) => {
        const text = parts?.map((part) => part.type === "text" ? part.text : "").join("");
        return text ? text : void 0;
      };
      const emitFinalSuccessResult = () => {
        if (streamFormatter) {
          const metrics = uiTelemetryService.getMetrics();
          const durationMs = Date.now() - startTime;
          streamFormatter.emitEvent({
            type: "result" /* RESULT */,
            timestamp: (/* @__PURE__ */ new Date()).toISOString(),
            status: "success",
            stats: streamFormatter.convertToStreamStats(metrics, durationMs)
          });
        } else if (config2.getOutputFormat() === "json" /* JSON */) {
          const formatter = new JsonFormatter();
          const stats = uiTelemetryService.getMetrics();
          textOutput.write(
            formatter.format(
              config2.getSessionId(),
              responseText,
              stats,
              void 0,
              warnings
            )
          );
        } else {
          textOutput.ensureTrailingNewline();
        }
      };
      const reconstructFatalError = (event) => {
        const errorMeta = event._meta;
        const name = typeof errorMeta?.["errorName"] === "string" ? errorMeta["errorName"] : void 0;
        let errToThrow;
        switch (name) {
          case "FatalAuthenticationError":
            errToThrow = new FatalAuthenticationError(event.message);
            break;
          case "FatalInputError":
            errToThrow = new FatalInputError(event.message);
            break;
          case "FatalSandboxError":
            errToThrow = new FatalSandboxError(event.message);
            break;
          case "FatalConfigError":
            errToThrow = new FatalConfigError(event.message);
            break;
          case "FatalTurnLimitedError":
            errToThrow = new FatalTurnLimitedError(event.message);
            break;
          case "FatalToolExecutionError":
            errToThrow = new FatalToolExecutionError(event.message);
            break;
          case "FatalCancellationError":
            errToThrow = new FatalCancellationError(event.message);
            break;
          case "FatalError":
            errToThrow = new FatalError(
              event.message,
              typeof errorMeta?.["exitCode"] === "number" ? errorMeta["exitCode"] : 1
            );
            break;
          default:
            errToThrow = new Error(event.message);
            if (name) {
              Object.defineProperty(errToThrow, "name", {
                value: name,
                enumerable: true
              });
            }
            break;
        }
        if (errorMeta?.["exitCode"] !== void 0) {
          Object.defineProperty(errToThrow, "exitCode", {
            value: errorMeta["exitCode"],
            enumerable: true
          });
        }
        if (errorMeta?.["code"] !== void 0) {
          Object.defineProperty(errToThrow, "code", {
            value: errorMeta["code"],
            enumerable: true
          });
        }
        if (errorMeta?.["status"] !== void 0) {
          Object.defineProperty(errToThrow, "status", {
            value: errorMeta["status"],
            enumerable: true
          });
        }
        return errToThrow;
      };
      let responseText = "";
      let preToolResponseText;
      let streamEnded = false;
      const warnings = [];
      for await (const event of session.stream({ streamId })) {
        if (streamEnded) break;
        switch (event.type) {
          case "message": {
            if (event.role === "agent") {
              for (const part of event.content) {
                if (part.type === "text") {
                  const isRaw = config2.getRawOutput() || config2.getAcceptRawOutputRisk();
                  const output = isRaw ? part.text : stripAnsi(part.text);
                  if (streamFormatter) {
                    streamFormatter.emitEvent({
                      type: "message" /* MESSAGE */,
                      timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                      role: "assistant",
                      content: output,
                      delta: true
                    });
                  } else if (config2.getOutputFormat() === "json" /* JSON */) {
                    responseText += output;
                  } else {
                    if (part.text) {
                      textOutput.write(output);
                    }
                  }
                }
              }
            }
            break;
          }
          case "tool_request": {
            if (config2.getOutputFormat() === "json" /* JSON */) {
              preToolResponseText = responseText || preToolResponseText;
              responseText = "";
            }
            if (streamFormatter) {
              streamFormatter.emitEvent({
                type: "tool_use" /* TOOL_USE */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                tool_name: event.name,
                tool_id: event.requestId,
                parameters: event.args
              });
            }
            break;
          }
          case "tool_response": {
            textOutput.ensureTrailingNewline();
            if (streamFormatter) {
              const display = event.display?.result;
              const displayText = displayContentToString(display);
              const errorMsg = getTextContent(event.content) ?? "Tool error";
              streamFormatter.emitEvent({
                type: "tool_result" /* TOOL_RESULT */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                tool_id: event.requestId,
                status: event.isError ? "error" : "success",
                output: displayText,
                error: event.isError ? {
                  type: typeof event.data?.["errorType"] === "string" ? event.data["errorType"] : "TOOL_EXECUTION_ERROR",
                  message: errorMsg
                } : void 0
              });
            }
            if (event.isError) {
              const display = event.display?.result;
              const displayText = displayContentToString(display);
              const errorMsg = getTextContent(event.content) ?? "Tool error";
              if (event.data?.["errorType"] === "stop_execution" /* STOP_EXECUTION */) {
                if (config2.getOutputFormat() === "json" /* JSON */ && !responseText && preToolResponseText) {
                  responseText = preToolResponseText;
                }
                const stopMessage = `Agent execution stopped: ${errorMsg}`;
                if (config2.getOutputFormat() === "text" /* TEXT */) {
                  process.stderr.write(`${stopMessage}
`);
                }
              }
              if (event.data?.["errorType"] === "no_space_left" /* NO_SPACE_LEFT */) {
                throw new FatalToolExecutionError(
                  "Error executing tool " + event.name + ": " + (displayText || errorMsg)
                );
              }
              handleToolError(
                event.name,
                new Error(errorMsg),
                config2,
                typeof event.data?.["errorType"] === "string" ? event.data["errorType"] : void 0,
                displayText
              );
            }
            break;
          }
          case "error": {
            if (event.fatal) {
              throw reconstructFatalError(event);
            }
            const errorCode = event._meta?.["code"];
            if (errorCode === "AGENT_EXECUTION_BLOCKED") {
              const blockMessage = `Agent execution blocked: ${event.message.trim()}`;
              if (config2.getOutputFormat() === "text" /* TEXT */) {
                process.stderr.write(`[WARNING] ${blockMessage}
`);
              } else if (streamFormatter) {
                streamFormatter.emitEvent({
                  type: "error" /* ERROR */,
                  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                  severity: "warning",
                  message: stripAnsi(blockMessage)
                });
              }
              warnings.push(blockMessage);
              break;
            }
            const severity = event.status === "RESOURCE_EXHAUSTED" ? "error" : "warning";
            if (config2.getOutputFormat() === "text" /* TEXT */) {
              process.stderr.write(`[WARNING] ${event.message}
`);
            }
            if (streamFormatter) {
              streamFormatter.emitEvent({
                type: "error" /* ERROR */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                severity,
                message: stripAnsi(event.message)
              });
            }
            warnings.push(event.message);
            break;
          }
          case "agent_end": {
            if (event.reason === "aborted") {
              throw new FatalCancellationError("Operation cancelled.");
            } else if (event.reason === "max_turns") {
              const isConfiguredTurnLimit = typeof event.data?.["maxTurns"] === "number" || typeof event.data?.["turnCount"] === "number";
              if (isConfiguredTurnLimit) {
                throw new FatalTurnLimitedError(
                  "Reached max session turns for this session. Increase the number of turns by specifying maxSessionTurns in settings.json."
                );
              } else if (streamFormatter) {
                streamFormatter.emitEvent({
                  type: "error" /* ERROR */,
                  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                  severity: "error",
                  message: "Maximum session turns exceeded"
                });
              }
            }
            const stopMessage = typeof event.data?.["message"] === "string" ? event.data["message"] : "";
            if (stopMessage && config2.getOutputFormat() === "text" /* TEXT */) {
              process.stderr.write(`Agent execution stopped: ${stopMessage}
`);
            }
            emitFinalSuccessResult();
            streamEnded = true;
            break;
          }
          case "initialize":
          case "session_update":
          case "agent_start":
          case "tool_update":
          case "elicitation_request":
          case "elicitation_response":
          case "usage":
          case "custom":
            break;
          default:
            debugLogger.error("Unknown agent event type:", event);
            event;
            break;
        }
      }
    } catch (error) {
      errorToHandle = error;
    } finally {
      cleanupStdinCancellation();
      abortController.signal.removeEventListener("abort", abortSession);
      scheduler?.dispose();
      consolePatcher.cleanup();
      coreEvents.off("user-feedback" /* UserFeedback */, handleUserFeedback);
    }
    if (errorToHandle) {
      handleError(errorToHandle, config2);
    }
  });
}

// packages/cli/src/nonInteractiveCli.ts
async function runNonInteractive2(params) {
  const useAgentSession = params.config.getAgentSessionNoninteractiveEnabled();
  if (useAgentSession) {
    debugLogger.debug(
      "[ADK] Running non-interactive mode with ADK agent session"
    );
    return runNonInteractive(params);
  }
  const { config: config2, settings, input, prompt_id, resumedSessionData } = params;
  return promptIdContext.run(prompt_id, async () => {
    const consolePatcher = new ConsolePatcher({
      stderr: true,
      interactive: false,
      debugMode: config2.getDebugMode(),
      onNewMessage: (msg) => {
        coreEvents.emitConsoleLog(msg.type, msg.content);
      }
    });
    if (process.env["GEMINI_CLI_ACTIVITY_LOG_TARGET"]) {
      const { setupInitialActivityLogger } = await import("./devtoolsService-RMCGNCQO.js");
      setupInitialActivityLogger(config2);
    }
    const { stdout: workingStdout } = createWorkingStdio();
    const textOutput = new TextOutput(workingStdout);
    const handleUserFeedback = (payload) => {
      const prefix = payload.severity.toUpperCase();
      process.stderr.write(`[${prefix}] ${payload.message}
`);
      if (payload.error && config2.getDebugMode()) {
        const errorToLog = payload.error instanceof Error ? payload.error.stack || payload.error.message : String(payload.error);
        process.stderr.write(`${errorToLog}
`);
      }
    };
    const startTime = Date.now();
    const streamFormatter = config2.getOutputFormat() === "stream-json" /* STREAM_JSON */ ? new StreamJsonFormatter() : null;
    const abortController = new AbortController();
    let isAborting = false;
    let cancelMessageTimer = null;
    let stdinWasRaw = false;
    let rl = null;
    const setupStdinCancellation = () => {
      if (!process.stdin.isTTY) {
        return;
      }
      stdinWasRaw = process.stdin.isRaw || false;
      process.stdin.setRawMode(true);
      process.stdin.resume();
      rl = readline3.createInterface({
        input: process.stdin,
        escapeCodeTimeout: 0
      });
      readline3.emitKeypressEvents(process.stdin, rl);
      const keypressHandler = (str, key) => {
        if (key && key.ctrl && key.name === "c" || str === "") {
          if (isAborting) {
            return;
          }
          isAborting = true;
          cancelMessageTimer = setTimeout(() => {
            process.stderr.write("\nCancelling...\n");
          }, 200);
          abortController.abort();
        }
      };
      process.stdin.on("keypress", keypressHandler);
    };
    const cleanupStdinCancellation = () => {
      if (cancelMessageTimer) {
        clearTimeout(cancelMessageTimer);
        cancelMessageTimer = null;
      }
      if (rl) {
        rl.close();
        rl = null;
      }
      process.stdin.removeAllListeners("keypress");
      if (process.stdin.isTTY) {
        process.stdin.setRawMode(stdinWasRaw);
        process.stdin.pause();
      }
    };
    let errorToHandle;
    let scheduler;
    try {
      consolePatcher.patch();
      if (config2.getRawOutput() && !config2.getAcceptRawOutputRisk() && config2.getOutputFormat() === "text" /* TEXT */) {
        process.stderr.write(
          "[WARNING] --raw-output is enabled. Model output is not sanitized and may contain harmful ANSI sequences (e.g. for phishing or command injection). Use --accept-raw-output-risk to suppress this warning.\n"
        );
      }
      setupStdinCancellation();
      coreEvents.on("user-feedback" /* UserFeedback */, handleUserFeedback);
      coreEvents.drainBacklogs();
      process.stdout.on("error", (err) => {
        if (err.code === "EPIPE") {
          process.exit(0);
        }
      });
      const geminiClient = config2.getGeminiClient();
      scheduler = new Scheduler({
        context: config2,
        messageBus: config2.getMessageBus(),
        getPreferredEditor: () => void 0,
        schedulerId: ROOT_SCHEDULER_ID
      });
      if (resumedSessionData) {
        await geminiClient.resumeChat(
          convertSessionToClientHistory(
            resumedSessionData.conversation.messages
          ),
          resumedSessionData
        );
      }
      if (streamFormatter) {
        streamFormatter.emitEvent({
          type: "init" /* INIT */,
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          session_id: config2.getSessionId(),
          model: config2.getModel()
        });
      }
      let query;
      if (isSlashCommand(input)) {
        const slashCommandResult = await handleSlashCommand(
          input,
          abortController,
          config2,
          settings
        );
        if (slashCommandResult) {
          query = slashCommandResult;
        }
      }
      if (!query) {
        const { processedQuery, error } = await handleAtCommand({
          query: input,
          config: config2,
          addItem: (_item, _timestamp) => 0,
          onDebugMessage: () => {
          },
          messageId: Date.now(),
          signal: abortController.signal,
          escapePastedAtSymbols: false
        });
        if (error || !processedQuery) {
          throw new FatalInputError(
            error || "Exiting due to an error processing the @ command."
          );
        }
        query = processedQuery;
      }
      if (streamFormatter) {
        streamFormatter.emitEvent({
          type: "message" /* MESSAGE */,
          timestamp: (/* @__PURE__ */ new Date()).toISOString(),
          role: "user",
          content: input
        });
      }
      let currentMessages = [{ role: "user", parts: query }];
      let turnCount = 0;
      let invalidStreamError;
      const warnings = [];
      while (true) {
        turnCount++;
        if (config2.getMaxSessionTurns() >= 0 && turnCount > config2.getMaxSessionTurns()) {
          handleMaxTurnsExceededError(config2);
        }
        const toolCallRequests = [];
        const responseStream = geminiClient.sendMessageStream(
          currentMessages[0]?.parts || [],
          abortController.signal,
          prompt_id,
          void 0,
          turnCount === 1 ? input : void 0
        );
        let responseText = "";
        for await (const event of responseStream) {
          if (abortController.signal.aborted) {
            handleCancellationError(config2);
          }
          if (event.type === "content" /* Content */) {
            const isRaw = config2.getRawOutput() || config2.getAcceptRawOutputRisk();
            const output = isRaw ? event.value : stripAnsi(event.value);
            if (streamFormatter) {
              streamFormatter.emitEvent({
                type: "message" /* MESSAGE */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                role: "assistant",
                content: output,
                delta: true
              });
            } else if (config2.getOutputFormat() === "json" /* JSON */) {
              responseText += output;
            } else {
              if (event.value) {
                textOutput.write(output);
              }
            }
          } else if (event.type === "tool_call_request" /* ToolCallRequest */) {
            if (streamFormatter) {
              streamFormatter.emitEvent({
                type: "tool_use" /* TOOL_USE */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                tool_name: event.value.name,
                tool_id: event.value.callId,
                parameters: event.value.args
              });
            }
            toolCallRequests.push(event.value);
          } else if (event.type === "loop_detected" /* LoopDetected */) {
            const message = "Loop detected, stopping execution";
            if (streamFormatter) {
              streamFormatter.emitEvent({
                type: "error" /* ERROR */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                severity: "warning",
                message
              });
            }
            warnings.push(message);
          } else if (event.type === "max_session_turns" /* MaxSessionTurns */) {
            const message = "Maximum session turns exceeded";
            if (streamFormatter) {
              streamFormatter.emitEvent({
                type: "error" /* ERROR */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                severity: "error",
                message
              });
            }
            warnings.push(message);
          } else if (event.type === "error" /* Error */) {
            throw event.value.error;
          } else if (event.type === "agent_execution_stopped" /* AgentExecutionStopped */) {
            const stopMessage = `Agent execution stopped: ${event.value.systemMessage?.trim() || event.value.reason}`;
            if (config2.getOutputFormat() === "text" /* TEXT */) {
              process.stderr.write(`${stopMessage}
`);
            }
            if (streamFormatter) {
              const metrics = uiTelemetryService.getMetrics();
              const durationMs = Date.now() - startTime;
              streamFormatter.emitEvent({
                type: "result" /* RESULT */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                status: "success",
                stats: streamFormatter.convertToStreamStats(
                  metrics,
                  durationMs
                )
              });
            } else if (config2.getOutputFormat() === "json" /* JSON */) {
              const formatter = new JsonFormatter();
              const stats = uiTelemetryService.getMetrics();
              textOutput.write(
                formatter.format(
                  config2.getSessionId(),
                  responseText,
                  stats,
                  void 0,
                  [...warnings, stopMessage]
                )
              );
            } else {
              textOutput.ensureTrailingNewline();
            }
            return;
          } else if (event.type === "agent_execution_blocked" /* AgentExecutionBlocked */) {
            const blockMessage = `Agent execution blocked: ${event.value.systemMessage?.trim() || event.value.reason}`;
            if (config2.getOutputFormat() === "text" /* TEXT */) {
              process.stderr.write(`[WARNING] ${blockMessage}
`);
            } else if (streamFormatter) {
              streamFormatter.emitEvent({
                type: "error" /* ERROR */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                severity: "warning",
                message: stripAnsi(blockMessage)
              });
            }
            warnings.push(blockMessage);
          } else if (event.type === "invalid_stream" /* InvalidStream */) {
            invalidStreamError = "Invalid stream: The model returned an empty response or malformed tool call.";
            if (streamFormatter) {
              streamFormatter.emitEvent({
                type: "error" /* ERROR */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                severity: "error",
                message: invalidStreamError
              });
            } else if (config2.getOutputFormat() === "text" /* TEXT */) {
              process.stderr.write(`[ERROR] ${invalidStreamError}
`);
            }
            toolCallRequests.length = 0;
            break;
          }
        }
        if (toolCallRequests.length > 0) {
          textOutput.ensureTrailingNewline();
          const completedToolCalls = await scheduler.schedule(
            toolCallRequests,
            abortController.signal
          );
          const toolResponseParts = [];
          for (const completedToolCall of completedToolCalls) {
            const toolResponse = completedToolCall.response;
            const requestInfo = completedToolCall.request;
            if (streamFormatter) {
              streamFormatter.emitEvent({
                type: "tool_result" /* TOOL_RESULT */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                tool_id: requestInfo.callId,
                status: completedToolCall.status === "error" ? "error" : "success",
                output: typeof toolResponse.resultDisplay === "string" ? toolResponse.resultDisplay : void 0,
                error: toolResponse.error ? {
                  type: toolResponse.errorType || "TOOL_EXECUTION_ERROR",
                  message: toolResponse.error.message
                } : void 0
              });
            }
            if (toolResponse.error) {
              handleToolError(
                requestInfo.name,
                toolResponse.error,
                config2,
                toolResponse.errorType || "TOOL_EXECUTION_ERROR",
                typeof toolResponse.resultDisplay === "string" ? toolResponse.resultDisplay : void 0
              );
            }
            if (toolResponse.responseParts) {
              toolResponseParts.push(...toolResponse.responseParts);
            }
          }
          try {
            const currentModel = geminiClient.getCurrentSequenceModel() ?? config2.getModel();
            geminiClient.getChat().recordCompletedToolCalls(currentModel, completedToolCalls);
            await recordToolCallInteractions(config2, completedToolCalls);
          } catch (error) {
            debugLogger.error(
              `Error recording completed tool call information: ${error}`
            );
          }
          const stopExecutionTool = completedToolCalls.find(
            (tc) => tc.response.errorType === "stop_execution" /* STOP_EXECUTION */
          );
          if (stopExecutionTool && stopExecutionTool.response.error) {
            const stopMessage = `Agent execution stopped: ${stopExecutionTool.response.error.message}`;
            if (config2.getOutputFormat() === "text" /* TEXT */) {
              process.stderr.write(`${stopMessage}
`);
            }
            if (streamFormatter) {
              const metrics = uiTelemetryService.getMetrics();
              const durationMs = Date.now() - startTime;
              streamFormatter.emitEvent({
                type: "result" /* RESULT */,
                timestamp: (/* @__PURE__ */ new Date()).toISOString(),
                status: "success",
                stats: streamFormatter.convertToStreamStats(
                  metrics,
                  durationMs
                )
              });
            } else if (config2.getOutputFormat() === "json" /* JSON */) {
              const formatter = new JsonFormatter();
              const stats = uiTelemetryService.getMetrics();
              textOutput.write(
                formatter.format(
                  config2.getSessionId(),
                  responseText,
                  stats,
                  void 0,
                  warnings
                )
              );
            } else {
              textOutput.ensureTrailingNewline();
            }
            return;
          }
          currentMessages = [{ role: "user", parts: toolResponseParts }];
        } else {
          if (streamFormatter) {
            const metrics = uiTelemetryService.getMetrics();
            const durationMs = Date.now() - startTime;
            streamFormatter.emitEvent({
              type: "result" /* RESULT */,
              timestamp: (/* @__PURE__ */ new Date()).toISOString(),
              status: invalidStreamError ? "error" : "success",
              stats: streamFormatter.convertToStreamStats(metrics, durationMs)
            });
          } else if (config2.getOutputFormat() === "json" /* JSON */) {
            const formatter = new JsonFormatter();
            const stats = uiTelemetryService.getMetrics();
            textOutput.write(
              formatter.format(
                config2.getSessionId(),
                responseText,
                stats,
                invalidStreamError ? { type: "INVALID_STREAM", message: invalidStreamError } : void 0,
                warnings
              )
            );
          } else {
            textOutput.ensureTrailingNewline();
          }
          return;
        }
      }
    } catch (error) {
      errorToHandle = error;
    } finally {
      cleanupStdinCancellation();
      scheduler?.dispose();
      consolePatcher.cleanup();
      coreEvents.off("user-feedback" /* UserFeedback */, handleUserFeedback);
    }
    if (errorToHandle) {
      handleError(errorToHandle, config2);
    }
  });
}

// packages/cli/src/utils/worktreeSetup.ts
async function setupWorktree(worktreeName) {
  if (process.env["GEMINI_CLI_WORKTREE_HANDLED"] === "1") {
    return void 0;
  }
  try {
    const projectRoot = await getProjectRootForWorktree(process.cwd());
    const service = await createWorktreeService(projectRoot);
    const worktreeInfo = await service.setup(worktreeName || void 0);
    process.chdir(worktreeInfo.path);
    process.env["GEMINI_CLI_WORKTREE_HANDLED"] = "1";
    return worktreeInfo;
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    writeToStderr(`Failed to create or switch to worktree: ${errorMessage}
`);
    process.exit(1);
  }
}

// node_modules/@agentclientprotocol/sdk/dist/schema/index.js
var AGENT_METHODS = {
  authenticate: "authenticate",
  initialize: "initialize",
  session_cancel: "session/cancel",
  session_close: "session/close",
  session_fork: "session/fork",
  session_list: "session/list",
  session_load: "session/load",
  session_new: "session/new",
  session_prompt: "session/prompt",
  session_resume: "session/resume",
  session_set_config_option: "session/set_config_option",
  session_set_mode: "session/set_mode",
  session_set_model: "session/set_model"
};
var CLIENT_METHODS = {
  fs_read_text_file: "fs/read_text_file",
  fs_write_text_file: "fs/write_text_file",
  session_request_permission: "session/request_permission",
  session_update: "session/update",
  terminal_create: "terminal/create",
  terminal_kill: "terminal/kill",
  terminal_output: "terminal/output",
  terminal_release: "terminal/release",
  terminal_wait_for_exit: "terminal/wait_for_exit"
};
var PROTOCOL_VERSION = 1;

// node_modules/@agentclientprotocol/sdk/dist/schema/zod.gen.js
var zAuthCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  terminal: external_exports2.boolean().optional().default(false)
});
var zAuthEnvVar = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  label: external_exports2.string().nullish(),
  name: external_exports2.string(),
  optional: external_exports2.boolean().optional().default(false),
  secret: external_exports2.boolean().optional().default(true)
});
var zAuthMethodAgent = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  description: external_exports2.string().nullish(),
  id: external_exports2.string(),
  name: external_exports2.string()
});
var zAuthMethodEnvVar = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  description: external_exports2.string().nullish(),
  id: external_exports2.string(),
  link: external_exports2.string().nullish(),
  name: external_exports2.string(),
  vars: external_exports2.array(zAuthEnvVar)
});
var zAuthMethodTerminal = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  args: external_exports2.array(external_exports2.string()).optional(),
  description: external_exports2.string().nullish(),
  env: external_exports2.record(external_exports2.string(), external_exports2.string()).optional(),
  id: external_exports2.string(),
  name: external_exports2.string()
});
var zAuthMethod = external_exports2.union([
  zAuthMethodEnvVar.and(external_exports2.object({
    type: external_exports2.literal("env_var")
  })),
  zAuthMethodTerminal.and(external_exports2.object({
    type: external_exports2.literal("terminal")
  })),
  zAuthMethodAgent
]);
var zAuthenticateRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  methodId: external_exports2.string()
});
var zAuthenticateResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zBlobResourceContents = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  blob: external_exports2.string(),
  mimeType: external_exports2.string().nullish(),
  uri: external_exports2.string()
});
var zCloseSessionResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zCost = external_exports2.object({
  amount: external_exports2.number(),
  currency: external_exports2.string()
});
var zCreateTerminalResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  terminalId: external_exports2.string()
});
var zDiff = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  newText: external_exports2.string(),
  oldText: external_exports2.string().nullish(),
  path: external_exports2.string()
});
var zEnvVariable = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  name: external_exports2.string(),
  value: external_exports2.string()
});
var zErrorCode = external_exports2.union([
  external_exports2.literal(-32700),
  external_exports2.literal(-32600),
  external_exports2.literal(-32601),
  external_exports2.literal(-32602),
  external_exports2.literal(-32603),
  external_exports2.literal(-32800),
  external_exports2.literal(-32e3),
  external_exports2.literal(-32002),
  external_exports2.number().int().min(-2147483648, {
    message: "Invalid value: Expected int32 to be >= -2147483648"
  }).max(2147483647, {
    message: "Invalid value: Expected int32 to be <= 2147483647"
  })
]);
var zError = external_exports2.object({
  code: zErrorCode,
  data: external_exports2.unknown().optional(),
  message: external_exports2.string()
});
var zExtNotification = external_exports2.unknown();
var zExtRequest = external_exports2.unknown();
var zExtResponse = external_exports2.unknown();
var zFileSystemCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  readTextFile: external_exports2.boolean().optional().default(false),
  writeTextFile: external_exports2.boolean().optional().default(false)
});
var zClientCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  auth: zAuthCapabilities.optional().default({ terminal: false }),
  fs: zFileSystemCapabilities.optional().default({ readTextFile: false, writeTextFile: false }),
  terminal: external_exports2.boolean().optional().default(false)
});
var zHttpHeader = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  name: external_exports2.string(),
  value: external_exports2.string()
});
var zImplementation = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  name: external_exports2.string(),
  title: external_exports2.string().nullish(),
  version: external_exports2.string()
});
var zKillTerminalResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zListSessionsRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  cursor: external_exports2.string().nullish(),
  cwd: external_exports2.string().nullish()
});
var zMcpCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  http: external_exports2.boolean().optional().default(false),
  sse: external_exports2.boolean().optional().default(false)
});
var zMcpServerHttp = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  headers: external_exports2.array(zHttpHeader),
  name: external_exports2.string(),
  url: external_exports2.string()
});
var zMcpServerSse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  headers: external_exports2.array(zHttpHeader),
  name: external_exports2.string(),
  url: external_exports2.string()
});
var zMcpServerStdio = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  args: external_exports2.array(external_exports2.string()),
  command: external_exports2.string(),
  env: external_exports2.array(zEnvVariable),
  name: external_exports2.string()
});
var zMcpServer = external_exports2.union([
  zMcpServerHttp.and(external_exports2.object({
    type: external_exports2.literal("http")
  })),
  zMcpServerSse.and(external_exports2.object({
    type: external_exports2.literal("sse")
  })),
  zMcpServerStdio
]);
var zModelId = external_exports2.string();
var zModelInfo = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  description: external_exports2.string().nullish(),
  modelId: zModelId,
  name: external_exports2.string()
});
var zNewSessionRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  cwd: external_exports2.string(),
  mcpServers: external_exports2.array(zMcpServer)
});
var zPermissionOptionId = external_exports2.string();
var zPermissionOptionKind = external_exports2.union([
  external_exports2.literal("allow_once"),
  external_exports2.literal("allow_always"),
  external_exports2.literal("reject_once"),
  external_exports2.literal("reject_always")
]);
var zPermissionOption = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  kind: zPermissionOptionKind,
  name: external_exports2.string(),
  optionId: zPermissionOptionId
});
var zPlanEntryPriority = external_exports2.union([
  external_exports2.literal("high"),
  external_exports2.literal("medium"),
  external_exports2.literal("low")
]);
var zPlanEntryStatus = external_exports2.union([
  external_exports2.literal("pending"),
  external_exports2.literal("in_progress"),
  external_exports2.literal("completed")
]);
var zPlanEntry = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  content: external_exports2.string(),
  priority: zPlanEntryPriority,
  status: zPlanEntryStatus
});
var zPlan = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  entries: external_exports2.array(zPlanEntry)
});
var zPromptCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  audio: external_exports2.boolean().optional().default(false),
  embeddedContext: external_exports2.boolean().optional().default(false),
  image: external_exports2.boolean().optional().default(false)
});
var zProtocolVersion = external_exports2.number().int().gte(0).lte(65535);
var zInitializeRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  clientCapabilities: zClientCapabilities.optional().default({
    auth: { terminal: false },
    fs: { readTextFile: false, writeTextFile: false },
    terminal: false
  }),
  clientInfo: zImplementation.nullish(),
  protocolVersion: zProtocolVersion
});
var zReadTextFileResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  content: external_exports2.string()
});
var zReleaseTerminalResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zRequestId = external_exports2.union([external_exports2.number(), external_exports2.string()]).nullable();
var zCancelRequestNotification = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  requestId: zRequestId
});
var zRole = external_exports2.enum(["assistant", "user"]);
var zAnnotations = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  audience: external_exports2.array(zRole).nullish(),
  lastModified: external_exports2.string().nullish(),
  priority: external_exports2.number().nullish()
});
var zAudioContent = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  annotations: zAnnotations.nullish(),
  data: external_exports2.string(),
  mimeType: external_exports2.string()
});
var zImageContent = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  annotations: zAnnotations.nullish(),
  data: external_exports2.string(),
  mimeType: external_exports2.string(),
  uri: external_exports2.string().nullish()
});
var zResourceLink = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  annotations: zAnnotations.nullish(),
  description: external_exports2.string().nullish(),
  mimeType: external_exports2.string().nullish(),
  name: external_exports2.string(),
  size: external_exports2.number().nullish(),
  title: external_exports2.string().nullish(),
  uri: external_exports2.string()
});
var zSelectedPermissionOutcome = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  optionId: zPermissionOptionId
});
var zRequestPermissionOutcome = external_exports2.union([
  external_exports2.object({
    outcome: external_exports2.literal("cancelled")
  }),
  zSelectedPermissionOutcome.and(external_exports2.object({
    outcome: external_exports2.literal("selected")
  }))
]);
var zRequestPermissionResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  outcome: zRequestPermissionOutcome
});
var zSessionCloseCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zSessionConfigBoolean = external_exports2.object({
  currentValue: external_exports2.boolean()
});
var zSessionConfigGroupId = external_exports2.string();
var zSessionConfigId = external_exports2.string();
var zSessionConfigOptionCategory = external_exports2.union([
  external_exports2.literal("mode"),
  external_exports2.literal("model"),
  external_exports2.literal("thought_level"),
  external_exports2.string()
]);
var zSessionConfigValueId = external_exports2.string();
var zSessionConfigSelectOption = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  description: external_exports2.string().nullish(),
  name: external_exports2.string(),
  value: zSessionConfigValueId
});
var zSessionConfigSelectGroup = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  group: zSessionConfigGroupId,
  name: external_exports2.string(),
  options: external_exports2.array(zSessionConfigSelectOption)
});
var zSessionConfigSelectOptions = external_exports2.union([
  external_exports2.array(zSessionConfigSelectOption),
  external_exports2.array(zSessionConfigSelectGroup)
]);
var zSessionConfigSelect = external_exports2.object({
  currentValue: zSessionConfigValueId,
  options: zSessionConfigSelectOptions
});
var zSessionConfigOption = external_exports2.intersection(external_exports2.union([
  zSessionConfigSelect.and(external_exports2.object({
    type: external_exports2.literal("select")
  })),
  zSessionConfigBoolean.and(external_exports2.object({
    type: external_exports2.literal("boolean")
  }))
]), external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  category: zSessionConfigOptionCategory.nullish(),
  description: external_exports2.string().nullish(),
  id: zSessionConfigId,
  name: external_exports2.string()
}));
var zConfigOptionUpdate = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  configOptions: external_exports2.array(zSessionConfigOption)
});
var zSessionForkCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zSessionId = external_exports2.string();
var zCancelNotification = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  sessionId: zSessionId
});
var zClientNotification = external_exports2.object({
  method: external_exports2.string(),
  params: external_exports2.union([zCancelNotification, zExtNotification]).nullish()
});
var zCloseSessionRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  sessionId: zSessionId
});
var zCreateTerminalRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  args: external_exports2.array(external_exports2.string()).optional(),
  command: external_exports2.string(),
  cwd: external_exports2.string().nullish(),
  env: external_exports2.array(zEnvVariable).optional(),
  outputByteLimit: external_exports2.number().nullish(),
  sessionId: zSessionId
});
var zForkSessionRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  cwd: external_exports2.string(),
  mcpServers: external_exports2.array(zMcpServer).optional(),
  sessionId: zSessionId
});
var zKillTerminalRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  sessionId: zSessionId,
  terminalId: external_exports2.string()
});
var zLoadSessionRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  cwd: external_exports2.string(),
  mcpServers: external_exports2.array(zMcpServer),
  sessionId: zSessionId
});
var zReadTextFileRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  limit: external_exports2.number().int().gte(0).max(4294967295, {
    message: "Invalid value: Expected uint32 to be <= 4294967295"
  }).nullish(),
  line: external_exports2.number().int().gte(0).max(4294967295, {
    message: "Invalid value: Expected uint32 to be <= 4294967295"
  }).nullish(),
  path: external_exports2.string(),
  sessionId: zSessionId
});
var zReleaseTerminalRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  sessionId: zSessionId,
  terminalId: external_exports2.string()
});
var zResumeSessionRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  cwd: external_exports2.string(),
  mcpServers: external_exports2.array(zMcpServer).optional(),
  sessionId: zSessionId
});
var zSessionInfo = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  cwd: external_exports2.string(),
  sessionId: zSessionId,
  title: external_exports2.string().nullish(),
  updatedAt: external_exports2.string().nullish()
});
var zListSessionsResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  nextCursor: external_exports2.string().nullish(),
  sessions: external_exports2.array(zSessionInfo)
});
var zSessionInfoUpdate = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  title: external_exports2.string().nullish(),
  updatedAt: external_exports2.string().nullish()
});
var zSessionListCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zSessionModeId = external_exports2.string();
var zCurrentModeUpdate = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  currentModeId: zSessionModeId
});
var zSessionMode = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  description: external_exports2.string().nullish(),
  id: zSessionModeId,
  name: external_exports2.string()
});
var zSessionModeState = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  availableModes: external_exports2.array(zSessionMode),
  currentModeId: zSessionModeId
});
var zSessionModelState = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  availableModels: external_exports2.array(zModelInfo),
  currentModelId: zModelId
});
var zForkSessionResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  configOptions: external_exports2.array(zSessionConfigOption).nullish(),
  models: zSessionModelState.nullish(),
  modes: zSessionModeState.nullish(),
  sessionId: zSessionId
});
var zLoadSessionResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  configOptions: external_exports2.array(zSessionConfigOption).nullish(),
  models: zSessionModelState.nullish(),
  modes: zSessionModeState.nullish()
});
var zNewSessionResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  configOptions: external_exports2.array(zSessionConfigOption).nullish(),
  models: zSessionModelState.nullish(),
  modes: zSessionModeState.nullish(),
  sessionId: zSessionId
});
var zResumeSessionResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  configOptions: external_exports2.array(zSessionConfigOption).nullish(),
  models: zSessionModelState.nullish(),
  modes: zSessionModeState.nullish()
});
var zSessionResumeCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zSessionCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  close: zSessionCloseCapabilities.nullish(),
  fork: zSessionForkCapabilities.nullish(),
  list: zSessionListCapabilities.nullish(),
  resume: zSessionResumeCapabilities.nullish()
});
var zAgentCapabilities = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  loadSession: external_exports2.boolean().optional().default(false),
  mcpCapabilities: zMcpCapabilities.optional().default({ http: false, sse: false }),
  promptCapabilities: zPromptCapabilities.optional().default({
    audio: false,
    embeddedContext: false,
    image: false
  }),
  sessionCapabilities: zSessionCapabilities.optional().default({})
});
var zInitializeResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  agentCapabilities: zAgentCapabilities.optional().default({
    loadSession: false,
    mcpCapabilities: { http: false, sse: false },
    promptCapabilities: {
      audio: false,
      embeddedContext: false,
      image: false
    },
    sessionCapabilities: {}
  }),
  agentInfo: zImplementation.nullish(),
  authMethods: external_exports2.array(zAuthMethod).optional().default([]),
  protocolVersion: zProtocolVersion
});
var zSetSessionConfigOptionRequest = external_exports2.intersection(external_exports2.union([
  external_exports2.object({
    type: external_exports2.literal("boolean"),
    value: external_exports2.boolean()
  }),
  external_exports2.object({
    value: zSessionConfigValueId
  })
]), external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  configId: zSessionConfigId,
  sessionId: zSessionId
}));
var zSetSessionConfigOptionResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  configOptions: external_exports2.array(zSessionConfigOption)
});
var zSetSessionModeRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  modeId: zSessionModeId,
  sessionId: zSessionId
});
var zSetSessionModeResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zSetSessionModelRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  modelId: zModelId,
  sessionId: zSessionId
});
var zSetSessionModelResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zStopReason = external_exports2.union([
  external_exports2.literal("end_turn"),
  external_exports2.literal("max_tokens"),
  external_exports2.literal("max_turn_requests"),
  external_exports2.literal("refusal"),
  external_exports2.literal("cancelled")
]);
var zTerminal = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  terminalId: external_exports2.string()
});
var zTerminalExitStatus = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  exitCode: external_exports2.number().int().gte(0).max(4294967295, {
    message: "Invalid value: Expected uint32 to be <= 4294967295"
  }).nullish(),
  signal: external_exports2.string().nullish()
});
var zTerminalOutputRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  sessionId: zSessionId,
  terminalId: external_exports2.string()
});
var zTerminalOutputResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  exitStatus: zTerminalExitStatus.nullish(),
  output: external_exports2.string(),
  truncated: external_exports2.boolean()
});
var zTextContent = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  annotations: zAnnotations.nullish(),
  text: external_exports2.string()
});
var zTextResourceContents = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  mimeType: external_exports2.string().nullish(),
  text: external_exports2.string(),
  uri: external_exports2.string()
});
var zEmbeddedResourceResource = external_exports2.union([
  zTextResourceContents,
  zBlobResourceContents
]);
var zEmbeddedResource = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  annotations: zAnnotations.nullish(),
  resource: zEmbeddedResourceResource
});
var zContentBlock = external_exports2.union([
  zTextContent.and(external_exports2.object({
    type: external_exports2.literal("text")
  })),
  zImageContent.and(external_exports2.object({
    type: external_exports2.literal("image")
  })),
  zAudioContent.and(external_exports2.object({
    type: external_exports2.literal("audio")
  })),
  zResourceLink.and(external_exports2.object({
    type: external_exports2.literal("resource_link")
  })),
  zEmbeddedResource.and(external_exports2.object({
    type: external_exports2.literal("resource")
  }))
]);
var zContent = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  content: zContentBlock
});
var zContentChunk = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  content: zContentBlock,
  messageId: external_exports2.string().nullish()
});
var zPromptRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  messageId: external_exports2.string().nullish(),
  prompt: external_exports2.array(zContentBlock),
  sessionId: zSessionId
});
var zClientRequest = external_exports2.object({
  id: zRequestId,
  method: external_exports2.string(),
  params: external_exports2.union([
    zInitializeRequest,
    zAuthenticateRequest,
    zNewSessionRequest,
    zLoadSessionRequest,
    zListSessionsRequest,
    zForkSessionRequest,
    zResumeSessionRequest,
    zCloseSessionRequest,
    zSetSessionModeRequest,
    zSetSessionConfigOptionRequest,
    zPromptRequest,
    zSetSessionModelRequest,
    zExtRequest
  ]).nullish()
});
var zToolCallContent = external_exports2.union([
  zContent.and(external_exports2.object({
    type: external_exports2.literal("content")
  })),
  zDiff.and(external_exports2.object({
    type: external_exports2.literal("diff")
  })),
  zTerminal.and(external_exports2.object({
    type: external_exports2.literal("terminal")
  }))
]);
var zToolCallId = external_exports2.string();
var zToolCallLocation = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  line: external_exports2.number().int().gte(0).max(4294967295, {
    message: "Invalid value: Expected uint32 to be <= 4294967295"
  }).nullish(),
  path: external_exports2.string()
});
var zToolCallStatus = external_exports2.union([
  external_exports2.literal("pending"),
  external_exports2.literal("in_progress"),
  external_exports2.literal("completed"),
  external_exports2.literal("failed")
]);
var zToolKind = external_exports2.union([
  external_exports2.literal("read"),
  external_exports2.literal("edit"),
  external_exports2.literal("delete"),
  external_exports2.literal("move"),
  external_exports2.literal("search"),
  external_exports2.literal("execute"),
  external_exports2.literal("think"),
  external_exports2.literal("fetch"),
  external_exports2.literal("switch_mode"),
  external_exports2.literal("other")
]);
var zToolCall = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  content: external_exports2.array(zToolCallContent).optional(),
  kind: zToolKind.optional(),
  locations: external_exports2.array(zToolCallLocation).optional(),
  rawInput: external_exports2.unknown().optional(),
  rawOutput: external_exports2.unknown().optional(),
  status: zToolCallStatus.optional(),
  title: external_exports2.string(),
  toolCallId: zToolCallId
});
var zToolCallUpdate = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  content: external_exports2.array(zToolCallContent).nullish(),
  kind: zToolKind.nullish(),
  locations: external_exports2.array(zToolCallLocation).nullish(),
  rawInput: external_exports2.unknown().optional(),
  rawOutput: external_exports2.unknown().optional(),
  status: zToolCallStatus.nullish(),
  title: external_exports2.string().nullish(),
  toolCallId: zToolCallId
});
var zRequestPermissionRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  options: external_exports2.array(zPermissionOption),
  sessionId: zSessionId,
  toolCall: zToolCallUpdate
});
var zUnstructuredCommandInput = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  hint: external_exports2.string()
});
var zAvailableCommandInput = zUnstructuredCommandInput;
var zAvailableCommand = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  description: external_exports2.string(),
  input: zAvailableCommandInput.nullish(),
  name: external_exports2.string()
});
var zAvailableCommandsUpdate = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  availableCommands: external_exports2.array(zAvailableCommand)
});
var zUsage = external_exports2.object({
  cachedReadTokens: external_exports2.number().nullish(),
  cachedWriteTokens: external_exports2.number().nullish(),
  inputTokens: external_exports2.number(),
  outputTokens: external_exports2.number(),
  thoughtTokens: external_exports2.number().nullish(),
  totalTokens: external_exports2.number()
});
var zPromptResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  stopReason: zStopReason,
  usage: zUsage.nullish(),
  userMessageId: external_exports2.string().nullish()
});
var zAgentResponse = external_exports2.union([
  external_exports2.object({
    id: zRequestId,
    result: external_exports2.union([
      zInitializeResponse,
      zAuthenticateResponse,
      zNewSessionResponse,
      zLoadSessionResponse,
      zListSessionsResponse,
      zForkSessionResponse,
      zResumeSessionResponse,
      zCloseSessionResponse,
      zSetSessionModeResponse,
      zSetSessionConfigOptionResponse,
      zPromptResponse,
      zSetSessionModelResponse,
      zExtResponse
    ])
  }),
  external_exports2.object({
    error: zError,
    id: zRequestId
  })
]);
var zUsageUpdate = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  cost: zCost.nullish(),
  size: external_exports2.number(),
  used: external_exports2.number()
});
var zSessionUpdate = external_exports2.union([
  zContentChunk.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("user_message_chunk")
  })),
  zContentChunk.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("agent_message_chunk")
  })),
  zContentChunk.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("agent_thought_chunk")
  })),
  zToolCall.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("tool_call")
  })),
  zToolCallUpdate.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("tool_call_update")
  })),
  zPlan.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("plan")
  })),
  zAvailableCommandsUpdate.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("available_commands_update")
  })),
  zCurrentModeUpdate.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("current_mode_update")
  })),
  zConfigOptionUpdate.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("config_option_update")
  })),
  zSessionInfoUpdate.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("session_info_update")
  })),
  zUsageUpdate.and(external_exports2.object({
    sessionUpdate: external_exports2.literal("usage_update")
  }))
]);
var zSessionNotification = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  sessionId: zSessionId,
  update: zSessionUpdate
});
var zAgentNotification = external_exports2.object({
  method: external_exports2.string(),
  params: external_exports2.union([zSessionNotification, zExtNotification]).nullish()
});
var zWaitForTerminalExitRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  sessionId: zSessionId,
  terminalId: external_exports2.string()
});
var zWaitForTerminalExitResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  exitCode: external_exports2.number().int().gte(0).max(4294967295, {
    message: "Invalid value: Expected uint32 to be <= 4294967295"
  }).nullish(),
  signal: external_exports2.string().nullish()
});
var zWriteTextFileRequest = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish(),
  content: external_exports2.string(),
  path: external_exports2.string(),
  sessionId: zSessionId
});
var zAgentRequest = external_exports2.object({
  id: zRequestId,
  method: external_exports2.string(),
  params: external_exports2.union([
    zWriteTextFileRequest,
    zReadTextFileRequest,
    zRequestPermissionRequest,
    zCreateTerminalRequest,
    zTerminalOutputRequest,
    zReleaseTerminalRequest,
    zWaitForTerminalExitRequest,
    zKillTerminalRequest,
    zExtRequest
  ]).nullish()
});
var zWriteTextFileResponse = external_exports2.object({
  _meta: external_exports2.record(external_exports2.string(), external_exports2.unknown()).nullish()
});
var zClientResponse = external_exports2.union([
  external_exports2.object({
    id: zRequestId,
    result: external_exports2.union([
      zWriteTextFileResponse,
      zReadTextFileResponse,
      zRequestPermissionResponse,
      zCreateTerminalResponse,
      zTerminalOutputResponse,
      zReleaseTerminalResponse,
      zWaitForTerminalExitResponse,
      zKillTerminalResponse,
      zExtResponse
    ])
  }),
  external_exports2.object({
    error: zError,
    id: zRequestId
  })
]);

// node_modules/@agentclientprotocol/sdk/dist/stream.js
function ndJsonStream(output, input) {
  const textEncoder = new TextEncoder();
  const textDecoder = new TextDecoder();
  const readable = new ReadableStream({
    async start(controller) {
      let content = "";
      const reader = input.getReader();
      try {
        while (true) {
          const { value, done } = await reader.read();
          if (done) {
            break;
          }
          if (!value) {
            continue;
          }
          content += textDecoder.decode(value, { stream: true });
          const lines = content.split("\n");
          content = lines.pop() || "";
          for (const line of lines) {
            const trimmedLine = line.trim();
            if (trimmedLine) {
              try {
                const message = JSON.parse(trimmedLine);
                controller.enqueue(message);
              } catch (err) {
                console.error("Failed to parse JSON message:", trimmedLine, err);
              }
            }
          }
        }
      } finally {
        reader.releaseLock();
        controller.close();
      }
    }
  });
  const writable = new WritableStream({
    async write(message) {
      const content = JSON.stringify(message) + "\n";
      const writer = output.getWriter();
      try {
        await writer.write(textEncoder.encode(content));
      } finally {
        writer.releaseLock();
      }
    }
  });
  return { readable, writable };
}

// node_modules/@agentclientprotocol/sdk/dist/acp.js
var AgentSideConnection = class {
  #connection;
  /**
   * Creates a new agent-side connection to a client.
   *
   * This establishes the communication channel from the agent's perspective
   * following the ACP specification.
   *
   * @param toAgent - A function that creates an Agent handler to process incoming client requests
   * @param stream - The bidirectional message stream for communication. Typically created using
   *                 {@link ndJsonStream} for stdio-based connections.
   *
   * See protocol docs: [Communication Model](https://agentclientprotocol.com/protocol/overview#communication-model)
   */
  constructor(toAgent, stream) {
    const agent = toAgent(this);
    const requestHandler = async (method, params) => {
      switch (method) {
        case AGENT_METHODS.initialize: {
          const validatedParams = zInitializeRequest.parse(params);
          return agent.initialize(validatedParams);
        }
        case AGENT_METHODS.session_new: {
          const validatedParams = zNewSessionRequest.parse(params);
          return agent.newSession(validatedParams);
        }
        case AGENT_METHODS.session_load: {
          if (!agent.loadSession) {
            throw RequestError.methodNotFound(method);
          }
          const validatedParams = zLoadSessionRequest.parse(params);
          return agent.loadSession(validatedParams);
        }
        case AGENT_METHODS.session_list: {
          if (!agent.listSessions) {
            throw RequestError.methodNotFound(method);
          }
          const validatedParams = zListSessionsRequest.parse(params);
          return agent.listSessions(validatedParams);
        }
        case AGENT_METHODS.session_fork: {
          if (!agent.unstable_forkSession) {
            throw RequestError.methodNotFound(method);
          }
          const validatedParams = zForkSessionRequest.parse(params);
          return agent.unstable_forkSession(validatedParams);
        }
        case AGENT_METHODS.session_resume: {
          if (!agent.unstable_resumeSession) {
            throw RequestError.methodNotFound(method);
          }
          const validatedParams = zResumeSessionRequest.parse(params);
          return agent.unstable_resumeSession(validatedParams);
        }
        case AGENT_METHODS.session_close: {
          if (!agent.unstable_closeSession) {
            throw RequestError.methodNotFound(method);
          }
          const validatedParams = zCloseSessionRequest.parse(params);
          return agent.unstable_closeSession(validatedParams);
        }
        case AGENT_METHODS.session_set_mode: {
          if (!agent.setSessionMode) {
            throw RequestError.methodNotFound(method);
          }
          const validatedParams = zSetSessionModeRequest.parse(params);
          const result = await agent.setSessionMode(validatedParams);
          return result ?? {};
        }
        case AGENT_METHODS.authenticate: {
          const validatedParams = zAuthenticateRequest.parse(params);
          const result = await agent.authenticate(validatedParams);
          return result ?? {};
        }
        case AGENT_METHODS.session_prompt: {
          const validatedParams = zPromptRequest.parse(params);
          return agent.prompt(validatedParams);
        }
        case AGENT_METHODS.session_set_model: {
          if (!agent.unstable_setSessionModel) {
            throw RequestError.methodNotFound(method);
          }
          const validatedParams = zSetSessionModelRequest.parse(params);
          const result = await agent.unstable_setSessionModel(validatedParams);
          return result ?? {};
        }
        case AGENT_METHODS.session_set_config_option: {
          if (!agent.setSessionConfigOption) {
            throw RequestError.methodNotFound(method);
          }
          const validatedParams = zSetSessionConfigOptionRequest.parse(params);
          return agent.setSessionConfigOption(validatedParams);
        }
        default:
          if (agent.extMethod) {
            return agent.extMethod(method, params);
          }
          throw RequestError.methodNotFound(method);
      }
    };
    const notificationHandler = async (method, params) => {
      switch (method) {
        case AGENT_METHODS.session_cancel: {
          const validatedParams = zCancelNotification.parse(params);
          return agent.cancel(validatedParams);
        }
        default:
          if (agent.extNotification) {
            return agent.extNotification(method, params);
          }
          throw RequestError.methodNotFound(method);
      }
    };
    this.#connection = new Connection(requestHandler, notificationHandler, stream);
  }
  /**
   * Handles session update notifications from the agent.
   *
   * This is a notification endpoint (no response expected) that sends
   * real-time updates about session progress, including message chunks,
   * tool calls, and execution plans.
   *
   * Note: Clients SHOULD continue accepting tool call updates even after
   * sending a `session/cancel` notification, as the agent may send final
   * updates before responding with the cancelled stop reason.
   *
   * See protocol docs: [Agent Reports Output](https://agentclientprotocol.com/protocol/prompt-turn#3-agent-reports-output)
   */
  async sessionUpdate(params) {
    return await this.#connection.sendNotification(CLIENT_METHODS.session_update, params);
  }
  /**
   * Requests permission from the user for a tool call operation.
   *
   * Called by the agent when it needs user authorization before executing
   * a potentially sensitive operation. The client should present the options
   * to the user and return their decision.
   *
   * If the client cancels the prompt turn via `session/cancel`, it MUST
   * respond to this request with `RequestPermissionOutcome::Cancelled`.
   *
   * See protocol docs: [Requesting Permission](https://agentclientprotocol.com/protocol/tool-calls#requesting-permission)
   */
  async requestPermission(params) {
    return await this.#connection.sendRequest(CLIENT_METHODS.session_request_permission, params);
  }
  /**
   * Reads content from a text file in the client's file system.
   *
   * Only available if the client advertises the `fs.readTextFile` capability.
   * Allows the agent to access file contents within the client's environment.
   *
   * See protocol docs: [Client](https://agentclientprotocol.com/protocol/overview#client)
   */
  async readTextFile(params) {
    return await this.#connection.sendRequest(CLIENT_METHODS.fs_read_text_file, params);
  }
  /**
   * Writes content to a text file in the client's file system.
   *
   * Only available if the client advertises the `fs.writeTextFile` capability.
   * Allows the agent to create or modify files within the client's environment.
   *
   * See protocol docs: [Client](https://agentclientprotocol.com/protocol/overview#client)
   */
  async writeTextFile(params) {
    return await this.#connection.sendRequest(CLIENT_METHODS.fs_write_text_file, params) ?? {};
  }
  /**
   * Executes a command in a new terminal.
   *
   * Returns a `TerminalHandle` that can be used to get output, wait for exit,
   * kill the command, or release the terminal.
   *
   * The terminal can also be embedded in tool calls by using its ID in
   * `ToolCallContent` with type "terminal".
   *
   * @param params - The terminal creation parameters
   * @returns A handle to control and monitor the terminal
   */
  async createTerminal(params) {
    const response = await this.#connection.sendRequest(CLIENT_METHODS.terminal_create, params);
    return new TerminalHandle(response.terminalId, params.sessionId, this.#connection);
  }
  /**
   * Extension method
   *
   * Allows the Agent to send an arbitrary request that is not part of the ACP spec.
   */
  async extMethod(method, params) {
    return await this.#connection.sendRequest(method, params);
  }
  /**
   * Extension notification
   *
   * Allows the Agent to send an arbitrary notification that is not part of the ACP spec.
   */
  async extNotification(method, params) {
    return await this.#connection.sendNotification(method, params);
  }
  /**
   * AbortSignal that aborts when the connection closes.
   *
   * This signal can be used to:
   * - Listen for connection closure: `connection.signal.addEventListener('abort', () => {...})`
   * - Check connection status synchronously: `if (connection.signal.aborted) {...}`
   * - Pass to other APIs (fetch, setTimeout) for automatic cancellation
   *
   * The connection closes when the underlying stream ends, either normally or due to an error.
   *
   * @example
   * ```typescript
   * const connection = new AgentSideConnection(agent, stream);
   *
   * // Listen for closure
   * connection.signal.addEventListener('abort', () => {
   *   console.log('Connection closed - performing cleanup');
   * });
   *
   * // Check status
   * if (connection.signal.aborted) {
   *   console.log('Connection is already closed');
   * }
   *
   * // Pass to other APIs
   * fetch(url, { signal: connection.signal });
   * ```
   */
  get signal() {
    return this.#connection.signal;
  }
  /**
   * Promise that resolves when the connection closes.
   *
   * The connection closes when the underlying stream ends, either normally or due to an error.
   * Once closed, the connection cannot send or receive any more messages.
   *
   * This is useful for async/await style cleanup:
   *
   * @example
   * ```typescript
   * const connection = new AgentSideConnection(agent, stream);
   * await connection.closed;
   * console.log('Connection closed - performing cleanup');
   * ```
   */
  get closed() {
    return this.#connection.closed;
  }
};
var TerminalHandle = class {
  id;
  #sessionId;
  #connection;
  constructor(id, sessionId, conn) {
    this.id = id;
    this.#sessionId = sessionId;
    this.#connection = conn;
  }
  /**
   * Gets the current terminal output without waiting for the command to exit.
   */
  async currentOutput() {
    return await this.#connection.sendRequest(CLIENT_METHODS.terminal_output, {
      sessionId: this.#sessionId,
      terminalId: this.id
    });
  }
  /**
   * Waits for the terminal command to complete and returns its exit status.
   */
  async waitForExit() {
    return await this.#connection.sendRequest(CLIENT_METHODS.terminal_wait_for_exit, {
      sessionId: this.#sessionId,
      terminalId: this.id
    });
  }
  /**
   * Kills the terminal command without releasing the terminal.
   *
   * The terminal remains valid after killing, allowing you to:
   * - Get the final output with `currentOutput()`
   * - Check the exit status
   * - Release the terminal when done
   *
   * Useful for implementing timeouts or cancellation.
   */
  async kill() {
    return await this.#connection.sendRequest(CLIENT_METHODS.terminal_kill, {
      sessionId: this.#sessionId,
      terminalId: this.id
    }) ?? {};
  }
  /**
   * Releases the terminal and frees all associated resources.
   *
   * If the command is still running, it will be killed.
   * After release, the terminal ID becomes invalid and cannot be used
   * with other terminal methods.
   *
   * Tool calls that already reference this terminal will continue to
   * display its output.
   *
   * **Important:** Always call this method when done with the terminal.
   */
  async release() {
    return await this.#connection.sendRequest(CLIENT_METHODS.terminal_release, {
      sessionId: this.#sessionId,
      terminalId: this.id
    }) ?? {};
  }
  async [Symbol.asyncDispose]() {
    await this.release();
  }
};
var Connection = class {
  #pendingResponses = /* @__PURE__ */ new Map();
  #nextRequestId = 0;
  #requestHandler;
  #notificationHandler;
  #stream;
  #writeQueue = Promise.resolve();
  #abortController = new AbortController();
  #closedPromise;
  constructor(requestHandler, notificationHandler, stream) {
    this.#requestHandler = requestHandler;
    this.#notificationHandler = notificationHandler;
    this.#stream = stream;
    this.#closedPromise = new Promise((resolve9) => {
      this.#abortController.signal.addEventListener("abort", () => resolve9());
    });
    this.#receive();
  }
  /**
   * AbortSignal that aborts when the connection closes.
   *
   * This signal can be used to:
   * - Listen for connection closure via event listeners
   * - Check connection status synchronously with `signal.aborted`
   * - Pass to other APIs (fetch, setTimeout) for automatic cancellation
   */
  get signal() {
    return this.#abortController.signal;
  }
  /**
   * Promise that resolves when the connection closes.
   *
   * The connection closes when the underlying stream ends, either normally
   * or due to an error. Once closed, the connection cannot send or receive
   * any more messages.
   *
   * @example
   * ```typescript
   * const connection = new ClientSideConnection(client, stream);
   * await connection.closed;
   * console.log('Connection closed - performing cleanup');
   * ```
   */
  get closed() {
    return this.#closedPromise;
  }
  async #receive() {
    const reader = this.#stream.readable.getReader();
    try {
      while (true) {
        const { value: message, done } = await reader.read();
        if (done) {
          break;
        }
        if (!message) {
          continue;
        }
        try {
          this.#processMessage(message);
        } catch (err) {
          console.error("Unexpected error during message processing:", message, err);
          if ("id" in message && message.id !== void 0) {
            this.#sendMessage({
              jsonrpc: "2.0",
              id: message.id,
              error: {
                code: -32700,
                message: "Parse error"
              }
            });
          }
        }
      }
    } finally {
      reader.releaseLock();
      this.#abortController.abort();
    }
  }
  async #processMessage(message) {
    if ("method" in message && "id" in message) {
      const response = await this.#tryCallRequestHandler(message.method, message.params);
      if ("error" in response) {
        console.error("Error handling request", message, response.error);
      }
      await this.#sendMessage({
        jsonrpc: "2.0",
        id: message.id,
        ...response
      });
    } else if ("method" in message) {
      const response = await this.#tryCallNotificationHandler(message.method, message.params);
      if ("error" in response) {
        console.error("Error handling notification", message, response.error);
      }
    } else if ("id" in message) {
      this.#handleResponse(message);
    } else {
      console.error("Invalid message", { message });
    }
  }
  async #tryCallRequestHandler(method, params) {
    try {
      const result = await this.#requestHandler(method, params);
      return { result: result ?? null };
    } catch (error) {
      if (error instanceof RequestError) {
        return error.toResult();
      }
      if (error instanceof external_exports.ZodError) {
        return RequestError.invalidParams(error.format()).toResult();
      }
      let details;
      if (error instanceof Error) {
        details = error.message;
      } else if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
        details = error.message;
      }
      try {
        return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
      } catch {
        return RequestError.internalError({ details }).toResult();
      }
    }
  }
  async #tryCallNotificationHandler(method, params) {
    try {
      await this.#notificationHandler(method, params);
      return { result: null };
    } catch (error) {
      if (error instanceof RequestError) {
        return error.toResult();
      }
      if (error instanceof external_exports.ZodError) {
        return RequestError.invalidParams(error.format()).toResult();
      }
      let details;
      if (error instanceof Error) {
        details = error.message;
      } else if (typeof error === "object" && error != null && "message" in error && typeof error.message === "string") {
        details = error.message;
      }
      try {
        return RequestError.internalError(details ? JSON.parse(details) : {}).toResult();
      } catch {
        return RequestError.internalError({ details }).toResult();
      }
    }
  }
  #handleResponse(response) {
    const pendingResponse = this.#pendingResponses.get(response.id);
    if (pendingResponse) {
      if ("result" in response) {
        pendingResponse.resolve(response.result);
      } else if ("error" in response) {
        pendingResponse.reject(response.error);
      }
      this.#pendingResponses.delete(response.id);
    } else {
      console.error("Got response to unknown request", response.id);
    }
  }
  async sendRequest(method, params) {
    const id = this.#nextRequestId++;
    const responsePromise = new Promise((resolve9, reject) => {
      this.#pendingResponses.set(id, { resolve: resolve9, reject });
    });
    await this.#sendMessage({ jsonrpc: "2.0", id, method, params });
    return responsePromise;
  }
  async sendNotification(method, params) {
    await this.#sendMessage({ jsonrpc: "2.0", method, params });
  }
  async #sendMessage(message) {
    this.#writeQueue = this.#writeQueue.then(async () => {
      const writer = this.#stream.writable.getWriter();
      try {
        await writer.write(message);
      } finally {
        writer.releaseLock();
      }
    }).catch((error) => {
      console.error("ACP write error:", error);
    });
    return this.#writeQueue;
  }
};
var RequestError = class _RequestError extends Error {
  code;
  data;
  constructor(code, message, data) {
    super(message);
    this.code = code;
    this.name = "RequestError";
    this.data = data;
  }
  /**
   * Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
   */
  static parseError(data, additionalMessage) {
    return new _RequestError(-32700, `Parse error${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
  }
  /**
   * The JSON sent is not a valid Request object.
   */
  static invalidRequest(data, additionalMessage) {
    return new _RequestError(-32600, `Invalid request${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
  }
  /**
   * The method does not exist / is not available.
   */
  static methodNotFound(method) {
    return new _RequestError(-32601, `"Method not found": ${method}`, {
      method
    });
  }
  /**
   * Invalid method parameter(s).
   */
  static invalidParams(data, additionalMessage) {
    return new _RequestError(-32602, `Invalid params${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
  }
  /**
   * Internal JSON-RPC error.
   */
  static internalError(data, additionalMessage) {
    return new _RequestError(-32603, `Internal error${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
  }
  /**
   * Authentication required.
   */
  static authRequired(data, additionalMessage) {
    return new _RequestError(-32e3, `Authentication required${additionalMessage ? `: ${additionalMessage}` : ""}`, data);
  }
  /**
   * Resource, such as a file, was not found
   */
  static resourceNotFound(uri) {
    return new _RequestError(-32002, `Resource not found${uri ? `: ${uri}` : ""}`, uri && { uri });
  }
  toResult() {
    return {
      error: {
        code: this.code,
        message: this.message,
        data: this.data
      }
    };
  }
  toErrorResponse() {
    return {
      code: this.code,
      message: this.message,
      data: this.data
    };
  }
};

// packages/cli/src/acp/acpStdioTransport.ts
import { Readable, Writable } from "node:stream";

// packages/cli/src/acp/acpErrors.ts
function getAcpErrorMessage(error) {
  const coreMessage = getErrorMessage(error);
  return extractRecursiveMessage(coreMessage);
}
function extractRecursiveMessage(input) {
  const trimmed = input.trim();
  if (trimmed.startsWith("{") && trimmed.endsWith("}") || trimmed.startsWith("[") && trimmed.endsWith("]")) {
    try {
      const parsed = JSON.parse(trimmed);
      const next = parsed?.error?.message || parsed?.[0]?.error?.message || parsed?.message;
      if (next && typeof next === "string" && next !== input) {
        return extractRecursiveMessage(next);
      }
    } catch {
    }
  }
  return input;
}

// packages/cli/src/acp/acpSessionManager.ts
import { randomUUID as randomUUID2 } from "node:crypto";

// packages/cli/src/acp/acpSession.ts
import * as fs12 from "node:fs/promises";
import * as path12 from "node:path";
import { randomUUID } from "node:crypto";

// packages/cli/src/acp/commands/commandRegistry.ts
var CommandRegistry = class {
  commands = /* @__PURE__ */ new Map();
  register(command2) {
    if (this.commands.has(command2.name)) {
      debugLogger.warn(`Command ${command2.name} already registered. Skipping.`);
      return;
    }
    this.commands.set(command2.name, command2);
    for (const subCommand of command2.subCommands ?? []) {
      this.register(subCommand);
    }
  }
  get(commandName) {
    return this.commands.get(commandName);
  }
  getAllCommands() {
    return [...this.commands.values()];
  }
};

// packages/cli/src/acp/commands/memory.ts
var MemoryCommand = class {
  name = "memory";
  description = "Manage memory.";
  subCommands = [
    new ShowMemoryCommand(),
    new RefreshMemoryCommand(),
    new ListMemoryCommand(),
    new InboxMemoryCommand()
  ];
  requiresWorkspace = true;
  async execute(context, _) {
    return new ShowMemoryCommand().execute(context, _);
  }
};
var ShowMemoryCommand = class {
  name = "memory show";
  description = "Shows the current memory contents.";
  async execute(context, _) {
    const result = showMemory(context.agentContext.config);
    return { name: this.name, data: result.content };
  }
};
var RefreshMemoryCommand = class {
  name = "memory refresh";
  aliases = ["memory reload"];
  description = "Refreshes the memory from the source.";
  async execute(context, _) {
    const result = await refreshMemory(context.agentContext.config);
    return { name: this.name, data: result.content };
  }
};
var ListMemoryCommand = class {
  name = "memory list";
  description = "Lists the paths of the GEMINI.md files in use.";
  async execute(context, _) {
    const result = listMemoryFiles(context.agentContext.config);
    return { name: this.name, data: result.content };
  }
};
var InboxMemoryCommand = class {
  name = "memory inbox";
  description = "Lists memory items extracted from past sessions that are pending review.";
  async execute(context, _) {
    if (!context.agentContext.config.isAutoMemoryEnabled()) {
      return {
        name: this.name,
        data: "The memory inbox requires Auto Memory. Enable it with: experimental.autoMemory = true in settings."
      };
    }
    const [skills, patches, memoryPatches] = await Promise.all([
      listInboxSkills(context.agentContext.config),
      listInboxPatches(context.agentContext.config),
      listInboxMemoryPatches(context.agentContext.config)
    ]);
    if (skills.length === 0 && patches.length === 0 && memoryPatches.length === 0) {
      return { name: this.name, data: "No items in inbox." };
    }
    const lines = [];
    for (const s of skills) {
      const date3 = s.extractedAt ? ` (extracted: ${new Date(s.extractedAt).toLocaleDateString()})` : "";
      lines.push(`- **${s.name}**: ${s.description}${date3}`);
    }
    for (const p of patches) {
      const targets = p.entries.map((e) => e.targetPath).join(", ");
      const date3 = p.extractedAt ? ` (extracted: ${new Date(p.extractedAt).toLocaleDateString()})` : "";
      lines.push(`- **${p.name}** (update): patches ${targets}${date3}`);
    }
    for (const memoryPatch of memoryPatches) {
      const targets = memoryPatch.entries.map((e) => e.targetPath).join(", ");
      const date3 = memoryPatch.extractedAt ? ` (latest extract: ${new Date(memoryPatch.extractedAt).toLocaleDateString()})` : "";
      const sourceCount = memoryPatch.sourceFiles.length;
      const sourceLabel = sourceCount === 1 ? "patch" : "patches";
      lines.push(
        `- **${memoryPatch.name}** (${sourceCount} source ${sourceLabel}, ${memoryPatch.entries.length} hunks): targets ${targets}${date3}`
      );
    }
    const total = skills.length + patches.length + memoryPatches.length;
    return {
      name: this.name,
      data: `Memory inbox (${total}):
${lines.join("\n")}`
    };
  }
};

// packages/cli/src/acp/commands/extensions.ts
import { stat } from "node:fs/promises";
var ExtensionsCommand = class {
  name = "extensions";
  description = "Manage extensions.";
  subCommands = [
    new ListExtensionsCommand(),
    new ExploreExtensionsCommand(),
    new EnableExtensionCommand(),
    new DisableExtensionCommand(),
    new InstallExtensionCommand(),
    new LinkExtensionCommand(),
    new UninstallExtensionCommand(),
    new RestartExtensionCommand(),
    new UpdateExtensionCommand()
  ];
  async execute(context, _) {
    return new ListExtensionsCommand().execute(context, _);
  }
};
var ListExtensionsCommand = class {
  name = "extensions list";
  description = "Lists all installed extensions.";
  async execute(context, _) {
    const extensions = listExtensions(context.agentContext.config);
    const data = extensions.length ? extensions : "No extensions installed.";
    return { name: this.name, data };
  }
};
var ExploreExtensionsCommand = class {
  name = "extensions explore";
  description = "Explore available extensions.";
  async execute(_context, _) {
    const extensionsUrl = "https://geminicli.com/extensions/";
    return {
      name: this.name,
      data: `View or install available extensions at ${extensionsUrl}`
    };
  }
};
function getEnableDisableContext(config2, args, invocationName) {
  const extensionManager = config2.getExtensionLoader();
  if (!(extensionManager instanceof ExtensionManager)) {
    return {
      error: `Cannot ${invocationName} extensions in this environment.`
    };
  }
  if (args.length === 0) {
    return {
      error: `Usage: /extensions ${invocationName} <extension> [--scope=<user|workspace|session>]`
    };
  }
  let scope = "User" /* User */;
  if (args.includes("--scope=workspace") || args.includes("workspace")) {
    scope = "Workspace" /* Workspace */;
  } else if (args.includes("--scope=session") || args.includes("session")) {
    scope = "Session" /* Session */;
  }
  const name = args.filter(
    (a) => !a.startsWith("--scope") && !["user", "workspace", "session"].includes(a)
  )[0];
  let names = [];
  if (name === "--all") {
    let extensions = extensionManager.getExtensions();
    if (invocationName === "enable") {
      extensions = extensions.filter((ext) => !ext.isActive);
    }
    if (invocationName === "disable") {
      extensions = extensions.filter((ext) => ext.isActive);
    }
    names = extensions.map((ext) => ext.name);
  } else if (name) {
    names = [name];
  } else {
    return { error: "No extension name provided." };
  }
  return { extensionManager, names, scope };
}
var EnableExtensionCommand = class {
  name = "extensions enable";
  description = "Enable an extension.";
  async execute(context, args) {
    const enableContext = getEnableDisableContext(
      context.agentContext.config,
      args,
      "enable"
    );
    if ("error" in enableContext) {
      return { name: this.name, data: enableContext.error };
    }
    const { names, scope, extensionManager } = enableContext;
    const output = [];
    for (const name of names) {
      try {
        await extensionManager.enableExtension(name, scope);
        output.push(`Extension "${name}" enabled for scope "${scope}".`);
        const extension = extensionManager.getExtensions().find((e) => e.name === name);
        if (extension?.mcpServers) {
          const mcpEnablementManager = McpServerEnablementManager.getInstance();
          const mcpClientManager = context.agentContext.config.getMcpClientManager();
          const enabledServers = await mcpEnablementManager.autoEnableServers(
            Object.keys(extension.mcpServers)
          );
          if (mcpClientManager && enabledServers.length > 0) {
            const restartPromises = enabledServers.map(
              (serverName) => mcpClientManager.restartServer(serverName).catch((error) => {
                output.push(
                  `Failed to restart MCP server '${serverName}': ${getErrorMessage(error)}`
                );
              })
            );
            await Promise.all(restartPromises);
            output.push(`Re-enabled MCP servers: ${enabledServers.join(", ")}`);
          }
        }
      } catch (e) {
        output.push(`Failed to enable "${name}": ${getErrorMessage(e)}`);
      }
    }
    return { name: this.name, data: output.join("\n") || "No action taken." };
  }
};
var DisableExtensionCommand = class {
  name = "extensions disable";
  description = "Disable an extension.";
  async execute(context, args) {
    const enableContext = getEnableDisableContext(
      context.agentContext.config,
      args,
      "disable"
    );
    if ("error" in enableContext) {
      return { name: this.name, data: enableContext.error };
    }
    const { names, scope, extensionManager } = enableContext;
    const output = [];
    for (const name of names) {
      try {
        await extensionManager.disableExtension(name, scope);
        output.push(`Extension "${name}" disabled for scope "${scope}".`);
      } catch (e) {
        output.push(`Failed to disable "${name}": ${getErrorMessage(e)}`);
      }
    }
    return { name: this.name, data: output.join("\n") || "No action taken." };
  }
};
var InstallExtensionCommand = class {
  name = "extensions install";
  description = "Install an extension from a git repo or local path.";
  async execute(context, args) {
    const extensionLoader = context.agentContext.config.getExtensionLoader();
    if (!(extensionLoader instanceof ExtensionManager)) {
      return {
        name: this.name,
        data: "Cannot install extensions in this environment."
      };
    }
    const source = args.join(" ").trim();
    if (!source) {
      return { name: this.name, data: `Usage: /extensions install <source>` };
    }
    if (/[;&|`'"]/.test(source)) {
      return {
        name: this.name,
        data: `Invalid source: contains disallowed characters.`
      };
    }
    try {
      const installMetadata = await inferInstallMetadata(source);
      const extension = await extensionLoader.installOrUpdateExtension(installMetadata);
      return {
        name: this.name,
        data: `Extension "${extension.name}" installed successfully.`
      };
    } catch (error) {
      return {
        name: this.name,
        data: `Failed to install extension from "${source}": ${getErrorMessage(error)}`
      };
    }
  }
};
var LinkExtensionCommand = class {
  name = "extensions link";
  description = "Link an extension from a local path.";
  async execute(context, args) {
    const extensionLoader = context.agentContext.config.getExtensionLoader();
    if (!(extensionLoader instanceof ExtensionManager)) {
      return {
        name: this.name,
        data: "Cannot link extensions in this environment."
      };
    }
    const sourceFilepath = args.join(" ").trim();
    if (!sourceFilepath) {
      return { name: this.name, data: `Usage: /extensions link <source>` };
    }
    try {
      await stat(sourceFilepath);
    } catch {
      return { name: this.name, data: `Invalid source: ${sourceFilepath}` };
    }
    try {
      const extension = await extensionLoader.installOrUpdateExtension({
        source: sourceFilepath,
        type: "link"
      });
      return {
        name: this.name,
        data: `Extension "${extension.name}" linked successfully.`
      };
    } catch (error) {
      return {
        name: this.name,
        data: `Failed to link extension: ${getErrorMessage(error)}`
      };
    }
  }
};
var UninstallExtensionCommand = class {
  name = "extensions uninstall";
  description = "Uninstall an extension.";
  async execute(context, args) {
    const extensionLoader = context.agentContext.config.getExtensionLoader();
    if (!(extensionLoader instanceof ExtensionManager)) {
      return {
        name: this.name,
        data: "Cannot uninstall extensions in this environment."
      };
    }
    const all = args.includes("--all");
    const names = args.filter((a) => !a.startsWith("--")).map((a) => a.trim());
    if (!all && names.length === 0) {
      return {
        name: this.name,
        data: `Usage: /extensions uninstall <extension-names...>|--all`
      };
    }
    let namesToUninstall = [];
    if (all) {
      namesToUninstall = extensionLoader.getExtensions().map((ext) => ext.name);
    } else {
      namesToUninstall = names;
    }
    if (namesToUninstall.length === 0) {
      return {
        name: this.name,
        data: all ? "No extensions installed." : "No extension name provided."
      };
    }
    const output = [];
    for (const extensionName of namesToUninstall) {
      try {
        await extensionLoader.uninstallExtension(extensionName, false);
        output.push(`Extension "${extensionName}" uninstalled successfully.`);
      } catch (error) {
        output.push(
          `Failed to uninstall extension "${extensionName}": ${getErrorMessage(error)}`
        );
      }
    }
    return { name: this.name, data: output.join("\n") };
  }
};
var RestartExtensionCommand = class {
  name = "extensions restart";
  description = "Restart an extension.";
  async execute(context, args) {
    const extensionLoader = context.agentContext.config.getExtensionLoader();
    if (!(extensionLoader instanceof ExtensionManager)) {
      return { name: this.name, data: "Cannot restart extensions." };
    }
    const all = args.includes("--all");
    const names = all ? null : args.filter((a) => !!a);
    if (!all && names?.length === 0) {
      return {
        name: this.name,
        data: "Usage: /extensions restart <extension-names>|--all"
      };
    }
    let extensionsToRestart = extensionLoader.getExtensions().filter((e) => e.isActive);
    if (names) {
      extensionsToRestart = extensionsToRestart.filter(
        (e) => names.includes(e.name)
      );
    }
    if (extensionsToRestart.length === 0) {
      return {
        name: this.name,
        data: "No active extensions matched the request."
      };
    }
    const output = [];
    for (const extension of extensionsToRestart) {
      try {
        await extensionLoader.restartExtension(extension);
        output.push(`Restarted "${extension.name}".`);
      } catch (e) {
        output.push(
          `Failed to restart "${extension.name}": ${getErrorMessage(e)}`
        );
      }
    }
    return { name: this.name, data: output.join("\n") };
  }
};
var UpdateExtensionCommand = class {
  name = "extensions update";
  description = "Update an extension.";
  async execute(context, args) {
    const extensionLoader = context.agentContext.config.getExtensionLoader();
    if (!(extensionLoader instanceof ExtensionManager)) {
      return { name: this.name, data: "Cannot update extensions." };
    }
    const all = args.includes("--all");
    const names = all ? null : args.filter((a) => !!a);
    if (!all && names?.length === 0) {
      return {
        name: this.name,
        data: "Usage: /extensions update <extension-names>|--all"
      };
    }
    return {
      name: this.name,
      data: "Headless extension updating requires internal UI dispatches. Please use `gemini extensions update` directly in the terminal."
    };
  }
};

// packages/cli/src/acp/commands/init.ts
import * as fs10 from "node:fs";
import * as path10 from "node:path";
var InitCommand = class {
  name = "init";
  description = "Analyzes the project and creates a tailored GEMINI.md file";
  requiresWorkspace = true;
  async execute(context, _args = []) {
    const targetDir = context.agentContext.config.getTargetDir();
    if (!targetDir) {
      throw new Error("Command requires a workspace.");
    }
    const geminiMdPath = path10.join(targetDir, "GEMINI.md");
    const result = performInit(fs10.existsSync(geminiMdPath));
    switch (result.type) {
      case "message":
        return {
          name: this.name,
          data: result
        };
      case "submit_prompt":
        fs10.writeFileSync(geminiMdPath, "", "utf8");
        if (typeof result.content !== "string") {
          throw new Error("Init command content must be a string.");
        }
        return {
          name: this.name,
          data: {
            type: "message",
            messageType: "info",
            content: `A template GEMINI.md has been created at ${geminiMdPath}.

To populate it with project context, you can run the following prompt in a new chat:

${result.content}`
          }
        };
      default:
        throw new Error("Unknown result type from performInit");
    }
  }
};

// packages/cli/src/acp/commands/restore.ts
import * as fs11 from "node:fs/promises";
import * as path11 from "node:path";
var RestoreCommand = class {
  name = "restore";
  description = "Restore to a previous checkpoint, or list available checkpoints to restore. This will reset the conversation and file history to the state it was in when the checkpoint was created";
  requiresWorkspace = true;
  subCommands = [new ListCheckpointsCommand()];
  async execute(context, args) {
    const { agentContext, git: gitService } = context;
    const { config: config2 } = agentContext;
    const argsStr = args.join(" ");
    try {
      if (!argsStr) {
        return await new ListCheckpointsCommand().execute(context);
      }
      if (!config2.getCheckpointingEnabled()) {
        return {
          name: this.name,
          data: "Checkpointing is not enabled. Please enable it in your settings (`general.checkpointing.enabled: true`) to use /restore."
        };
      }
      const selectedFile = argsStr.endsWith(".json") ? argsStr : `${argsStr}.json`;
      const checkpointDir = config2.storage.getProjectTempCheckpointsDir();
      const filePath = path11.join(checkpointDir, selectedFile);
      let data;
      try {
        data = await fs11.readFile(filePath, "utf-8");
      } catch (error) {
        if (isNodeError(error) && error.code === "ENOENT") {
          return {
            name: this.name,
            data: `File not found: ${selectedFile}`
          };
        }
        throw error;
      }
      const toolCallData = JSON.parse(data);
      const ToolCallDataSchema = getToolCallDataSchema();
      const parseResult = ToolCallDataSchema.safeParse(toolCallData);
      if (!parseResult.success) {
        return {
          name: this.name,
          data: "Checkpoint file is invalid or corrupted."
        };
      }
      const restoreResultGenerator = performRestore(
        parseResult.data,
        gitService
      );
      const restoreResult = [];
      for await (const result of restoreResultGenerator) {
        restoreResult.push(result);
      }
      const formattedResult = restoreResult.map((r) => {
        if (r.type === "message") {
          return `[${r.messageType.toUpperCase()}] ${r.content}`;
        } else if (r.type === "load_history") {
          return `Loaded history with ${r.clientHistory.length} messages.`;
        }
        return `Restored: ${JSON.stringify(r)}`;
      }).join("\n");
      return {
        name: this.name,
        data: formattedResult
      };
    } catch (error) {
      return {
        name: this.name,
        data: `An unexpected error occurred during restore: ${error}`
      };
    }
  }
};
var ListCheckpointsCommand = class {
  name = "restore list";
  description = "Lists all available checkpoints.";
  async execute(context) {
    const { config: config2 } = context.agentContext;
    try {
      if (!config2.getCheckpointingEnabled()) {
        return {
          name: this.name,
          data: "Checkpointing is not enabled. Please enable it in your settings (`general.checkpointing.enabled: true`) to use /restore."
        };
      }
      const checkpointDir = config2.storage.getProjectTempCheckpointsDir();
      try {
        await fs11.mkdir(checkpointDir, { recursive: true });
      } catch {
      }
      const files = await fs11.readdir(checkpointDir);
      const jsonFiles = files.filter((file) => file.endsWith(".json"));
      if (jsonFiles.length === 0) {
        return { name: this.name, data: "No checkpoints found." };
      }
      const checkpointFiles = /* @__PURE__ */ new Map();
      for (const file of jsonFiles) {
        const filePath = path11.join(checkpointDir, file);
        const data = await fs11.readFile(filePath, "utf-8");
        checkpointFiles.set(file, data);
      }
      const checkpointInfoList = getCheckpointInfoList(checkpointFiles);
      const formatted = checkpointInfoList.map((info) => {
        const i = info;
        const fileName = String(i["fileName"] || "Unknown");
        const toolName = String(i["toolName"] || "Unknown");
        const status = String(i["status"] || "Unknown");
        const timestamp = new Date(
          Number(i["timestamp"]) || 0
        ).toLocaleString();
        return `- **${fileName}**: ${toolName} (Status: ${status}) [${timestamp}]`;
      }).join("\n");
      return {
        name: this.name,
        data: `Available Checkpoints:
${formatted}`
      };
    } catch {
      return {
        name: this.name,
        data: "An unexpected error occurred while listing checkpoints."
      };
    }
  }
};

// packages/cli/src/acp/commands/about.ts
import process6 from "node:process";
var AboutCommand = class {
  name = "about";
  description = "Show version and environment info";
  async execute(context, _args = []) {
    const osVersion = process6.platform;
    let sandboxEnv = "no sandbox";
    if (process6.env["SANDBOX"] && process6.env["SANDBOX"] !== "sandbox-exec") {
      sandboxEnv = process6.env["SANDBOX"];
    } else if (process6.env["SANDBOX"] === "sandbox-exec") {
      sandboxEnv = `sandbox-exec (${process6.env["SEATBELT_PROFILE"] || "unknown"})`;
    }
    const modelVersion = context.agentContext.config.getModel() || "Unknown";
    const cliVersion = await getVersion();
    const selectedAuthType = context.settings.merged?.security?.auth?.selectedType ?? "";
    const gcpProject = process6.env["GOOGLE_CLOUD_PROJECT"] || "";
    const ideClient = await getIdeClientName(context);
    const userAccountManager = new UserAccountManager();
    const cachedAccount = userAccountManager.getCachedGoogleAccount();
    const userEmail = cachedAccount ?? "Unknown";
    const tier = context.agentContext.config.getUserTierName() || "Unknown";
    const info = [
      `- Version: ${cliVersion}`,
      `- OS: ${osVersion}`,
      `- Sandbox: ${sandboxEnv}`,
      `- Model: ${modelVersion}`,
      `- Auth Type: ${selectedAuthType}`,
      `- GCP Project: ${gcpProject}`,
      `- IDE Client: ${ideClient}`,
      `- User Email: ${userEmail}`,
      `- Tier: ${tier}`
    ].join("\n");
    return {
      name: this.name,
      data: `Gemini CLI Info:
${info}`
    };
  }
};
async function getIdeClientName(context) {
  if (!context.agentContext.config.getIdeMode()) {
    return "";
  }
  const ideClient = await IdeClient.getInstance();
  return ideClient?.getDetectedIdeDisplayName() ?? "";
}

// packages/cli/src/acp/commands/help.ts
var HelpCommand = class {
  constructor(registry2) {
    this.registry = registry2;
  }
  name = "help";
  description = "Show available commands";
  async execute(_context, _args = []) {
    const commands = this.registry.getAllCommands().sort((a, b) => a.name.localeCompare(b.name));
    const lines = [];
    lines.push("Gemini CLI Help:");
    lines.push("");
    lines.push("### Basics");
    lines.push(
      "- **Add context**: Use `@` to specify files for context (e.g., `@src/myFile.ts`) to target specific files or folders."
    );
    lines.push("");
    lines.push("### Commands");
    for (const cmd of commands) {
      if (cmd.description) {
        lines.push(`- **/${cmd.name}** - ${cmd.description}`);
      }
    }
    return {
      name: this.name,
      data: lines.join("\n")
    };
  }
};

// packages/cli/src/acp/acpCommandHandler.ts
var CommandHandler = class _CommandHandler {
  registry;
  constructor() {
    this.registry = _CommandHandler.createRegistry();
  }
  static createRegistry() {
    const registry2 = new CommandRegistry();
    registry2.register(new MemoryCommand());
    registry2.register(new ExtensionsCommand());
    registry2.register(new InitCommand());
    registry2.register(new RestoreCommand());
    registry2.register(new AboutCommand());
    registry2.register(new HelpCommand(registry2));
    return registry2;
  }
  getAvailableCommands() {
    return this.registry.getAllCommands().map((cmd) => ({
      name: cmd.name,
      description: cmd.description
    }));
  }
  /**
   * Parses and executes a command string if it matches a registered command.
   * Returns true if a command was handled, false otherwise.
   */
  async handleCommand(commandText, context) {
    const { commandToExecute, args } = this.parseSlashCommand(commandText);
    if (commandToExecute) {
      await this.runCommand(commandToExecute, args, context);
      return true;
    }
    return false;
  }
  async runCommand(commandToExecute, args, context) {
    try {
      const result = await commandToExecute.execute(
        context,
        args ? args.split(/\s+/) : []
      );
      let messageContent = "";
      if (typeof result.data === "string") {
        messageContent = result.data;
      } else if (typeof result.data === "object" && result.data !== null && "content" in result.data) {
        messageContent = result.data["content"];
      } else {
        messageContent = JSON.stringify(result.data, null, 2);
      }
      await context.sendMessage(messageContent);
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      await context.sendMessage(`Error: ${errorMessage}`);
    }
  }
  /**
   * Parses a raw slash command string into its matching headless command and arguments.
   * Mirrors `packages/cli/src/utils/commands.ts` logic.
   */
  parseSlashCommand(query) {
    const trimmed = query.trim();
    const parts = trimmed.substring(1).trim().split(/\s+/);
    const commandPath = parts.filter((p) => p);
    let currentCommands = this.registry.getAllCommands();
    let commandToExecute;
    let pathIndex = 0;
    for (const part of commandPath) {
      const foundCommand = currentCommands.find((cmd) => {
        const expectedName = commandPath.slice(0, pathIndex + 1).join(" ");
        return cmd.name === part || cmd.name === expectedName || cmd.aliases?.includes(part) || cmd.aliases?.includes(expectedName);
      });
      if (foundCommand) {
        commandToExecute = foundCommand;
        pathIndex++;
        if (foundCommand.subCommands) {
          currentCommands = foundCommand.subCommands;
        } else {
          break;
        }
      } else {
        break;
      }
    }
    const args = parts.slice(pathIndex).join(" ");
    return { commandToExecute, args };
  }
};

// packages/cli/src/acp/acpUtils.ts
function hasMeta(obj) {
  return typeof obj === "object" && obj !== null && "_meta" in obj;
}
var RequestPermissionResponseSchema = external_exports.object({
  outcome: external_exports.discriminatedUnion("outcome", [
    external_exports.object({ outcome: external_exports.literal("cancelled") }),
    external_exports.object({
      outcome: external_exports.literal("selected"),
      optionId: external_exports.string()
    })
  ])
});
function toToolCallContent(toolResult) {
  if (toolResult.error?.message) {
    throw new Error(toolResult.error.message);
  }
  if (toolResult.returnDisplay) {
    if (typeof toolResult.returnDisplay === "string") {
      return {
        type: "content",
        content: { type: "text", text: toolResult.returnDisplay }
      };
    } else {
      if ("fileName" in toolResult.returnDisplay) {
        return {
          type: "diff",
          path: toolResult.returnDisplay.filePath ?? toolResult.returnDisplay.fileName,
          oldText: toolResult.returnDisplay.originalContent,
          newText: toolResult.returnDisplay.newContent,
          _meta: {
            kind: !toolResult.returnDisplay.originalContent ? "add" : toolResult.returnDisplay.newContent === "" ? "delete" : "modify"
          }
        };
      }
      return null;
    }
  } else {
    return null;
  }
}
var basicPermissionOptions = [
  {
    optionId: "proceed_once" /* ProceedOnce */,
    name: "Allow",
    kind: "allow_once"
  },
  {
    optionId: "cancel" /* Cancel */,
    name: "Reject",
    kind: "reject_once"
  }
];
function toPermissionOptions(confirmation, config2, enablePermanentToolApproval = false) {
  const disableAlwaysAllow = config2.getDisableAlwaysAllow();
  const options = [];
  if (!disableAlwaysAllow) {
    switch (confirmation.type) {
      case "edit":
        options.push({
          optionId: "proceed_always" /* ProceedAlways */,
          name: "Allow for this session",
          kind: "allow_always"
        });
        if (enablePermanentToolApproval) {
          options.push({
            optionId: "proceed_always_and_save" /* ProceedAlwaysAndSave */,
            name: "Allow for this file in all future sessions",
            kind: "allow_always"
          });
        }
        break;
      case "exec":
        options.push({
          optionId: "proceed_always" /* ProceedAlways */,
          name: "Allow for this session",
          kind: "allow_always"
        });
        if (enablePermanentToolApproval) {
          options.push({
            optionId: "proceed_always_and_save" /* ProceedAlwaysAndSave */,
            name: "Allow this command for all future sessions",
            kind: "allow_always"
          });
        }
        break;
      case "mcp":
        options.push(
          {
            optionId: "proceed_always_server" /* ProceedAlwaysServer */,
            name: "Allow all server tools for this session",
            kind: "allow_always"
          },
          {
            optionId: "proceed_always_tool" /* ProceedAlwaysTool */,
            name: "Allow tool for this session",
            kind: "allow_always"
          }
        );
        if (enablePermanentToolApproval) {
          options.push({
            optionId: "proceed_always_and_save" /* ProceedAlwaysAndSave */,
            name: "Allow tool for all future sessions",
            kind: "allow_always"
          });
        }
        break;
      case "info":
        options.push({
          optionId: "proceed_always" /* ProceedAlways */,
          name: "Allow for this session",
          kind: "allow_always"
        });
        if (enablePermanentToolApproval) {
          options.push({
            optionId: "proceed_always_and_save" /* ProceedAlwaysAndSave */,
            name: "Allow for all future sessions",
            kind: "allow_always"
          });
        }
        break;
      case "ask_user":
      case "exit_plan_mode":
        break;
      default:
        break;
    }
  }
  options.push(...basicPermissionOptions);
  switch (confirmation.type) {
    case "edit":
    case "exec":
    case "mcp":
    case "info":
    case "ask_user":
    case "exit_plan_mode":
    case "sandbox_expansion":
      break;
    default: {
      const unreachable = confirmation;
      throw new Error(`Unexpected: ${unreachable}`);
    }
  }
  return options;
}
function toAcpToolKind(kind) {
  switch (kind) {
    case "read" /* Read */:
    case "edit" /* Edit */:
    case "execute" /* Execute */:
    case "search" /* Search */:
    case "delete" /* Delete */:
    case "move" /* Move */:
    case "think" /* Think */:
    case "fetch" /* Fetch */:
    case "switch_mode" /* SwitchMode */:
    case "other" /* Other */:
      return kind;
    case "agent" /* Agent */:
      return "think";
    case "plan" /* Plan */:
    case "communicate" /* Communicate */:
    default:
      return "other";
  }
}
function buildAvailableModes(isPlanEnabled) {
  const modes = [
    {
      id: "default" /* DEFAULT */,
      name: "Default",
      description: "Prompts for approval"
    },
    {
      id: "autoEdit" /* AUTO_EDIT */,
      name: "Auto Edit",
      description: "Auto-approves edit tools"
    },
    {
      id: "yolo" /* YOLO */,
      name: "YOLO",
      description: "Auto-approves all tools"
    }
  ];
  if (isPlanEnabled) {
    modes.push({
      id: "plan" /* PLAN */,
      name: "Plan",
      description: "Read-only mode"
    });
  }
  return modes;
}
function buildAvailableModels(config2, settings) {
  const preferredModel = config2.getModel() || GEMINI_MODEL_ALIAS_AUTO;
  const shouldShowPreviewModels = config2.getHasAccessToPreviewModel();
  const useGemini31 = config2.getGemini31LaunchedSync?.() ?? false;
  const useGemini3_5Flash = config2.hasGemini35FlashGAAccess?.() ?? false;
  const selectedAuthType = settings.merged.security.auth.selectedType;
  const useCustomToolModel = useGemini31 && selectedAuthType === "gemini-api-key" /* USE_GEMINI */;
  if (config2.getExperimentalDynamicModelConfiguration?.() === true && config2.getModelConfigService) {
    const options = config2.getModelConfigService().getAvailableModelOptions({
      useGemini3_1: useGemini31,
      useGemini3_5Flash,
      useCustomTools: useCustomToolModel,
      hasAccessToPreview: shouldShowPreviewModels
    });
    return {
      availableModels: options,
      currentModelId: preferredModel
    };
  }
  const mainOptions = [
    {
      value: GEMINI_MODEL_ALIAS_AUTO,
      title: getDisplayString(GEMINI_MODEL_ALIAS_AUTO),
      description: getAutoModelDescription(
        shouldShowPreviewModels,
        useGemini31,
        useGemini3_5Flash
      )
    }
  ];
  const manualOptions = [
    {
      value: DEFAULT_GEMINI_MODEL,
      title: getDisplayString(DEFAULT_GEMINI_MODEL)
    },
    {
      value: DEFAULT_GEMINI_FLASH_MODEL,
      title: getDisplayString(DEFAULT_GEMINI_FLASH_MODEL)
    },
    {
      value: DEFAULT_GEMINI_FLASH_LITE_MODEL,
      title: getDisplayString(DEFAULT_GEMINI_FLASH_LITE_MODEL)
    }
  ];
  if (shouldShowPreviewModels) {
    const previewProModel = useGemini31 ? PREVIEW_GEMINI_3_1_MODEL : PREVIEW_GEMINI_MODEL;
    const previewProValue = useCustomToolModel ? PREVIEW_GEMINI_3_1_CUSTOM_TOOLS_MODEL : previewProModel;
    const previewOptions = [
      {
        value: previewProValue,
        title: getDisplayString(previewProModel)
      },
      {
        value: PREVIEW_GEMINI_FLASH_MODEL,
        title: getDisplayString(PREVIEW_GEMINI_FLASH_MODEL)
      }
    ];
    if (PREVIEW_GEMINI_FLASH_LITE_MODEL !== "none") {
      previewOptions.push({
        value: PREVIEW_GEMINI_FLASH_LITE_MODEL,
        title: getDisplayString(PREVIEW_GEMINI_FLASH_LITE_MODEL)
      });
    }
    manualOptions.unshift(...previewOptions);
  }
  const scaleOptions = (options) => options.map((o) => ({
    modelId: o.value,
    name: o.title,
    description: o.description
  }));
  return {
    availableModels: [
      ...scaleOptions(mainOptions),
      ...scaleOptions(manualOptions)
    ],
    currentModelId: preferredModel
  };
}

// packages/cli/src/acp/acpSession.ts
var StructuredErrorSchema = external_exports.object({
  status: external_exports.number().optional(),
  message: external_exports.string().optional()
});
var Session = class {
  constructor(id, chat, context, connection, settings) {
    this.id = id;
    this.chat = chat;
    this.context = context;
    this.connection = connection;
    this.settings = settings;
    coreEvents.on(
      "approval-mode-changed" /* ApprovalModeChanged */,
      this.handleApprovalModeChanged
    );
    this.context.config.getMessageBus()?.subscribe(
      "tool-confirmation-request" /* TOOL_CONFIRMATION_REQUEST */,
      this.handleToolConfirmationRequest,
      { signal: this.disposeController.signal }
    );
  }
  pendingPrompt = null;
  commandHandler = new CommandHandler();
  callIdCounter = 0;
  disposeController = new AbortController();
  generateCallId(name) {
    return `${name}-${Date.now()}-${++this.callIdCounter}`;
  }
  handleToolConfirmationRequest = async (request) => {
    try {
      const policyEngine = this.context.config.getPolicyEngine?.();
      const messageBus = this.context.config.getMessageBus();
      if (!messageBus) {
        return;
      }
      if (!policyEngine) {
        debugLogger.warn(
          "Policy engine missing. Denying tool confirmation request."
        );
        await messageBus.publish({
          type: "tool-confirmation-response" /* TOOL_CONFIRMATION_RESPONSE */,
          correlationId: request.correlationId,
          confirmed: false,
          requiresUserConfirmation: false
        });
        return;
      }
      const toolName = request.toolCall.name?.trim();
      if (!toolName) {
        debugLogger.warn(
          "Tool confirmation request missing tool name. Denying."
        );
        await messageBus.publish({
          type: "tool-confirmation-response" /* TOOL_CONFIRMATION_RESPONSE */,
          correlationId: request.correlationId,
          confirmed: false,
          requiresUserConfirmation: false
        });
        return;
      }
      const tool = this.context.toolRegistry.getTool(toolName);
      if (!tool) {
        debugLogger.warn(
          `Tool confirmation request for unknown tool: ${toolName}. Denying.`
        );
        await messageBus.publish({
          type: "tool-confirmation-response" /* TOOL_CONFIRMATION_RESPONSE */,
          correlationId: request.correlationId,
          confirmed: false,
          requiresUserConfirmation: false
        });
        return;
      }
      const serverName = tool instanceof DiscoveredMCPTool ? tool.serverName : void 0;
      const toolAnnotations = tool.toolAnnotations;
      const result = await policyEngine.check(
        request.toolCall,
        serverName,
        toolAnnotations,
        request.subagent
      );
      await messageBus.publish({
        type: "tool-confirmation-response" /* TOOL_CONFIRMATION_RESPONSE */,
        correlationId: request.correlationId,
        confirmed: result.decision === "allow" /* ALLOW */,
        requiresUserConfirmation: result.decision === "ask_user" /* ASK_USER */
      });
    } catch (error) {
      debugLogger.error("Error handling tool confirmation request:", error);
      await this.context.config.getMessageBus()?.publish({
        type: "tool-confirmation-response" /* TOOL_CONFIRMATION_RESPONSE */,
        correlationId: request.correlationId,
        confirmed: false,
        requiresUserConfirmation: false
      });
    }
  };
  handleApprovalModeChanged = (payload) => {
    if (payload.sessionId === this.id) {
      void this.sendUpdate({
        sessionUpdate: "agent_message_chunk",
        content: {
          type: "text",
          text: `[MODE_UPDATE] ${payload.mode}`
        }
      });
    }
  };
  dispose() {
    coreEvents.off(
      "approval-mode-changed" /* ApprovalModeChanged */,
      this.handleApprovalModeChanged
    );
    this.disposeController.abort();
  }
  async cancelPendingPrompt() {
    if (!this.pendingPrompt) {
      throw new Error("Not currently generating");
    }
    this.pendingPrompt.abort();
    this.pendingPrompt = null;
  }
  setMode(modeId) {
    const availableModes = buildAvailableModes(
      this.context.config.isPlanEnabled()
    );
    const mode = availableModes.find((m) => m.id === modeId);
    if (!mode) {
      throw new Error(`Invalid or unavailable mode: ${modeId}`);
    }
    this.context.config.setApprovalMode(mode.id);
    return {};
  }
  getAvailableCommands() {
    return this.commandHandler.getAvailableCommands();
  }
  async sendAvailableCommands() {
    const availableCommands = this.getAvailableCommands().map((command2) => ({
      name: command2.name,
      description: command2.description
    }));
    await this.sendUpdate({
      sessionUpdate: "available_commands_update",
      availableCommands
    });
  }
  setModel(modelId) {
    this.context.config.setModel(modelId);
    return {};
  }
  async streamHistory(messages) {
    for (const msg of messages) {
      const contentString = partListUnionToString(msg.content);
      if (msg.type === "user") {
        if (contentString.trim()) {
          await this.sendUpdate({
            sessionUpdate: "user_message_chunk",
            content: { type: "text", text: contentString }
          });
        }
      } else if (msg.type === "gemini") {
        if (msg.thoughts) {
          for (const thought of msg.thoughts) {
            const thoughtText = `**${thought.subject}**
${thought.description}`;
            await this.sendUpdate({
              sessionUpdate: "agent_thought_chunk",
              content: { type: "text", text: thoughtText }
            });
          }
        }
        if (contentString.trim()) {
          await this.sendUpdate({
            sessionUpdate: "agent_message_chunk",
            content: { type: "text", text: contentString }
          });
        }
        if (msg.toolCalls) {
          for (const toolCall of msg.toolCalls) {
            const toolCallContent = [];
            if (toolCall.resultDisplay) {
              if (typeof toolCall.resultDisplay === "string") {
                toolCallContent.push({
                  type: "content",
                  content: { type: "text", text: toolCall.resultDisplay }
                });
              } else if ("fileName" in toolCall.resultDisplay) {
                toolCallContent.push({
                  type: "diff",
                  path: toolCall.resultDisplay.fileName,
                  oldText: toolCall.resultDisplay.originalContent,
                  newText: toolCall.resultDisplay.newContent
                });
              }
            }
            const tool = this.context.toolRegistry.getTool(toolCall.name);
            await this.sendUpdate({
              sessionUpdate: "tool_call",
              toolCallId: toolCall.id,
              status: toolCall.status === "success" /* Success */ ? "completed" : "failed",
              title: toolCall.displayName || toolCall.name,
              content: toolCallContent,
              kind: tool ? toAcpToolKind(tool.kind) : "other"
            });
          }
        }
      }
    }
  }
  async prompt(params) {
    this.pendingPrompt?.abort();
    const pendingSend = new AbortController();
    this.pendingPrompt = pendingSend;
    await this.context.config.waitForMcpInit();
    const promptId = Math.random().toString(16).slice(2);
    const parts = await this.#resolvePrompt(params.prompt, pendingSend.signal);
    let commandText = "";
    for (const part of parts) {
      if (typeof part === "object" && part !== null) {
        if (isTextPart(part)) {
          const text = part.text;
          commandText += text;
        } else {
          break;
        }
      }
    }
    commandText = commandText.trim();
    if (commandText && (commandText.startsWith("/") || commandText.startsWith("$"))) {
      const handled = await this.handleCommand(commandText, parts);
      if (handled) {
        return {
          stopReason: "end_turn",
          _meta: {
            quota: {
              token_count: { input_tokens: 0, output_tokens: 0 },
              model_usage: []
            }
          }
        };
      }
    }
    let totalInputTokens = 0;
    let totalOutputTokens = 0;
    const modelUsageMap = /* @__PURE__ */ new Map();
    let currentParts = parts;
    let turnCount = 0;
    const maxTurns = this.context.config.getMaxSessionTurns();
    while (true) {
      turnCount++;
      if (maxTurns >= 0 && turnCount > maxTurns) {
        return {
          stopReason: "max_turn_requests",
          _meta: {
            quota: {
              token_count: {
                input_tokens: totalInputTokens,
                output_tokens: totalOutputTokens
              },
              model_usage: Array.from(modelUsageMap.entries()).map(
                ([modelName, counts]) => ({
                  model: modelName,
                  token_count: {
                    input_tokens: counts.input,
                    output_tokens: counts.output
                  }
                })
              )
            }
          }
        };
      }
      if (pendingSend.signal.aborted) {
        return { stopReason: "cancelled" };
      }
      const toolCallRequests = [];
      let stopReason = "end_turn";
      let turnModelId = this.context.config.getModel();
      let turnInputTokens = 0;
      let turnOutputTokens = 0;
      try {
        const responseStream = this.context.geminiClient.sendMessageStream(
          currentParts,
          pendingSend.signal,
          promptId
        );
        for await (const event of responseStream) {
          if (pendingSend.signal.aborted) {
            return { stopReason: "cancelled" };
          }
          switch (event.type) {
            case "content" /* Content */: {
              const content = {
                type: "text",
                text: event.value
              };
              await this.sendUpdate({
                sessionUpdate: "agent_message_chunk",
                content
              });
              break;
            }
            case "thought" /* Thought */: {
              const thoughtText = `**${event.value.subject}**
${event.value.description}`;
              await this.sendUpdate({
                sessionUpdate: "agent_thought_chunk",
                content: { type: "text", text: thoughtText }
              });
              break;
            }
            case "tool_call_request" /* ToolCallRequest */:
              toolCallRequests.push(event.value);
              break;
            case "finished" /* Finished */: {
              const usage2 = event.value.usageMetadata;
              if (usage2) {
                turnInputTokens = usage2.promptTokenCount ?? turnInputTokens;
                turnOutputTokens = usage2.candidatesTokenCount ?? turnOutputTokens;
              }
              break;
            }
            case "model_info" /* ModelInfo */:
              turnModelId = event.value;
              break;
            case "max_session_turns" /* MaxSessionTurns */:
              stopReason = "max_turn_requests";
              break;
            case "loop_detected" /* LoopDetected */:
              stopReason = "max_turn_requests";
              break;
            case "context_window_will_overflow" /* ContextWindowWillOverflow */:
              stopReason = "max_tokens";
              break;
            case "error" /* Error */: {
              const parseResult = StructuredErrorSchema.safeParse(
                event.value.error
              );
              const errData = parseResult.success ? parseResult.data : {};
              throw new RequestError(
                errData.status ?? 500,
                errData.message ?? "Unknown stream execution error."
              );
            }
            default:
              break;
          }
        }
      } catch (error) {
        if (getErrorStatus(error) === 429) {
          throw new RequestError(
            429,
            "Rate limit exceeded. Try again later."
          );
        }
        if (pendingSend.signal.aborted || error instanceof Error && error.name === "AbortError") {
          return { stopReason: "cancelled" };
        }
        if (error instanceof RequestError) {
          throw error;
        }
        if (error instanceof InvalidStreamError || error && typeof error === "object" && "type" in error && (error.type === "NO_RESPONSE_TEXT" || error.type === "NO_FINISH_REASON" || error.type === "MALFORMED_FUNCTION_CALL" || error.type === "UNEXPECTED_TOOL_CALL")) {
          return {
            stopReason: "end_turn",
            _meta: {
              quota: {
                token_count: {
                  input_tokens: totalInputTokens,
                  output_tokens: totalOutputTokens
                },
                model_usage: Array.from(modelUsageMap.entries()).map(
                  ([modelName, counts]) => ({
                    model: modelName,
                    token_count: {
                      input_tokens: counts.input,
                      output_tokens: counts.output
                    }
                  })
                )
              }
            }
          };
        }
        throw new RequestError(
          getErrorStatus(error) || 500,
          getAcpErrorMessage(error)
        );
      }
      totalInputTokens += turnInputTokens;
      totalOutputTokens += turnOutputTokens;
      if (turnInputTokens > 0 || turnOutputTokens > 0) {
        const existing = modelUsageMap.get(turnModelId) ?? {
          input: 0,
          output: 0
        };
        existing.input += turnInputTokens;
        existing.output += turnOutputTokens;
        modelUsageMap.set(turnModelId, existing);
      }
      if (stopReason !== "end_turn") {
        return {
          stopReason,
          _meta: {
            quota: {
              token_count: {
                input_tokens: totalInputTokens,
                output_tokens: totalOutputTokens
              },
              model_usage: Array.from(modelUsageMap.entries()).map(
                ([modelName, counts]) => ({
                  model: modelName,
                  token_count: {
                    input_tokens: counts.input,
                    output_tokens: counts.output
                  }
                })
              )
            }
          }
        };
      }
      if (toolCallRequests.length === 0) {
        break;
      }
      const toolResponseParts = [];
      for (const tReq of toolCallRequests) {
        const fc = {
          id: tReq.callId,
          name: tReq.name,
          args: tReq.args
        };
        const response = await this.runTool(pendingSend.signal, promptId, fc);
        toolResponseParts.push(...response);
      }
      currentParts = toolResponseParts;
    }
    const modelUsageArray = Array.from(modelUsageMap.entries()).map(
      ([modelName, counts]) => ({
        model: modelName,
        token_count: {
          input_tokens: counts.input,
          output_tokens: counts.output
        }
      })
    );
    return {
      stopReason: "end_turn",
      _meta: {
        quota: {
          token_count: {
            input_tokens: totalInputTokens,
            output_tokens: totalOutputTokens
          },
          model_usage: modelUsageArray
        }
      }
    };
  }
  async handleCommand(commandText, parts) {
    const gitService = await this.context.config.getGitService();
    const commandContext = {
      agentContext: this.context,
      settings: this.settings,
      git: gitService,
      sendMessage: async (text) => {
        await this.sendUpdate({
          sessionUpdate: "agent_message_chunk",
          content: { type: "text", text }
        });
      }
    };
    return this.commandHandler.handleCommand(commandText, commandContext);
  }
  async sendUpdate(update) {
    const params = {
      sessionId: this.id,
      update
    };
    await this.connection.sessionUpdate(params);
  }
  async runTool(abortSignal, promptId, fc) {
    const callId = fc.id ?? this.generateCallId(fc.name || "unknown");
    const args = fc.args ?? {};
    const startTime = Date.now();
    const errorResponse = (error) => {
      const durationMs = Date.now() - startTime;
      logToolCall(
        this.context.config,
        new ToolCallEvent(
          void 0,
          fc.name ?? "",
          args,
          durationMs,
          false,
          promptId,
          typeof tool !== "undefined" && tool instanceof DiscoveredMCPTool ? "mcp" : "native",
          error.message
        )
      );
      return [
        {
          functionResponse: {
            id: callId,
            name: fc.name ?? "",
            response: { error: error.message }
          }
        }
      ];
    };
    if (!fc.name) {
      return errorResponse(new Error("Missing function name"));
    }
    const toolRegistry = this.context.toolRegistry;
    const tool = toolRegistry.getTool(fc.name);
    if (!tool) {
      return errorResponse(
        new Error(`Tool "${fc.name}" not found in registry.`)
      );
    }
    try {
      const invocation = tool.build(args);
      const displayTitle = typeof invocation.getDisplayTitle === "function" ? invocation.getDisplayTitle() : invocation.getDescription();
      const explanation = typeof invocation.getExplanation === "function" ? invocation.getExplanation() : "";
      const confirmationDetails = await invocation.shouldConfirmExecute(abortSignal);
      if (confirmationDetails) {
        const content2 = [];
        if (confirmationDetails.type === "edit") {
          content2.push({
            type: "diff",
            path: confirmationDetails.filePath,
            oldText: confirmationDetails.originalContent,
            newText: confirmationDetails.newContent,
            _meta: {
              kind: !confirmationDetails.originalContent ? "add" : confirmationDetails.newContent === "" ? "delete" : "modify"
            }
          });
        }
        if (content2.length === 0 && explanation) {
          content2.push({
            type: "content",
            content: { type: "text", text: explanation }
          });
        }
        const params = {
          sessionId: this.id,
          options: toPermissionOptions(
            confirmationDetails,
            this.context.config,
            this.settings.merged.security.enablePermanentToolApproval
          ),
          toolCall: {
            toolCallId: callId,
            status: "pending",
            title: displayTitle,
            content: content2,
            locations: invocation.toolLocations(),
            kind: toAcpToolKind(tool.kind)
          }
        };
        const output = RequestPermissionResponseSchema.parse(
          await this.connection.requestPermission(params)
        );
        const outcome = output.outcome.outcome === "cancelled" ? "cancel" /* Cancel */ : external_exports.nativeEnum(ToolConfirmationOutcome).parse(output.outcome.optionId);
        await confirmationDetails.onConfirm(outcome);
        await updatePolicy(
          tool,
          outcome,
          confirmationDetails,
          this.context,
          this.context.messageBus,
          invocation
        );
        switch (outcome) {
          case "cancel" /* Cancel */:
            return errorResponse(
              new Error(`Tool "${fc.name}" was canceled by the user.`)
            );
          case "proceed_once" /* ProceedOnce */:
          case "proceed_always" /* ProceedAlways */:
          case "proceed_always_and_save" /* ProceedAlwaysAndSave */:
          case "proceed_always_server" /* ProceedAlwaysServer */:
          case "proceed_always_tool" /* ProceedAlwaysTool */:
          case "modify_with_editor" /* ModifyWithEditor */:
            break;
          default: {
            const resultOutcome = outcome;
            throw new Error(`Unexpected: ${resultOutcome}`);
          }
        }
      } else {
        const content2 = [];
        if (explanation) {
          content2.push({
            type: "content",
            content: { type: "text", text: explanation }
          });
        }
        await this.sendUpdate({
          sessionUpdate: "tool_call",
          toolCallId: callId,
          status: "in_progress",
          title: displayTitle,
          content: content2,
          locations: invocation.toolLocations(),
          kind: toAcpToolKind(tool.kind)
        });
      }
      const toolResult = await invocation.execute({
        abortSignal
      });
      const content = toToolCallContent(toolResult);
      const updateContent = content ? [content] : [];
      await this.sendUpdate({
        sessionUpdate: "tool_call_update",
        toolCallId: callId,
        status: "completed",
        title: displayTitle,
        content: updateContent,
        locations: invocation.toolLocations(),
        kind: toAcpToolKind(tool.kind)
      });
      const durationMs = Date.now() - startTime;
      logToolCall(
        this.context.config,
        new ToolCallEvent(
          void 0,
          fc.name ?? "",
          args,
          durationMs,
          true,
          promptId,
          typeof tool !== "undefined" && tool instanceof DiscoveredMCPTool ? "mcp" : "native"
        )
      );
      this.chat.recordCompletedToolCalls(this.context.config.getActiveModel(), [
        {
          status: "success" /* Success */,
          request: {
            callId,
            name: fc.name,
            args,
            isClientInitiated: false,
            prompt_id: promptId
          },
          tool,
          invocation,
          response: {
            callId,
            responseParts: convertToFunctionResponse(
              fc.name,
              callId,
              toolResult.llmContent,
              this.context.config.getActiveModel(),
              this.context.config
            ),
            resultDisplay: toolResult.returnDisplay,
            error: void 0,
            errorType: void 0
          }
        }
      ]);
      return convertToFunctionResponse(
        fc.name,
        callId,
        toolResult.llmContent,
        this.context.config.getActiveModel(),
        this.context.config
      );
    } catch (e) {
      const error = e instanceof Error ? e : new Error(String(e));
      await this.sendUpdate({
        sessionUpdate: "tool_call_update",
        toolCallId: callId,
        status: "failed",
        content: [
          { type: "content", content: { type: "text", text: error.message } }
        ],
        kind: toAcpToolKind(tool.kind)
      });
      this.chat.recordCompletedToolCalls(this.context.config.getActiveModel(), [
        {
          status: "error" /* Error */,
          request: {
            callId,
            name: fc.name,
            args,
            isClientInitiated: false,
            prompt_id: promptId
          },
          tool,
          response: {
            callId,
            responseParts: [
              {
                functionResponse: {
                  id: callId,
                  name: fc.name ?? "",
                  response: { error: error.message }
                }
              }
            ],
            resultDisplay: error.message,
            error,
            errorType: void 0
          }
        }
      ]);
      return errorResponse(error);
    }
  }
  async #resolvePrompt(message, abortSignal) {
    const FILE_URI_SCHEME = "file://";
    const embeddedContext = [];
    const parts = message.map((part) => {
      switch (part.type) {
        case "text":
          return { text: part.text };
        case "image":
        case "audio":
          return {
            inlineData: {
              mimeType: part.mimeType,
              data: part.data
            }
          };
        case "resource_link": {
          if (part.uri.startsWith(FILE_URI_SCHEME)) {
            return {
              fileData: {
                mimeData: part.mimeType,
                name: part.name,
                fileUri: part.uri.slice(FILE_URI_SCHEME.length)
              }
            };
          } else {
            return { text: `@${part.uri}` };
          }
        }
        case "resource": {
          embeddedContext.push(part.resource);
          return { text: `@${part.resource.uri}` };
        }
        default: {
          const unreachable = part;
          throw new Error(`Unexpected chunk type: '${unreachable}'`);
        }
      }
    });
    const atPathCommandParts = parts.filter((part) => "fileData" in part);
    if (atPathCommandParts.length === 0 && embeddedContext.length === 0) {
      return parts;
    }
    const atPathToResolvedSpecMap = /* @__PURE__ */ new Map();
    const fileDiscovery = this.context.config.getFileService();
    const fileFilteringOptions = this.context.config.getFileFilteringOptions();
    const pathSpecsToRead = [];
    const contentLabelsForDisplay = [];
    const ignoredPaths = [];
    const directContents = [];
    const toolRegistry = this.context.toolRegistry;
    const readManyFilesTool = new ReadManyFilesTool(
      this.context.config,
      this.context.messageBus
    );
    const globTool = toolRegistry.getTool("glob");
    if (!readManyFilesTool) {
      throw new Error("Error: read_many_files tool not found.");
    }
    for (const atPathPart of atPathCommandParts) {
      const pathName = atPathPart.fileData.fileUri;
      if (fileDiscovery.shouldIgnoreFile(pathName, fileFilteringOptions)) {
        ignoredPaths.push(pathName);
        debugLogger.warn(`Path ${pathName} is ignored and will be skipped.`);
        continue;
      }
      let currentPathSpec = pathName;
      let resolvedSuccessfully = false;
      let readDirectly = false;
      const result = await resolveAtCommandPath(
        pathName,
        this.context.config,
        (msg) => this.debug(msg)
      );
      let validationError = null;
      let absolutePath;
      let resolved;
      if (result.status === "resolved") {
        resolved = result.resolved;
        absolutePath = resolved.absolutePath;
      } else if (result.status === "unauthorized") {
        absolutePath = result.absolutePath;
        validationError = result.error;
      } else if (result.status === "invalid") {
        continue;
      } else {
        absolutePath = path12.resolve(
          this.context.config.getTargetDir(),
          pathName
        );
      }
      if (!resolved && validationError && !isWithinRoot(absolutePath, this.context.config.getTargetDir())) {
        try {
          const stats = await fs12.stat(absolutePath);
          if (stats.isFile()) {
            const syntheticCallId = `resolve-prompt-${pathName}-${randomUUID()}`;
            const params = {
              sessionId: this.id,
              options: [
                {
                  optionId: "proceed_once" /* ProceedOnce */,
                  name: "Allow once",
                  kind: "allow_once"
                },
                {
                  optionId: "cancel" /* Cancel */,
                  name: "Deny",
                  kind: "reject_once"
                }
              ],
              toolCall: {
                toolCallId: syntheticCallId,
                status: "pending",
                title: `Allow access to absolute path: ${pathName}`,
                content: [
                  {
                    type: "content",
                    content: {
                      type: "text",
                      text: `The Agent needs access to read an attached file outside your workspace: ${pathName}`
                    }
                  }
                ],
                locations: [],
                kind: "read"
              }
            };
            const output = RequestPermissionResponseSchema.parse(
              await this.connection.requestPermission(params)
            );
            const outcome = output.outcome.outcome === "cancelled" ? "cancel" /* Cancel */ : external_exports.nativeEnum(ToolConfirmationOutcome).parse(output.outcome.optionId);
            if (outcome === "proceed_once" /* ProceedOnce */) {
              this.context.config.getWorkspaceContext().addReadOnlyPath(absolutePath);
              validationError = null;
            } else {
              this.debug(
                `Direct read authorization denied for absolute path ${pathName}`
              );
              directContents.push({
                spec: pathName,
                content: `[Warning: Access to absolute path \`${pathName}\` denied by user.]`
              });
              continue;
            }
          }
        } catch (error) {
          this.debug(
            `Failed to request permission for absolute attachment ${pathName}: ${getErrorMessage(error)}`
          );
          await this.sendUpdate({
            sessionUpdate: "agent_thought_chunk",
            content: {
              type: "text",
              text: `Warning: Failed to display permission dialog for \`${absolutePath}\`. Error: ${getErrorMessage(error)}`
            }
          });
        }
      }
      try {
        if (!validationError) {
          if ((path12.isAbsolute(pathName) || !isWithinRoot(
            absolutePath,
            this.context.config.getTargetDir()
          )) && !readDirectly) {
            try {
              const stats = resolved ? resolved.stats : await fs12.stat(absolutePath);
              if (stats.isFile()) {
                const fileReadResult = await processSingleFileContent(
                  absolutePath,
                  this.context.config.getTargetDir(),
                  this.context.config.getFileSystemService()
                );
                if (!fileReadResult.error) {
                  if (typeof fileReadResult.llmContent === "object" && "inlineData" in fileReadResult.llmContent) {
                    directContents.push({
                      spec: pathName,
                      part: fileReadResult.llmContent
                    });
                  } else if (typeof fileReadResult.llmContent === "string") {
                    let contentToPush = fileReadResult.llmContent;
                    if (fileReadResult.isTruncated) {
                      contentToPush = `[WARNING: This file was truncated]

${contentToPush}`;
                    }
                    directContents.push({
                      spec: pathName,
                      content: contentToPush
                    });
                  }
                  readDirectly = true;
                  resolvedSuccessfully = true;
                } else {
                  this.debug(
                    `Direct read failed for absolute path ${pathName}: ${fileReadResult.error}`
                  );
                  await this.sendUpdate({
                    sessionUpdate: "agent_thought_chunk",
                    content: {
                      type: "text",
                      text: `Warning: file read failed for \`${pathName}\`. Reason: ${fileReadResult.error}`
                    }
                  });
                  continue;
                }
              }
            } catch (error) {
              this.debug(
                `File stat/access error for absolute path ${pathName}: ${getErrorMessage(error)}`
              );
              await this.sendUpdate({
                sessionUpdate: "agent_thought_chunk",
                content: {
                  type: "text",
                  text: `Warning: file access failed for \`${pathName}\`. Reason: ${getErrorMessage(error)}`
                }
              });
              continue;
            }
          }
          if (!readDirectly) {
            const stats = resolved ? resolved.stats : await fs12.stat(absolutePath);
            if (stats.isDirectory()) {
              currentPathSpec = pathName.endsWith("/") ? `${pathName}**` : `${pathName}/**`;
              this.debug(
                `Path ${pathName} resolved to directory, using glob: ${currentPathSpec}`
              );
            } else {
              this.debug(
                `Path ${pathName} resolved to file: ${currentPathSpec}`
              );
            }
            resolvedSuccessfully = true;
          }
        } else {
          this.debug(
            `Path ${pathName} access disallowed: ${validationError}. Skipping.`
          );
          await this.sendUpdate({
            sessionUpdate: "agent_thought_chunk",
            content: {
              type: "text",
              text: `Warning: skipping access to \`${pathName}\`. Reason: ${validationError}`
            }
          });
        }
      } catch (error) {
        if (isNodeError(error) && error.code === "ENOENT") {
          if (this.context.config.getEnableRecursiveFileSearch() && globTool) {
            this.debug(
              `Path ${pathName} not found directly, attempting glob search.`
            );
            try {
              const globResult = await globTool.buildAndExecute(
                {
                  pattern: `**/*${pathName}*`,
                  path: this.context.config.getTargetDir()
                },
                abortSignal
              );
              if (globResult.llmContent && typeof globResult.llmContent === "string" && !globResult.llmContent.startsWith("No files found") && !globResult.llmContent.startsWith("Error:")) {
                const lines = globResult.llmContent.split("\n");
                if (lines.length > 1 && lines[1]) {
                  const firstMatchAbsolute = lines[1].trim();
                  currentPathSpec = path12.relative(
                    this.context.config.getTargetDir(),
                    firstMatchAbsolute
                  );
                  this.debug(
                    `Glob search for ${pathName} found ${firstMatchAbsolute}, using relative path: ${currentPathSpec}`
                  );
                  resolvedSuccessfully = true;
                } else {
                  this.debug(
                    `Glob search for '**/*${pathName}*' did not return a usable path. Path ${pathName} will be skipped.`
                  );
                }
              } else {
                this.debug(
                  `Glob search for '**/*${pathName}*' found no files or an error. Path ${pathName} will be skipped.`
                );
              }
            } catch (globError) {
              debugLogger.error(
                `Error during glob search for ${pathName}: ${getErrorMessage(globError)}`
              );
            }
          } else {
            this.debug(
              `Glob tool not found. Path ${pathName} will be skipped.`
            );
          }
        } else {
          debugLogger.error(
            `Error stating path ${pathName}. Path ${pathName} will be skipped.`
          );
        }
      }
      if (resolvedSuccessfully) {
        if (!readDirectly) {
          pathSpecsToRead.push(currentPathSpec);
        }
        atPathToResolvedSpecMap.set(pathName, currentPathSpec);
        contentLabelsForDisplay.push(pathName);
      }
    }
    let initialQueryText = "";
    for (let i = 0; i < parts.length; i++) {
      const chunk = parts[i];
      if ("text" in chunk) {
        initialQueryText += chunk.text;
      } else {
        const resolvedSpec = chunk.fileData && atPathToResolvedSpecMap.get(chunk.fileData.fileUri);
        if (i > 0 && initialQueryText.length > 0 && !initialQueryText.endsWith(" ") && resolvedSpec) {
          const prevPart = parts[i - 1];
          if ("text" in prevPart || "fileData" in prevPart && atPathToResolvedSpecMap.has(prevPart.fileData.fileUri)) {
            initialQueryText += " ";
          }
        }
        if (resolvedSpec) {
          initialQueryText += `@${resolvedSpec}`;
        } else {
          if (i > 0 && initialQueryText.length > 0 && !initialQueryText.endsWith(" ") && !chunk.fileData?.fileUri.startsWith(" ")) {
            initialQueryText += " ";
          }
          if (chunk.fileData?.fileUri) {
            initialQueryText += `@${chunk.fileData.fileUri}`;
          }
        }
      }
    }
    initialQueryText = initialQueryText.trim();
    if (ignoredPaths.length > 0) {
      this.debug(
        `Ignored ${ignoredPaths.length} files: ${ignoredPaths.join(", ")}`
      );
    }
    const processedQueryParts = [{ text: initialQueryText }];
    if (pathSpecsToRead.length === 0 && embeddedContext.length === 0 && directContents.length === 0) {
      debugLogger.warn("No valid file paths found in @ commands to read.");
      return [{ text: initialQueryText }];
    }
    if (pathSpecsToRead.length > 0) {
      const toolArgs = {
        include: pathSpecsToRead
      };
      const callId = this.generateCallId(readManyFilesTool.name);
      try {
        const invocation = readManyFilesTool.build(toolArgs);
        await this.sendUpdate({
          sessionUpdate: "tool_call",
          toolCallId: callId,
          status: "in_progress",
          title: invocation.getDescription(),
          content: [],
          locations: invocation.toolLocations(),
          kind: toAcpToolKind(readManyFilesTool.kind)
        });
        const result = await invocation.execute({ abortSignal });
        const content = toToolCallContent(result) || {
          type: "content",
          content: {
            type: "text",
            text: `Successfully read: ${contentLabelsForDisplay.join(", ")}`
          }
        };
        await this.sendUpdate({
          sessionUpdate: "tool_call_update",
          toolCallId: callId,
          status: "completed",
          title: invocation.getDescription(),
          content: content ? [content] : [],
          locations: invocation.toolLocations(),
          kind: toAcpToolKind(readManyFilesTool.kind)
        });
        if (Array.isArray(result.llmContent)) {
          const fileContentRegex = /^--- (.*?) ---\n\n([\s\S]*?)\n\n$/;
          processedQueryParts.push({
            text: `
${REFERENCE_CONTENT_START}`
          });
          for (const part of result.llmContent) {
            if (typeof part === "string") {
              const match = fileContentRegex.exec(part);
              if (match) {
                const filePathSpecInContent = match[1];
                const fileActualContent = match[2].trim();
                processedQueryParts.push({
                  text: `
Content from @${filePathSpecInContent}:
`
                });
                processedQueryParts.push({ text: fileActualContent });
              } else {
                processedQueryParts.push({ text: part });
              }
            } else {
              processedQueryParts.push(part);
            }
          }
        } else {
          debugLogger.warn(
            "read_many_files tool returned no content or empty content."
          );
        }
      } catch (error) {
        await this.sendUpdate({
          sessionUpdate: "tool_call_update",
          toolCallId: callId,
          status: "failed",
          content: [
            {
              type: "content",
              content: {
                type: "text",
                text: `Error reading files (${contentLabelsForDisplay.join(", ")}): ${getErrorMessage(error)}`
              }
            }
          ],
          kind: toAcpToolKind(readManyFilesTool.kind)
        });
        throw error;
      }
    }
    if (directContents.length > 0) {
      const hasReferenceStart = processedQueryParts.some(
        (p) => "text" in p && typeof p.text === "string" && p.text.includes(REFERENCE_CONTENT_START)
      );
      if (!hasReferenceStart) {
        processedQueryParts.push({
          text: `
${REFERENCE_CONTENT_START}`
        });
      }
      for (const item of directContents) {
        processedQueryParts.push({
          text: `
Content from @${item.spec}:
`
        });
        if (item.content) {
          processedQueryParts.push({ text: item.content });
        } else if (item.part) {
          processedQueryParts.push(item.part);
        }
      }
    }
    if (embeddedContext.length > 0) {
      processedQueryParts.push({
        text: "\n--- Content from referenced context ---"
      });
      for (const contextPart of embeddedContext) {
        processedQueryParts.push({
          text: `
Content from @${contextPart.uri}:
`
        });
        if ("text" in contextPart) {
          processedQueryParts.push({
            text: contextPart.text
          });
        } else {
          processedQueryParts.push({
            inlineData: {
              mimeType: contextPart.mimeType ?? "application/octet-stream",
              data: contextPart.blob
            }
          });
        }
      }
    }
    return processedQueryParts;
  }
  debug(msg) {
    if (this.context.config.getDebugMode()) {
      debugLogger.warn(msg);
    }
  }
};

// packages/cli/src/acp/acpFileSystemService.ts
import os5 from "node:os";
import path13 from "node:path";
var AcpFileSystemService = class {
  constructor(connection, sessionId, capabilities, fallback, root) {
    this.connection = connection;
    this.sessionId = sessionId;
    this.capabilities = capabilities;
    this.fallback = fallback;
    this.root = root;
  }
  geminiDir = path13.join(os5.homedir(), ".gemini");
  shouldUseFallback(filePath) {
    return !isWithinRoot(filePath, this.root) || isWithinRoot(filePath, this.geminiDir);
  }
  normalizeFileSystemError(err) {
    const errorMessage = err instanceof Error ? err.message : String(err);
    if (errorMessage.includes("Resource not found") || errorMessage.includes("ENOENT") || errorMessage.includes("does not exist") || errorMessage.includes("No such file")) {
      const newErr = new Error(errorMessage);
      newErr.code = "ENOENT";
      throw newErr;
    }
    throw err;
  }
  async readTextFile(filePath) {
    if (!this.capabilities.readTextFile || this.shouldUseFallback(filePath)) {
      return this.fallback.readTextFile(filePath);
    }
    try {
      const response = await this.connection.readTextFile({
        path: filePath,
        sessionId: this.sessionId
      });
      const content = response.content;
      if (typeof content !== "string") {
        throw new Error("content must be a string");
      }
      return content;
    } catch (err) {
      this.normalizeFileSystemError(err);
    }
  }
  async writeTextFile(filePath, content) {
    if (!this.capabilities.writeTextFile || this.shouldUseFallback(filePath)) {
      return this.fallback.writeTextFile(filePath, content);
    }
    try {
      await this.connection.writeTextFile({
        path: filePath,
        content,
        sessionId: this.sessionId
      });
    } catch (err) {
      this.normalizeFileSystemError(err);
    }
  }
};

// packages/cli/src/acp/acpSessionManager.ts
var AcpSessionManager = class {
  constructor(settings, argv, connection) {
    this.settings = settings;
    this.argv = argv;
    this.connection = connection;
  }
  sessions = /* @__PURE__ */ new Map();
  clientCapabilities;
  setClientCapabilities(capabilities) {
    this.clientCapabilities = capabilities;
  }
  getSession(sessionId) {
    return this.sessions.get(sessionId);
  }
  dispose() {
    for (const session of this.sessions.values()) {
      session.dispose();
    }
    this.sessions.clear();
  }
  async newSession({ cwd, mcpServers }, authDetails) {
    const sessionId = randomUUID2();
    const loadedSettings = loadSettings(cwd);
    const config2 = await this.newSessionConfig(
      sessionId,
      cwd,
      mcpServers,
      loadedSettings
    );
    const authType = loadedSettings.merged.security.auth.selectedType || (authDetails.baseUrl || process.env["GOOGLE_GEMINI_BASE_URL"] ? "gateway" /* GATEWAY */ : "gemini-api-key" /* USE_GEMINI */);
    let isAuthenticated = false;
    let authErrorMessage = "";
    try {
      await config2.refreshAuth(
        authType,
        authDetails.apiKey,
        authDetails.baseUrl,
        authDetails.customHeaders
      );
      isAuthenticated = true;
      const contentGeneratorConfig = config2.getContentGeneratorConfig();
      if (authType === "gemini-api-key" /* USE_GEMINI */ && (!contentGeneratorConfig || !contentGeneratorConfig.apiKey)) {
        isAuthenticated = false;
        authErrorMessage = "Gemini API key is missing or not configured.";
      }
    } catch (e) {
      isAuthenticated = false;
      authErrorMessage = getAcpErrorMessage(e);
      debugLogger.error(
        `Authentication failed: ${e instanceof Error ? e.stack : e}`
      );
    }
    if (!isAuthenticated) {
      throw new RequestError(
        -32e3,
        authErrorMessage || "Authentication required."
      );
    }
    if (this.clientCapabilities?.fs) {
      const acpFileSystemService = new AcpFileSystemService(
        this.connection,
        sessionId,
        this.clientCapabilities.fs,
        config2.getFileSystemService(),
        cwd
      );
      config2.setFileSystemService(acpFileSystemService);
    }
    await config2.initialize();
    startupProfiler.flush(config2);
    startAutoMemoryIfEnabled(config2);
    const geminiClient = config2.getGeminiClient();
    const chat = await geminiClient.startChat();
    const session = new Session(
      sessionId,
      chat,
      config2,
      this.connection,
      this.settings
    );
    this.sessions.set(sessionId, session);
    setTimeout(() => {
      session.sendAvailableCommands();
    }, 0);
    const { availableModels, currentModelId } = buildAvailableModels(
      config2,
      loadedSettings
    );
    const response = {
      sessionId,
      modes: {
        availableModes: buildAvailableModes(config2.isPlanEnabled()),
        currentModeId: config2.getApprovalMode()
      },
      models: {
        availableModels,
        currentModelId
      }
    };
    return response;
  }
  async loadSession({ sessionId, cwd, mcpServers }, authDetails) {
    const config2 = await this.initializeSessionConfig(
      sessionId,
      cwd,
      mcpServers,
      authDetails
    );
    const sessionSelector = new SessionSelector(config2.storage);
    const { sessionData, sessionPath } = await sessionSelector.resolveSession(sessionId);
    const clientHistory = convertSessionToClientHistory(sessionData.messages);
    const geminiClient = config2.getGeminiClient();
    await geminiClient.initialize();
    await geminiClient.resumeChat(clientHistory, {
      conversation: sessionData,
      filePath: sessionPath
    });
    const session = new Session(
      sessionId,
      geminiClient.getChat(),
      config2,
      this.connection,
      this.settings
    );
    const existingSession = this.sessions.get(sessionId);
    if (existingSession) {
      existingSession.dispose();
    }
    this.sessions.set(sessionId, session);
    session.streamHistory(sessionData.messages);
    setTimeout(() => {
      session.sendAvailableCommands();
    }, 0);
    const { availableModels, currentModelId } = buildAvailableModels(
      config2,
      this.settings
    );
    const response = {
      modes: {
        availableModes: buildAvailableModes(config2.isPlanEnabled()),
        currentModeId: config2.getApprovalMode()
      },
      models: {
        availableModels,
        currentModelId
      }
    };
    return response;
  }
  async initializeSessionConfig(sessionId, cwd, mcpServers, authDetails) {
    const selectedAuthType = this.settings.merged.security.auth.selectedType || (authDetails.baseUrl || process.env["GOOGLE_GEMINI_BASE_URL"] ? "gateway" /* GATEWAY */ : void 0);
    if (!selectedAuthType) {
      throw RequestError.authRequired();
    }
    const config2 = await this.newSessionConfig(sessionId, cwd, mcpServers);
    try {
      await config2.refreshAuth(
        selectedAuthType,
        authDetails.apiKey,
        authDetails.baseUrl,
        authDetails.customHeaders
      );
    } catch (e) {
      debugLogger.error(`Authentication failed: ${e}`);
      throw RequestError.authRequired();
    }
    if (this.clientCapabilities?.fs) {
      const acpFileSystemService = new AcpFileSystemService(
        this.connection,
        sessionId,
        this.clientCapabilities.fs,
        config2.getFileSystemService(),
        cwd
      );
      config2.setFileSystemService(acpFileSystemService);
    }
    await config2.initialize();
    startupProfiler.flush(config2);
    startAutoMemoryIfEnabled(config2);
    return config2;
  }
  async newSessionConfig(sessionId, cwd, mcpServers, loadedSettings) {
    const currentSettings = loadedSettings || this.settings;
    const mergedMcpServers = { ...currentSettings.merged.mcpServers };
    for (const server of mcpServers) {
      if ("type" in server && (server.type === "sse" || server.type === "http")) {
        const headers = Object.fromEntries(
          server.headers.map(({ name, value }) => [name, value])
        );
        mergedMcpServers[server.name] = new MCPServerConfig(
          void 0,
          // command
          void 0,
          // args
          void 0,
          // env
          void 0,
          // cwd
          server.type === "sse" ? server.url : void 0,
          // url (sse)
          server.type === "http" ? server.url : void 0,
          // httpUrl
          headers
        );
      } else if ("command" in server) {
        const env2 = {};
        for (const { name: envName, value } of server.env) {
          env2[envName] = value;
        }
        mergedMcpServers[server.name] = new MCPServerConfig(
          server.command,
          server.args,
          env2,
          cwd
        );
      }
    }
    const settings = {
      ...currentSettings.merged,
      mcpServers: mergedMcpServers
    };
    const config2 = await loadCliConfig(settings, sessionId, this.argv, { cwd });
    createPolicyUpdater(
      config2.getPolicyEngine(),
      config2.messageBus,
      config2.storage
    );
    return config2;
  }
};

// packages/cli/src/acp/acpRpcDispatcher.ts
var GeminiAgent = class {
  constructor(context, settings, argv, connection) {
    this.context = context;
    this.settings = settings;
    this.sessionManager = new AcpSessionManager(settings, argv, connection);
  }
  apiKey;
  baseUrl;
  customHeaders;
  sessionManager;
  dispose() {
    this.sessionManager.dispose();
  }
  async initialize(args) {
    if (args.clientCapabilities) {
      this.sessionManager.setClientCapabilities(args.clientCapabilities);
    }
    const authMethods = [
      {
        id: "oauth-personal" /* LOGIN_WITH_GOOGLE */,
        name: "Log in with Google",
        description: "Log in with your Google account"
      },
      {
        id: "gemini-api-key" /* USE_GEMINI */,
        name: "Gemini API key",
        description: "Use an API key with Gemini Developer API",
        _meta: {
          "api-key": {
            provider: "google"
          }
        }
      },
      {
        id: "vertex-ai" /* USE_VERTEX_AI */,
        name: "Vertex AI",
        description: "Use an API key with Vertex AI GenAI API"
      },
      {
        id: "gateway" /* GATEWAY */,
        name: "AI API Gateway",
        description: "Use a custom AI API Gateway",
        _meta: {
          gateway: {
            protocol: "google",
            restartRequired: "false"
          }
        }
      }
    ];
    await this.context.config.initialize();
    const version2 = await getVersion();
    return {
      protocolVersion: PROTOCOL_VERSION,
      authMethods,
      agentInfo: {
        name: "gemini-cli",
        title: "Gemini CLI",
        version: version2
      },
      agentCapabilities: {
        loadSession: true,
        promptCapabilities: {
          image: true,
          audio: true,
          embeddedContext: true
        },
        mcpCapabilities: {
          http: true,
          sse: true
        }
      }
    };
  }
  async authenticate(req) {
    const { methodId } = req;
    const method = external_exports.nativeEnum(AuthType).parse(methodId);
    const selectedAuthType = this.settings.merged.security.auth.selectedType;
    if (selectedAuthType && selectedAuthType !== method) {
      await clearCachedCredentialFile();
    }
    const meta2 = hasMeta(req) ? req._meta : void 0;
    const apiKey = typeof meta2?.["api-key"] === "string" ? meta2["api-key"] : void 0;
    try {
      if (apiKey) {
        this.apiKey = apiKey;
      }
      const gatewaySchema = external_exports.object({
        baseUrl: external_exports.string().optional(),
        headers: external_exports.record(external_exports.string()).optional()
      });
      let baseUrl;
      let headers;
      if (meta2?.["gateway"]) {
        const result = gatewaySchema.safeParse(meta2["gateway"]);
        if (result.success) {
          baseUrl = result.data.baseUrl;
          headers = result.data.headers;
        } else {
          throw new RequestError(
            -32602,
            `Malformed gateway payload: ${result.error.message}`
          );
        }
      }
      this.baseUrl = baseUrl;
      this.customHeaders = headers;
      await this.context.config.refreshAuth(
        method,
        apiKey ?? this.apiKey,
        baseUrl,
        headers
      );
    } catch (e) {
      throw new RequestError(-32e3, getAcpErrorMessage(e));
    }
    this.settings.setValue(
      "User" /* User */,
      "security.auth.selectedType",
      method
    );
  }
  getAuthDetails() {
    return {
      apiKey: this.apiKey,
      baseUrl: this.baseUrl,
      customHeaders: this.customHeaders
    };
  }
  async newSession(params) {
    return this.sessionManager.newSession(params, this.getAuthDetails());
  }
  async loadSession(params) {
    return this.sessionManager.loadSession(params, this.getAuthDetails());
  }
  async cancel(params) {
    const session = this.sessionManager.getSession(params.sessionId);
    if (!session) {
      throw new RequestError(
        -32602,
        `Session not found: ${params.sessionId}`
      );
    }
    await session.cancelPendingPrompt();
  }
  async prompt(params) {
    const session = this.sessionManager.getSession(params.sessionId);
    if (!session) {
      throw new RequestError(
        -32602,
        `Session not found: ${params.sessionId}`
      );
    }
    return session.prompt(params);
  }
  async setSessionMode(params) {
    const session = this.sessionManager.getSession(params.sessionId);
    if (!session) {
      throw new RequestError(
        -32602,
        `Session not found: ${params.sessionId}`
      );
    }
    return session.setMode(params.modeId);
  }
  async unstable_setSessionModel(params) {
    const session = this.sessionManager.getSession(params.sessionId);
    if (!session) {
      throw new RequestError(
        -32602,
        `Session not found: ${params.sessionId}`
      );
    }
    return session.setModel(params.modelId);
  }
};

// packages/cli/src/acp/acpStdioTransport.ts
async function runAcpClient(config2, settings, argv) {
  const { stdout: workingStdout } = createWorkingStdio();
  const stdout = Writable.toWeb(workingStdout);
  const stdin = Readable.toWeb(process.stdin);
  const stream = ndJsonStream(stdout, stdin);
  const connection = new AgentSideConnection(
    (connection2) => new GeminiAgent(config2, settings, argv, connection2),
    stream
  );
  await connection.closed.finally(runExitCleanup);
}

// packages/cli/src/validateNonInterActiveAuth.ts
async function validateNonInteractiveAuth(configuredAuthType, useExternalAuth, nonInteractiveConfig, settings) {
  try {
    const effectiveAuthType = configuredAuthType || getAuthTypeFromEnv();
    const enforcedType = settings.merged.security.auth.enforcedType;
    if (enforcedType && effectiveAuthType !== enforcedType) {
      const message = effectiveAuthType ? `The enforced authentication type is '${enforcedType}', but the current type is '${effectiveAuthType}'. Please re-authenticate with the correct type.` : `The auth type '${enforcedType}' is enforced, but no authentication is configured.`;
      throw new Error(message);
    }
    if (!effectiveAuthType) {
      const message = `Please set an Auth method in your ${USER_SETTINGS_PATH} or specify one of the following environment variables before running: GEMINI_API_KEY, GOOGLE_GENAI_USE_VERTEXAI, GOOGLE_GENAI_USE_GCA`;
      throw new Error(message);
    }
    const authType = effectiveAuthType;
    if (!useExternalAuth) {
      const err = await validateAuthMethod(String(authType));
      if (err != null) {
        throw new Error(err);
      }
    }
    return authType;
  } catch (error) {
    if (nonInteractiveConfig.getOutputFormat() === "json" /* JSON */) {
      handleError(
        error instanceof Error ? error : new Error(String(error)),
        nonInteractiveConfig,
        ExitCodes.FATAL_AUTHENTICATION_ERROR
      );
    } else {
      debugLogger.error(error instanceof Error ? error.message : String(error));
      await runExitCleanup();
      process.exit(ExitCodes.FATAL_AUTHENTICATION_ERROR);
    }
  }
}

// packages/cli/src/utils/relaunch.ts
async function relaunchOnExitCode(runner) {
  while (true) {
    try {
      const exitCode = await runner();
      if (process.platform === "android" || exitCode !== RELAUNCH_EXIT_CODE) {
        process.exit(exitCode);
      }
    } catch (error) {
      process.stdin.resume();
      const errorMessage = error instanceof Error ? error.stack ?? error.message : String(error);
      writeToStderr(
        `Fatal error: Failed to relaunch the CLI process.
${errorMessage}
`
      );
      process.exit(1);
    }
  }
}

// packages/cli/src/utils/sessions.ts
async function listSessions(config2) {
  await generateSummary(config2);
  const sessionSelector = new SessionSelector(config2.storage);
  const sessions = await sessionSelector.listSessions();
  if (sessions.length === 0) {
    writeToStdout("No previous sessions found for this project.");
    return;
  }
  writeToStdout(
    `
Available sessions for this project (${sessions.length}):
`
  );
  sessions.sort(
    (a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime()
  ).forEach((session, index) => {
    const current = session.isCurrentSession ? ", current" : "";
    const time3 = formatRelativeTime(session.lastUpdated);
    const title = session.displayName.length > 100 ? session.displayName.slice(0, 97) + "..." : session.displayName;
    writeToStdout(
      `  ${index + 1}. ${title} (${time3}${current}) [${session.id}]
`
    );
  });
}
async function deleteSession(config2, sessionIndex) {
  const sessionSelector = new SessionSelector(config2.storage);
  const sessions = await sessionSelector.listSessions();
  if (sessions.length === 0) {
    writeToStderr("No sessions found for this project.");
    return;
  }
  const sortedSessions = sessions.sort(
    (a, b) => new Date(a.startTime).getTime() - new Date(b.startTime).getTime()
  );
  let sessionToDelete;
  const sessionByUuid = sortedSessions.find(
    (session) => session.id === sessionIndex
  );
  if (sessionByUuid) {
    sessionToDelete = sessionByUuid;
  } else {
    const index = parseInt(sessionIndex, 10);
    if (isNaN(index) || index < 1 || index > sessions.length) {
      writeToStderr(
        `Invalid session identifier "${sessionIndex}". Use --list-sessions to see available sessions.`
      );
      return;
    }
    sessionToDelete = sortedSessions[index - 1];
  }
  if (sessionToDelete.isCurrentSession) {
    writeToStderr("Cannot delete the current active session.");
    return;
  }
  try {
    await deleteStoredSession(config2, sessionToDelete.file);
    const time3 = formatRelativeTime(sessionToDelete.lastUpdated);
    writeToStdout(
      `Deleted session ${sessionToDelete.index}: ${sessionToDelete.firstUserMessage} (${time3})`
    );
  } catch (error) {
    writeToStderr(
      `Failed to delete session: ${error instanceof Error ? error.message : "Unknown error"}`
    );
  }
}

// packages/cli/src/utils/terminalTheme.ts
async function setupTerminalAndTheme(config2, settings) {
  let terminalBackground = void 0;
  if (config2.isInteractive() && process.stdin.isTTY) {
    await terminalCapabilityManager.detectCapabilities();
    terminalBackground = terminalCapabilityManager.getTerminalBackgroundColor();
  }
  themeManager.loadCustomThemes(settings.merged.ui.customThemes);
  if (settings.merged.ui.theme) {
    if (!themeManager.setActiveTheme(settings.merged.ui.theme)) {
      debugLogger.warn(
        `Warning: Theme "${settings.merged.ui.theme}" not found.`
      );
    }
  } else {
    const themeName = pickDefaultThemeName(
      terminalBackground,
      themeManager.getAllThemes(),
      DEFAULT_THEME.name,
      "Default Light"
    );
    themeManager.setActiveTheme(themeName);
  }
  config2.setTerminalBackground(terminalBackground);
  themeManager.setTerminalBackground(terminalBackground);
  if (terminalBackground !== void 0 && (settings.merged.ui.autoThemeSwitching ?? true)) {
    const currentTheme = themeManager.getActiveTheme();
    if (!themeManager.isThemeCompatible(currentTheme, terminalBackground)) {
      const backgroundType = getThemeTypeFromBackgroundColor(terminalBackground);
      coreEvents.emitFeedback(
        "warning",
        `Theme '${currentTheme.name}' (${currentTheme.type}) might look incorrect on your ${backgroundType} terminal background. Type /theme to change theme.`
      );
    }
  }
  return terminalBackground;
}

// packages/cli/src/utils/logCleanup.ts
import { promises as fs13 } from "node:fs";
import * as path14 from "node:path";
var RETENTION_PERIOD_MS = 7 * 24 * 60 * 60 * 1e3;
async function cleanupBackgroundLogs(debugMode = false) {
  try {
    const logDir = ShellExecutionService.getLogDir();
    try {
      await fs13.access(logDir);
    } catch {
      return;
    }
    const entries = await fs13.readdir(logDir, { withFileTypes: true });
    const now = Date.now();
    let deletedCount = 0;
    for (const entry of entries) {
      if (entry.isFile() && entry.name.endsWith(".log")) {
        const filePath = path14.join(logDir, entry.name);
        try {
          const stats = await fs13.stat(filePath);
          if (now - stats.mtime.getTime() > RETENTION_PERIOD_MS) {
            await fs13.unlink(filePath);
            deletedCount++;
          }
        } catch (error) {
          if (debugMode) {
            debugLogger.debug(
              `Failed to process log file ${entry.name}:`,
              error
            );
          }
        }
      }
    }
    if (deletedCount > 0 && debugMode) {
      debugLogger.debug(`Cleaned up ${deletedCount} expired background logs.`);
    }
  } catch (error) {
    if (debugMode) {
      debugLogger.warn("Background log cleanup failed:", error);
    }
  }
}

// packages/cli/src/services/SlashCommandConflictHandler.ts
var SlashCommandConflictHandler = class {
  notifiedConflicts = /* @__PURE__ */ new Set();
  pendingConflicts = [];
  flushTimeout = null;
  constructor() {
    this.handleConflicts = this.handleConflicts.bind(this);
  }
  start() {
    coreEvents.on("slash-command-conflicts" /* SlashCommandConflicts */, this.handleConflicts);
  }
  stop() {
    coreEvents.off("slash-command-conflicts" /* SlashCommandConflicts */, this.handleConflicts);
    if (this.flushTimeout) {
      clearTimeout(this.flushTimeout);
      this.flushTimeout = null;
    }
  }
  handleConflicts(payload) {
    const newConflicts = payload.conflicts.filter((c) => {
      const sourceId = c.loserExtensionName || c.loserMcpServerName || c.loserKind;
      const key = `${c.name}:${sourceId}:${c.renamedTo}`;
      if (this.notifiedConflicts.has(key)) {
        return false;
      }
      this.notifiedConflicts.add(key);
      return true;
    });
    if (newConflicts.length > 0) {
      this.pendingConflicts.push(...newConflicts);
      this.scheduleFlush();
    }
  }
  scheduleFlush() {
    if (this.flushTimeout) {
      clearTimeout(this.flushTimeout);
    }
    this.flushTimeout = setTimeout(() => this.flush(), 500);
  }
  flush() {
    this.flushTimeout = null;
    const conflicts = [...this.pendingConflicts];
    this.pendingConflicts = [];
    if (conflicts.length === 0) {
      return;
    }
    const grouped = /* @__PURE__ */ new Map();
    for (const c of conflicts) {
      const list = grouped.get(c.name) ?? [];
      list.push(c);
      grouped.set(c.name, list);
    }
    for (const [name, commandConflicts] of grouped) {
      if (commandConflicts.length > 1) {
        this.emitGroupedFeedback(name, commandConflicts);
      } else {
        this.emitSingleFeedback(commandConflicts[0]);
      }
    }
  }
  /**
   * Emits a grouped notification for multiple conflicts sharing the same name.
   */
  emitGroupedFeedback(name, conflicts) {
    const messages = conflicts.map((c) => {
      const source = this.getSourceDescription(
        c.loserExtensionName,
        c.loserKind,
        c.loserMcpServerName
      );
      return `- ${this.capitalize(source)} '/${c.name}' was renamed to '/${c.renamedTo}'`;
    }).join("\n");
    coreEvents.emitFeedback(
      "info",
      `Conflicts detected for command '/${name}':
${messages}`
    );
  }
  /**
   * Emits a descriptive notification for a single command conflict.
   */
  emitSingleFeedback(c) {
    const loserSource = this.getSourceDescription(
      c.loserExtensionName,
      c.loserKind,
      c.loserMcpServerName
    );
    const winnerSource = this.getSourceDescription(
      c.winnerExtensionName,
      c.winnerKind,
      c.winnerMcpServerName
    );
    coreEvents.emitFeedback(
      "info",
      `${this.capitalize(loserSource)} '/${c.name}' was renamed to '/${c.renamedTo}' because it conflicts with ${winnerSource}.`
    );
  }
  capitalize(s) {
    return s.charAt(0).toUpperCase() + s.slice(1);
  }
  /**
   * Returns a human-readable description of a command's source.
   */
  getSourceDescription(extensionName, kind, mcpServerName) {
    switch (kind) {
      case "extension-file" /* EXTENSION_FILE */:
        return extensionName ? `extension '${extensionName}' command` : "extension command";
      case "skill" /* SKILL */:
        return extensionName ? `extension '${extensionName}' skill` : "skill command";
      case "mcp-prompt" /* MCP_PROMPT */:
        return mcpServerName ? `MCP server '${mcpServerName}' command` : "MCP server command";
      case "user-file" /* USER_FILE */:
        return "user command";
      case "workspace-file" /* WORKSPACE_FILE */:
        return "workspace command";
      case "built-in" /* BUILT_IN */:
        return "built-in command";
      default:
        return "existing command";
    }
  }
};

// packages/cli/src/gemini.tsx
function validateDnsResolutionOrder(order) {
  const defaultValue = "ipv4first";
  if (order === void 0) {
    return defaultValue;
  }
  if (order === "ipv4first" || order === "verbatim") {
    return order;
  }
  debugLogger.warn(
    `Invalid value for dnsResolutionOrder in settings: "${order}". Using default "${defaultValue}".`
  );
  return defaultValue;
}
var DEFAULT_EPT_SIZE = (256 * 1024 * 1024).toString();
function getNodeMemoryArgs(isDebugMode2) {
  const totalMemoryMB = os6.totalmem() / (1024 * 1024);
  const heapStats = v8.getHeapStatistics();
  const currentMaxOldSpaceSizeMb = Math.floor(
    heapStats.heap_size_limit / 1024 / 1024
  );
  const targetMaxOldSpaceSizeInMB = Math.floor(totalMemoryMB * 0.5);
  if (isDebugMode2) {
    debugLogger.debug(
      `Current heap size ${currentMaxOldSpaceSizeMb.toFixed(2)} MB`
    );
  }
  if (process.env["GEMINI_CLI_NO_RELAUNCH"]) {
    return [];
  }
  const args = [];
  const eptFlag = `--max-external-pointer-table-size=${DEFAULT_EPT_SIZE}`;
  const isV8SandboxEnabled = (
    // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-type-assertion
    process.config?.variables?.v8_enable_sandbox === 1
  );
  if (isV8SandboxEnabled && !process.execArgv.some(
    (arg) => arg.startsWith("--max-external-pointer-table-size")
  )) {
    args.push(eptFlag);
  }
  if (targetMaxOldSpaceSizeInMB > currentMaxOldSpaceSizeMb) {
    if (isDebugMode2) {
      debugLogger.debug(
        `Need to relaunch with more memory: ${targetMaxOldSpaceSizeInMB.toFixed(2)} MB`
      );
    }
    args.push(`--max-old-space-size=${targetMaxOldSpaceSizeInMB}`);
  }
  return args;
}
function setupUnhandledRejectionHandler() {
  let unhandledRejectionOccurred = false;
  process.on("unhandledRejection", (reason, _promise) => {
    if (reason instanceof Error && reason.name === "AbortError") {
      debugLogger.log(`Suppressed unhandled AbortError: ${reason.message}`);
      return;
    }
    const errorMessage = `=========================================
This is an unexpected error. Please file a bug report using the /bug tool.
CRITICAL: Unhandled Promise Rejection!
=========================================
Reason: ${reason}${reason instanceof Error && reason.stack ? `
Stack trace:
${reason.stack}` : ""}`;
    debugLogger.error(errorMessage);
    if (!unhandledRejectionOccurred) {
      unhandledRejectionOccurred = true;
      appEvents.emit("open-debug-console" /* OpenDebugConsole */);
    }
  });
}
async function resolveSessionId(resumeArg, sessionIdArg, sessionFileArg) {
  if (!resumeArg && !sessionIdArg && !sessionFileArg) {
    return { sessionId: createSessionId() };
  }
  const storage = new Storage(process.cwd());
  await storage.initialize();
  const sessionSelector = new SessionSelector(storage);
  if (sessionFileArg) {
    try {
      const sessionData = await loadConversationRecord(sessionFileArg);
      if (!sessionData) {
        throw new Error(`File not found or invalid format: ${sessionFileArg}`);
      }
      const now = Date.now();
      const isoNow = new Date(now).toISOString();
      sessionData.messages = (sessionData.messages || []).filter(
        (m) => typeof m === "object" && m !== null && (m.type === "user" || m.type === "gemini") && m.content !== void 0
      );
      sessionData.messages.unshift({
        id: `import-${now}`,
        type: "info",
        content: `Imported session from ${sessionFileArg}`,
        timestamp: isoNow
      });
      const newSessionId = createSessionId();
      sessionData.sessionId = newSessionId;
      sessionData.projectHash = getProjectHash(storage.getProjectRoot());
      sessionData.startTime = isoNow;
      sessionData.lastUpdated = isoNow;
      const chatsDir = path15.join(storage.getProjectTempDir(), "chats");
      const newSessionPath = path15.join(
        chatsDir,
        `session-${now}-${newSessionId.slice(0, 8)}.jsonl`
      );
      const { messages: _messages, ...initialMetadata } = sessionData;
      const lines = [JSON.stringify(initialMetadata)];
      if (sessionData.messages) {
        for (const msg of sessionData.messages) {
          lines.push(JSON.stringify(msg));
        }
      }
      await fsPromises.mkdir(chatsDir, { recursive: true });
      await fsPromises.writeFile(
        newSessionPath,
        lines.join("\n") + "\n",
        "utf-8"
      );
      return {
        sessionId: newSessionId,
        resumedSessionData: {
          conversation: sessionData,
          filePath: newSessionPath
        }
      };
    } catch (error) {
      coreEvents.emitFeedback(
        "error",
        `Error importing session from file: ${error instanceof Error ? error.message : "Unknown error"}`
      );
      await runExitCleanup();
      process.exit(ExitCodes.FATAL_INPUT_ERROR);
    }
  }
  if (sessionIdArg) {
    if (await sessionSelector.sessionExists(sessionIdArg)) {
      coreEvents.emitFeedback(
        "error",
        `Error starting session: Session ID "${sessionIdArg}" already exists. Use --resume to resume it, or provide a different ID.`
      );
      await runExitCleanup();
      process.exit(ExitCodes.FATAL_INPUT_ERROR);
    }
    return { sessionId: sessionIdArg };
  }
  try {
    const { sessionData, sessionPath } = await sessionSelector.resolveSession(
      resumeArg
    );
    return {
      sessionId: sessionData.sessionId,
      resumedSessionData: { conversation: sessionData, filePath: sessionPath }
    };
  } catch (error) {
    if (error instanceof SessionError && error.code === "NO_SESSIONS_FOUND") {
      if (resumeArg === RESUME_LATEST) {
        coreEvents.emitFeedback("warning", error.message);
        return { sessionId: createSessionId() };
      }
    }
    coreEvents.emitFeedback(
      "error",
      `Error resuming session: ${error instanceof Error ? error.message : "Unknown error"}`
    );
    await runExitCleanup();
    process.exit(ExitCodes.FATAL_INPUT_ERROR);
  }
}
async function startInteractiveUI(config2, settings, startupWarnings, workspaceRoot = process.cwd(), resumedSessionData, initializationResult) {
  const { startInteractiveUI: doStartUI } = await import("./interactiveCli-JTPPDTTX.js");
  await doStartUI(
    config2,
    settings,
    startupWarnings,
    workspaceRoot,
    resumedSessionData,
    initializationResult
  );
}
async function main() {
  let config2;
  const cliStartupHandle = startupProfiler.start("cli_startup");
  const adminControlsListner = setupAdminControlsListener();
  registerCleanup(adminControlsListner.cleanup);
  const cleanupStdio = patchStdio();
  registerSyncCleanup(() => {
    initializeOutputListenersAndFlush(config2);
    cleanupStdio();
  });
  setupUnhandledRejectionHandler();
  setupSignalHandlers();
  const slashCommandConflictHandler = new SlashCommandConflictHandler();
  slashCommandConflictHandler.start();
  registerCleanup(() => slashCommandConflictHandler.stop());
  const loadSettingsHandle = startupProfiler.start("load_settings");
  const settings = loadSettings();
  loadSettingsHandle?.end();
  const requestedWorktree = getRequestedWorktreeName(settings);
  let worktreeInfo;
  if (requestedWorktree !== void 0) {
    const worktreeHandle = startupProfiler.start("setup_worktree");
    worktreeInfo = await setupWorktree(requestedWorktree || void 0);
    worktreeHandle?.end();
  }
  const cleanupOpsHandle = startupProfiler.start("cleanup_ops");
  Promise.all([
    cleanupCheckpoints(),
    cleanupToolOutputFiles(settings.merged),
    cleanupBackgroundLogs()
  ]).catch((e) => {
    debugLogger.error("Early cleanup failed:", e);
  }).finally(() => {
    cleanupOpsHandle?.end();
  });
  const parseArgsHandle = startupProfiler.start("parse_arguments");
  const argvPromise = parseArguments(settings.merged).finally(() => {
    parseArgsHandle?.end();
  });
  const rawStartupWarningsPromise = getStartupWarnings();
  settings.errors.forEach((error) => {
    coreEvents.emitFeedback("warning", error.message);
  });
  const trustedFolders = loadTrustedFolders();
  trustedFolders.errors.forEach((error) => {
    coreEvents.emitFeedback(
      "warning",
      `Error in ${error.path}: ${error.message}`
    );
  });
  const argv = await argvPromise;
  const { sessionId, resumedSessionData } = await resolveSessionId(
    argv.resume,
    argv.sessionId,
    argv.sessionFile
  );
  if (argv.allowedTools && argv.allowedTools.length > 0 || settings.merged.tools?.allowed && settings.merged.tools.allowed.length > 0) {
    coreEvents.emitFeedback(
      "warning",
      "Warning: --allowed-tools cli argument and tools.allowed in settings.json are deprecated and will be removed in 1.0: Migrate to Policy Engine: https://geminicli.com/docs/core/policy-engine/"
    );
  }
  if (settings.merged.tools?.exclude && settings.merged.tools.exclude.length > 0) {
    coreEvents.emitFeedback(
      "warning",
      "Warning: tools.exclude in settings.json is deprecated and will be removed in 1.0. Migrate to Policy Engine: https://geminicli.com/docs/core/policy-engine/"
    );
  }
  if (argv.startupMessages) {
    argv.startupMessages.forEach((msg) => {
      coreEvents.emitFeedback("info", msg);
    });
  }
  if (argv.promptInteractive && !process.stdin.isTTY) {
    writeToStderr(
      "Error: The --prompt-interactive flag cannot be used when input is piped from stdin.\n"
    );
    await runExitCleanup();
    process.exit(ExitCodes.FATAL_INPUT_ERROR);
  }
  const isDebugMode2 = isDebugMode(argv);
  const consolePatcher = new ConsolePatcher({
    stderr: argv.isCommand ? false : true,
    interactive: isHeadlessMode() && !argv.isCommand ? false : true,
    debugMode: isDebugMode2,
    onNewMessage: (msg) => {
      coreEvents.emitConsoleLog(msg.type, msg.content);
    }
  });
  consolePatcher.patch();
  dns.setDefaultResultOrder(
    validateDnsResolutionOrder(settings.merged.advanced.dnsResolutionOrder)
  );
  if (!settings.merged.security.auth.selectedType || settings.merged.security.auth.selectedType === "cloud-shell" /* LEGACY_CLOUD_SHELL */) {
    if (process.env["CLOUD_SHELL"] === "true" || process.env["GEMINI_CLI_USE_COMPUTE_ADC"] === "true") {
      settings.setValue(
        "User" /* User */,
        "security.auth.selectedType",
        "compute-default-credentials" /* COMPUTE_ADC */
      );
    }
  }
  const partialConfig = await loadCliConfig(settings.merged, sessionId, argv, {
    projectHooks: settings.workspace.settings.hooks,
    skipExtensions: true,
    loadedSettings: settings
  });
  adminControlsListner.setConfig(partialConfig);
  let initialAuthFailed = false;
  if (!settings.merged.security.auth.useExternal && !argv.isCommand) {
    try {
      if (partialConfig.isInteractive() && settings.merged.security.auth.selectedType) {
        const err = await validateAuthMethod(
          settings.merged.security.auth.selectedType
        );
        if (err) {
          throw new Error(err);
        }
        await partialConfig.refreshAuth(
          settings.merged.security.auth.selectedType
        );
      } else if (!partialConfig.isInteractive()) {
        const authType = await validateNonInteractiveAuth(
          settings.merged.security.auth.selectedType,
          settings.merged.security.auth.useExternal,
          partialConfig,
          settings
        );
        await partialConfig.refreshAuth(authType);
      }
    } catch (err) {
      if (err instanceof ValidationCancelledError) {
        await runExitCleanup();
        process.exit(ExitCodes.SUCCESS);
      }
      if (!(err instanceof ValidationRequiredError)) {
        debugLogger.error("Error authenticating:", err);
        initialAuthFailed = true;
      }
    }
  }
  const remoteAdminSettings = partialConfig.getRemoteAdminSettings();
  if (remoteAdminSettings) {
    settings.setRemoteAdminSettings(remoteAdminSettings);
    if (process.send) {
      process.send({
        type: "admin-settings-update",
        settings: remoteAdminSettings
      });
    }
  }
  await runDeferredCommand(settings.merged);
  if (!process.env["SANDBOX"] && !argv.isCommand) {
    const memoryArgs = settings.merged.advanced.autoConfigureMemory ? getNodeMemoryArgs(isDebugMode2) : [];
    const sandboxConfig = await loadSandboxConfig(settings.merged, argv);
    if (sandboxConfig) {
      if (initialAuthFailed) {
        await runExitCleanup();
        process.exit(ExitCodes.FATAL_AUTHENTICATION_ERROR);
      }
      let stdinData = "";
      if (!process.stdin.isTTY) {
        stdinData = await readStdin();
      }
      const injectStdinIntoArgs = (args, stdinData2) => {
        const finalArgs = [...args];
        if (stdinData2) {
          const promptIndex = finalArgs.findIndex(
            (arg) => arg === "--prompt" || arg === "-p"
          );
          if (promptIndex > -1 && finalArgs.length > promptIndex + 1) {
            finalArgs[promptIndex + 1] = `${stdinData2}

${finalArgs[promptIndex + 1]}`;
          } else {
            finalArgs.push("--prompt", stdinData2);
          }
        }
        return finalArgs;
      };
      const sandboxArgs = injectStdinIntoArgs(process.argv, stdinData);
      await relaunchOnExitCode(
        () => start_sandbox(sandboxConfig, memoryArgs, partialConfig, sandboxArgs)
      );
      await runExitCleanup();
      process.exit(ExitCodes.SUCCESS);
    }
  }
  {
    const loadConfigHandle = startupProfiler.start("load_cli_config");
    config2 = await loadCliConfig(settings.merged, sessionId, argv, {
      projectHooks: settings.workspace.settings.hooks,
      worktreeSettings: worktreeInfo,
      loadedSettings: settings
    });
    loadConfigHandle?.end();
    await config2.storage.initialize();
    adminControlsListner.setConfig(config2);
    if (config2.isInteractive() && settings.merged.general.devtools) {
      const { setupInitialActivityLogger } = await import("./devtoolsService-RMCGNCQO.js");
      setupInitialActivityLogger(config2);
    }
    registerTelemetryConfig(config2);
    const policyEngine = config2.getPolicyEngine();
    const messageBus = config2.getMessageBus();
    createPolicyUpdater2(policyEngine, messageBus, config2.storage);
    registerCleanup(async () => {
      await config2?.getHookSystem()?.fireSessionEndEvent("exit" /* Exit */);
    });
    if (!config2.getAcpMode()) {
      registerCleanup(consolePatcher.cleanup);
    }
    cleanupExpiredSessions(config2, settings.merged).catch((e) => {
      debugLogger.error("Failed to cleanup expired sessions:", e);
    });
    if (config2.getListExtensions()) {
      debugLogger.log("Installed extensions:");
      for (const extension of config2.getExtensions()) {
        debugLogger.log(`- ${extension.name}`);
      }
      await runExitCleanup();
      process.exit(ExitCodes.SUCCESS);
    }
    if (config2.getListSessions()) {
      const authType2 = settings.merged.security.auth.selectedType;
      if (authType2) {
        try {
          await config2.refreshAuth(authType2);
        } catch (e) {
          debugLogger.debug(
            "Auth failed for --list-sessions, summaries may not be generated:",
            e
          );
        }
      }
      await listSessions(config2);
      await runExitCleanup();
      process.exit(ExitCodes.SUCCESS);
    }
    const sessionToDelete = config2.getDeleteSession();
    if (sessionToDelete) {
      await deleteSession(config2, sessionToDelete);
      await runExitCleanup();
      process.exit(ExitCodes.SUCCESS);
    }
    const wasRaw = process.stdin.isRaw;
    if (config2.isInteractive() && !wasRaw && process.stdin.isTTY) {
      process.stdin.setRawMode(true);
      registerSyncCleanup(() => {
        process.stdin.setRawMode(wasRaw);
      });
    }
    const terminalHandle = startupProfiler.start("setup_terminal");
    await setupTerminalAndTheme(config2, settings);
    terminalHandle?.end();
    const initAppHandle = startupProfiler.start("initialize_app");
    const initializationResult = await initializeApp(config2, settings);
    initAppHandle?.end();
    import("./liteRtServerManager-PKYX347H.js").then(({ LiteRtServerManager }) => {
      const mergedGemma = settings.merged.experimental?.gemmaModelRouter;
      if (!mergedGemma) return;
      const userGemma = settings.forScope("User" /* User */).settings.experimental?.gemmaModelRouter;
      return LiteRtServerManager.ensureRunning({
        ...mergedGemma,
        binaryPath: userGemma?.binaryPath,
        autoStartServer: userGemma?.autoStartServer
      });
    }).catch((e) => debugLogger.warn("LiteRT auto-start import failed:", e));
    if (settings.merged.security.auth.selectedType === "oauth-personal" /* LOGIN_WITH_GOOGLE */ && config2.isBrowserLaunchSuppressed()) {
      await getOauthClient(settings.merged.security.auth.selectedType, config2);
    }
    if (config2.getAcpMode()) {
      return runAcpClient(config2, settings, argv);
    }
    let input = config2.getQuestion();
    const useAlternateBuffer = shouldEnterAlternateScreen(
      config2.getUseAlternateBuffer(),
      config2.getScreenReader()
    );
    const rawStartupWarnings = await rawStartupWarningsPromise;
    const startupWarnings = [
      ...rawStartupWarnings.map((message) => ({
        id: `startup-${createHash2("sha256").update(message).digest("hex").substring(0, 16)}`,
        message,
        priority: "high" /* High */
      })),
      ...await getUserStartupWarnings(settings.merged, void 0, {
        isAlternateBuffer: useAlternateBuffer
      })
    ];
    cliStartupHandle?.end();
    if (!config2.isInteractive()) {
      for (const warning of startupWarnings) {
        writeToStderr(warning.message + "\n");
      }
    }
    if (config2.isInteractive()) {
      if (process.stdin.isTTY) {
        process.stdin.resume();
      }
      await startInteractiveUI(
        config2,
        settings,
        startupWarnings,
        process.cwd(),
        resumedSessionData,
        initializationResult
      );
      return;
    }
    await config2.initialize();
    startupProfiler.flush(config2);
    let stdinData = void 0;
    if (!process.stdin.isTTY) {
      stdinData = await readStdin();
      if (stdinData) {
        input = input ? `${stdinData}

${input}` : stdinData;
      }
    }
    const sessionStartSource = resumedSessionData ? "resume" /* Resume */ : "startup" /* Startup */;
    const hookSystem = config2?.getHookSystem();
    if (hookSystem) {
      const result = await hookSystem.fireSessionStartEvent(sessionStartSource);
      if (result) {
        if (result.systemMessage) {
          writeToStderr(result.systemMessage + "\n");
        }
        const additionalContext = result.getAdditionalContext();
        if (additionalContext) {
          const wrappedContext = `<hook_context>${additionalContext}</hook_context>`;
          input = input ? `${wrappedContext}

${input}` : wrappedContext;
        }
      }
    }
    if (!input) {
      debugLogger.error(
        `No input provided via stdin. Input can be provided by piping data into gemini or using the --prompt option.`
      );
      await runExitCleanup();
      process.exit(ExitCodes.FATAL_INPUT_ERROR);
    }
    const prompt_id = sessionId;
    logUserPrompt(
      config2,
      new UserPromptEvent(
        input.length,
        prompt_id,
        config2.getContentGeneratorConfig()?.authType,
        input
      )
    );
    const authType = await validateNonInteractiveAuth(
      settings.merged.security.auth.selectedType,
      settings.merged.security.auth.useExternal,
      config2,
      settings
    );
    await config2.refreshAuth(authType);
    if (config2.getDebugMode()) {
      debugLogger.log("Session ID: %s", sessionId);
    }
    initializeOutputListenersAndFlush(config2);
    await runNonInteractive2({
      config: config2,
      settings,
      input,
      prompt_id,
      resumedSessionData
    });
    await runExitCleanup();
    process.exit(ExitCodes.SUCCESS);
  }
}
function initializeOutputListenersAndFlush(config2) {
  if (coreEvents.listenerCount("output" /* Output */) === 0) {
    coreEvents.on("output" /* Output */, (payload) => {
      if (payload.isStderr) {
        writeToStderr(payload.chunk, payload.encoding);
      } else {
        writeToStdout(payload.chunk, payload.encoding);
      }
    });
  }
  if (coreEvents.listenerCount("console-log" /* ConsoleLog */) === 0) {
    coreEvents.on("console-log" /* ConsoleLog */, (payload) => {
      if (payload.type === "error" || payload.type === "warn") {
        writeToStderr(payload.content + "\n");
      } else {
        writeToStderr(payload.content + "\n");
      }
    });
  }
  if (coreEvents.listenerCount("user-feedback" /* UserFeedback */) === 0) {
    coreEvents.on("user-feedback" /* UserFeedback */, (payload) => {
      writeToStderr(payload.message + "\n");
    });
  }
  const outputFormat = config2?.getOutputFormat();
  const forceToStderr = outputFormat === "json";
  coreEvents.drainBacklogs(
    (event, args) => {
      if (forceToStderr && event === "output" /* Output */) {
        const payload = args[0];
        if (!payload.isStderr) {
          return {
            event,
            // eslint-disable-next-line @typescript-eslint/no-unsafe-type-assertion
            args: [{ ...payload, isStderr: true }]
          };
        }
      }
      return { event, args };
    }
  );
}
function setupAdminControlsListener() {
  let pendingSettings;
  let config2;
  const messageHandler = (msg) => {
    const message = msg;
    if (message?.type === "admin-settings" && message.settings) {
      if (config2) {
        config2.setRemoteAdminSettings(message.settings);
      } else {
        pendingSettings = message.settings;
      }
    }
  };
  process.on("message", messageHandler);
  return {
    setConfig: (newConfig) => {
      config2 = newConfig;
      if (pendingSettings) {
        config2.setRemoteAdminSettings(pendingSettings);
      }
    },
    cleanup: () => {
      process.off("message", messageHandler);
    }
  };
}
export {
  getNodeMemoryArgs,
  initializeOutputListenersAndFlush,
  main,
  resolveSessionId,
  setupUnhandledRejectionHandler,
  startInteractiveUI,
  validateDnsResolutionOrder
};
/**
 * @license
 * Copyright 2025 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */
/*! Bundled license information:

yargs-parser/build/lib/string-utils.js:
  (**
   * @license
   * Copyright (c) 2016, Contributors
   * SPDX-License-Identifier: ISC
   *)

yargs-parser/build/lib/tokenize-arg-string.js:
  (**
   * @license
   * Copyright (c) 2016, Contributors
   * SPDX-License-Identifier: ISC
   *)

yargs-parser/build/lib/yargs-parser-types.js:
  (**
   * @license
   * Copyright (c) 2016, Contributors
   * SPDX-License-Identifier: ISC
   *)

yargs-parser/build/lib/yargs-parser.js:
  (**
   * @license
   * Copyright (c) 2016, Contributors
   * SPDX-License-Identifier: ISC
   *)

yargs-parser/build/lib/index.js:
  (**
   * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js
   * CJS and ESM environments.
   *
   * @license
   * Copyright (c) 2016, Contributors
   * SPDX-License-Identifier: ISC
   *)
*/
